Categories
React Answers

How to Set State Inside a React useEffect Hook Callback?

Spread the love

Sometimes, we want to set states inside the React useEffect hook callback.

In this article, we’ll look at how to set states inside the React useEffect hook callback.

Set State Inside a useEffect Hook

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

For instance, we write:

useEffect(() => {
  setState(state => ({ ...state, foo: props.foo }));
}, [props.foo]);

useEffect(() => {
  setState(state => ({ ...state, bar: props.bar }));
}, [props.bar]);

We watch the props properties by passing them into the array.

Then we merge the items into the state object that we return in the callback.

Conclusion

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

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 *