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.