Categories
React Answers

How to use setState callback on React hooks?

Spread the love

To use setState callback on React hooks, we can use the useEffect hook.

For instance, we write

function Comp() {
  const [counter, setCounter] = useState(0);

  const doSomething = () => {
    setCounter(123);
  };

  useEffect(() => {
    console.log("Do something after counter has changed", counter);
  }, [counter]);

  //..
}

to create the counter state with useState.

Then we watch the counter state for changes with the useEffect hook called with [counter] as the 2nd argument.

The useEffect callback will run whenever counter changes.

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 *