React useState Callbacks: How to Run Code After Updating State

React useState Callbacks: How to Run Code After Updating State


2 min read

The useState hook is a basic building block for state management in React.

Using the hook is pretty straightforward. The function returns a tuple with the current state and a function to update the state. Here's a basic example:

In this example, we're managing state for a comment variable. We use the state to populate the input and then use the setComment state updater to update the state when the input changes (i.e. you type into the input field).


So managing state seems pretty easy, but what if you want to run some code whenever your state changes? Luckily React has you covered!

The useEffect hook runs when its dependencies change

We can use the useEffect hook for this exact purpose. The hook takes a list of dependencies as its second argument and executes the effect whenever a dependency changes.

In other words, you can pass the state variable to the dependency list and execute your code in the effect.

Here's what that might look like:

This time, as you type into the input above, there's an effect that runs anytime the comment variable updates. This effect logs the input field's value every time it changes. This is a pretty basic example, but it shows you how to run code when your state changes.

Combining useState and useEffect in React can be super helpful!

These hooks make it easy to manage state and run code when things change. With these tools, you can build apps that work well and do what you expect. It's simple and effective!