Why using the setState method in React doesn’t mutate the state immediately?

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?

  1. 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store