How to listen for state changes in React?

Sometimes, we want to listen for state changes in React.

In this article, we’ll look at how to listen for state changes in React.

How to listen for state changes in React?

To listen for state changes in React, we use the useEffect hook.

For instance, we write

export function MyComponent(props) {
  const [myState, setMystate] = useState("initialState");

  useEffect(() => {
    console.log(myState);
  }, [myState]);
  //...
}

to create the MyComponent component.

In it, we define the myState state.

And we watch it for changes with

useEffect(() => {
  console.log(myState);
}, [myState]);

We call the useEffect hook with a callback that logs the latest value of myState.

And we use [myState] as the 2nd argument to watch myState for changes.

Conclusion

To listen for state changes in React, we use the useEffect hook.