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
}

--

--

--

Starting a tech bootcamp

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Most Simple React Hook Example

Svelte Slicer

Introduction to Application Frameworks

How to Level Up and Use Auto Formatting to Do Less Work

Deep Dive into ES6 Array Destructuring

18 Types Of Programmers On Earth

eating food in office

Not another ReactJS Hooks post

Monitor and handle exceptions like a boss in Angularjs

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
Jesse Chung

Jesse Chung

Starting a tech bootcamp

More from Medium

Straight forward implementation of global state in React, with independently updated target…

React Project: Flags Of The World

Procedural Restructuring of Fetch Data in React.js

Recipeez -React Final Project