How to run code after React hooks state variable is updated?

Sometimes, we want to run code after React hooks state variable is updated.

In this article, we’ll look at how to run code after React hooks state variable is updated.

How to run code after React hooks state variable is updated?

To run code after React hooks state variable is updated, we can watch the state’s value with the useEffect callback and run code when the value we’re looking for is set.

For instance, we write:

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

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

  useEffect(() => {
    if (count === 5) {
      console.log("you win");
    }
  }, [count]);

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

We define the count state with the useState hook.

Then we add a button that calls setCount to increment the count when we click on it.

Then we add the useEffect callback that watches count‘s value and log 'you win' when count is 5.

Conclusion

To run code after React hooks state variable is updated, we can watch the state’s value with the useEffect callback and run code when the value we’re looking for is set.