Recently I was working on developing a react component where on updating state I had to make a fetch call which used one of the state properties as a URL parameter and I ran into some trouble which led me to read about setState() method in depth.
this.setState({ userType: 'vendor'});
fetch(`${BASE_URL}/${this.state.userType}`)
.then((data) => { console.log(data)
});
So according to fetch call made using the above code, I should have made call to URL with type vendor in it but it turns out that value of userType property wasn't updated despite the setState call made previous to the fetch call.
So I visited React official documentation and there I found that setState method is asynchronous in nature. This revelation led me to read about setState method in detail and I found below 3 ways of using this method.
1. Normal mode
this.setState({ userType: 'vendor' });
In this mode object passed to setState method is shallow merged in current state object.
2. Functional mode
this.setState((state, props) => {
return {
xCoordinate: state.xCoordinate + 1
}
});
In this mode, we pass a function to setState method that receives the state and props which refer to the component's state and props at the time the change is being applied and this function computes the new state object which gets shallow merged to current state object.
Use cases
If we want to update state based on some previous state values, this mode might help us.
Classic example would be toggling functionality.
this.setState((state) => {
return {
isOpen: !state.isOpen
}
});
- Useful in creating Animations, Games, Dynamic Visualizations etc
3. Updater mode
this.setState({ userType: 'vendor'}, () => {
fetch(`${BASE_URL}/${this.state.userType}`)
.then((data) => {
console.log(data)
});
});
According to React documentation,
The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.
This mode helped me to solve the problem that I was facing at the beginning of the article.
Use cases
- If we want to access state values as soon as they are updated.
Parting Notes
Though setState method solves the problem it was designed to solve, we can improve it syntactically by providing promisified version of it as it is already asynchronous in nature.
Something like this:
this.setState({ x: 'abc' }).then((currentState) => {
// currentState holds the new state after we make updates to it
});
Thanks for taking the time to read this. I'd love some feedback. Please share your experiences with using setState in comments and like and share this post if you liked reading it.
Top comments (0)