Why using the setState method in React doesn’t mutate the state immediately?
1 min readApr 11, 2021
The reason is setState is asynchronous, you can’t expect the updated state just after the setState, if you want to check the value use a callback method. Pass a method as a callback that will be get executed after the setState completes its task.
Why setState is asynchronous?
This is because setState alters the state and causes re-rendering. It can be an expensive operation and making it synchronous might leave the browser unresponsive. Thus, the setState calls are asynchronous as well as batched for better User experience and performance
How to use the setState with a callback?
- In React class-based components, to check the updated state value just after the setState, use a callback method like this:
this.setState({ key: value }, () => {
console.log('updated state value', this.state.key)
})
2. In a functional component (using useState hook), checking the updated state in a useEfftect hook:
const [beerCount, setBeerCount] = useState(0);
useEffect(() => {
console.log("count updated! this is run after update!");
}, [beerCount]); // run whenever beerCount is changed
- Vietnamese Ver (Phiên bản tiếng Việt): updating…
- Refs:
https://reactjs.org/docs/react-component.html#setstate
https://stackoverflow.com/a/42593250