React state not updating immediately?

The reason why the state doesn’t update immediately is because for each render, the state is immutable.

You can see that …

const [someState, setSomeState] = useState()

…are both constants values ! So they’re immutable. The state remains constant inside the render but can be changed between two renders. The same goes for dispatch and useReducer.

we could go further and ask us the question, but why are they immutable? Why isn’t it just let? There are probably plenty of reasons why the React team decided this, for performance reasons, has to work for concurrent mode etc etc… but this is as deep as this article goes.

capture the new value and use it again

In most cases this solution is enough to solve your problem. Let’s take an example where you’d want to fetch data based on the value you’ve just updated.

//Instead of this:function onChange(){
setCount(count + 1);
getData(count);
//here count is not equal to the state
//you just set, it's the previous state
}
//Do this:
function onChange(){
const newCount = count + 1;
setCount(newCount);
getData(newCount);
//now you can be sure you call getData
//with the state you just set
}

--

--

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