In this article, we will see what happens if we update or set state inside the react useEffect.

In react, we create the state using the useState() hook. Following is the syntax.

const [state, setState] = useState({});

In the above example, the “state” is the state variable and “setState” is the callback used to update the “state” variable.

However, following are the some of the key points to keep in mind when updating a state inside the useEffect:

  1. Calling setState() inside useEffect() can cause infinite loop of re-renders, leads to performance issues and unexpected behavior.
  2. The infinite loop or infinite rendering can be avoided by using dependencies array when updating a state inside the useEffect. In such a case the useEffect() hook only runs when the specified dependencies change.
  3. Updating a state inside the useEffect() can be really helpful when updating the state based on asynchronous data or using props to update the state.
  4. Note that, It is critical to carefully manage dependencies and avoid infinite loops when using setState() inside useEffect().

Following is the example of using setState() inside useEffect():

function ExampleComponent(props) {
  const [state, setState] = useState({});

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

  return <div>{state.foo}</div>;
}

In the above example, we’re using the useEffect() hook to update the component’s state based on the value of the props.bar prop.

props.bar is being passed as a dependency to useEffect() to ensure that the effect only runs when the prop changes. When props.bar changes, the useEffect() hook will run, and setState() will update the component’s state, causing a re-render.

Categorized in:

Tagged in: