React state does not update immediately!? This is how to do it.

Vinod Lakshan
2 min readMay 25, 2022

--

When you update the React state using SetState and immediately try to use the modified value, it still shows the previous value! Here’s why! and how to use the modified value immediately.

Why ?

Initiating a state

As you can see these are constants! So the React state is immutable for each render. However, it can be altered between different renders.

React’s state object is not directly modified by SetState. Instead, it creates queue to update the state object of a component. So the React state updates in an asynchronous manner for performance reasons.

Capture the modified state and use immediately

In this case, we can utilize React useEffect hook. It does accept a call back function and a dependency list to perform side effects and actions.

So instead of doing this,

Without using useEffect hook

You can use the modified state immediately like this,

With using useEffect hook

If the list of dependencies is empty, the useEffect hook will execute only once. Since count state is now a dependency (Line 11), this useEffect hook will execute whenever count state is modified.

Ensure that none of the dependencies will be modified within the useEffect hook or the methods that are used in the useEffect hook. Otherwise, the useEffect hook will execute indefinitely since it continues to monitor changes to the dependency list.

--

--

Vinod Lakshan

Software Engineer | discuss about coding challenges that arise in day to day work