Performing an action with state after setting  state (useState)

Performing an action with state after setting state (useState)

In react functional components, state is managed by the useState hook. This hook returns an array of two elements. One is the state, and the second element is the state setter function.

One major caveat of the state setter function is that it is asynchronous. Meaning that it doesn't complete its operation instantaneously. Therefore, trying to access the new state immediately after setting the state's value might be quite a headache.

import React, { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount((prev) => prev + 1);
    console.log(count);
  };

  return (
    <div>
      <h1>COUNTER</h1>
      <button onClick={incrementCount}>INCR</button>
    </div>
  );
};

export default Counter;

If you run the above code, you will notice that when you click the button to call the increment count function, the value 0 is logged to the console. The state changed but JavaScript didn't wait, for the setCount function to be executed before proceeding with the console.log(...). Things like this can cause unwanted behaviour in our code.

To tackle this, all we need to do is make use of the useEffect hook. The useEffect hook can be used to watch the value of certain variables or state and then perform an action based on that. So what we do here is pass the state we want to be watched into the useEffect's dependency array, then perform our desired action in the callback of the useEffect.

Here's what I mean:

  const incrementCount = () => {
    setCount((prev) => prev + 1);
  };

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

This way, console.log(count) only runs after the value of count has been successfully mutated.

If you have any more questions about this article or the useState hook, please be free to ask me in the comments section. Follow me for more tips and tutorials regarding Web development.