reactjsreact-hooks

Infinite loop in useEffect


I've been playing around with the new hook system in React 16.7-alpha and get stuck in an infinite loop in useEffect when the state I'm handling is an object or array.

First, I use useState and initiate it with an empty object like this:

const [obj, setObj] = useState({});

Then, in useEffect, I use setObj to set it to an empty object again. As a second argument I'm passing [obj], hoping that it wont update if the content of the object hasn't changed. But it keeps updating. I guess because no matter the content, these are always different objects making React thinking it keep changing?

useEffect(() => {
  setIngredients({});
}, [ingredients]);

The same is true with arrays, but as a primitive it wont get stuck in a loop, as expected.

Using these new hooks, how should I handle objects and array when checking weather the content has changed or not?


Solution

  • Passing an empty array as the second argument to useEffect makes it only run on mount and unmount, thus stopping any infinite loops.

    useEffect(() => {
      setIngredients({});
    }, []);
    

    This was clarified to me in the blog post on React hooks at https://www.robinwieruch.de/react-hooks/