Categories
React

How to Use the setState Callback with React Hooks?

Spread the love

When we’re using class-based components, we can pass in a callback as the 2nd argument of the setState method to run code after a state has been updated.

Since we moved to using hooks to create components, we’ve to use the useState hook to create and update states.

The state setter function doesn’t take a callback as a second argument to let us run code after a state is updated.

Therefore, we must find a new way to run code after a state is updated.

In this article, we’ll look at how to run code after a state has been updated.

Use the useEffect Hook

To run code after a state is updated, we can use the useEffect hook to watch the value of a state and run code accordingly.

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>
  );
}

to watch the value of the count state with the useEffect hook.

We pass in count to the array in the 2nd argument to watch its value.

Now when we click on the increment button to update the count , the useEffect callback will run.

The same thing works for props since they also trigger a re-render of the component.

Conclusion

To run code after a state is changed, we can use the useEffect hook with an array of state or props we want to watch for changes for.

Then the useEffect callback will run when any of the values in the array 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 *