Search code examples
reactjsreact-hooksinfinite-loop

React Hooks infinite loop with Array


I'm having an infinite loop when I assign an array to a state in a useEffect hook in React and I'm not sure why as I'm adding the state series as a dependency.

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, [series]);

The same code with a string doesn't create an infinite loop

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries('No Infinite Loop');
}, [series]);

Solution

  • React does shallow equality check when it comes to state, unless defined otherwise. When you do this setSeries([1, 2, 3, 4]);, you create the array [1, 2, 3, 4] every single time this effect is called, and since your useEffect depends on series, it will be called infinitly.

    On the other hand, shallow comparing of the strings will not cause infinite loop as they are "shallow equal".