Categories
React

What’s the React Hooks Equivalent of the setState Callback?

Spread the love

If we use React hooks to create components, we can no longer use setState to set our state.

Instead, we’ve to use the state setter function returned from the useState hook.

However, the setState method takes a second argument that lets us run code after a state is set.

There’s no way to do this directly with state setter functions.

However, we can fix this by writing their hooks equivalent.

In this article, we’ll look at the React Hooks equivalent of the setState callback.

React Hooks Equivalent of the setState Callback

The React hooks equivalent of the setState callback is the useEffect hook.

The useEffect hook lets us watch the change of a state.

To watch a state’s value, we can write:

import { useEffect, useState } from "react";

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

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

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

We create the count state that stores a number.

Then we add the useEffect hook with a callback that runs when the count state changes.

It runs when count state changes because count is passed into an array in the 2nd argument of useEffect .

The count state is updated when we click on the increment button.

This is because we passed a function into the onClick hook.

The function calls setCount with a callback that returns the current value of count increased by 1.

Therefore, when we click on the increment button, the console.log in the useEffect callback will run.

Conclusion

We can create a React hooks equivalent of the setState callback by using the useEffect hook with an array of the states we want to watch in the 2nd argument.

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 *