React state not updating immediately?

Jesse Chung
1 min readJan 26, 2022

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
}

--

--