Categories
React

How to Make the React useState Hook Setter Function Reflect Changes Immediately?

Spread the love

Sometimes, we may see that the state changes we made with the useState hook’s state setter function doesn’t reflect at the time we expect them to.

In this article, we’ll look at how to make the React useState hook’s state setter function gets reflected when we want it.

Using the useState State Setter Function Properly

To make sure we pick the latest changes to a state after a usetState state setter function is run, we should watch the latest value of the state with the useEffect hook.

For instance, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log(count);
  }, [count]);

  return (
    <div className="App">
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <p>{count}</p>
    </div>
  );
}

We call the useState hook to return the setCount function to set the state.

And we call setCount with a callback that takes the previous state value and return the new state value based on that.

The useEffect callback runs when count ‘s value is changed.

So we can see the latest value of count logged in the useEffect callback.

When we click on the increment button, we show the value of count .

We’ve to use the useEffect hook to watch the state value because React’s useState state setter function is async.

The array we pass in as the 2nd argument of useEffect has the state or prop values we want to watch.

Therefore, we can’t get the value of count right after calling the setCount function.

The state setter function will trigger a re-render when it’s called.

And the latest value of count will be available after the next render.

Conclusion

To get the latest value of a state and do something with it, we’ve to use the useEffect hook with a callback and the array of values we want to watch.

Then in the useEffect callback, we get the latest value of whatever we’re watching.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *