React Hooks infinite loop with Array

Viewed 1134

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]);
3 Answers

you have added series depandancy in hooks and you'r updating series so whenever series update that hook is called . so, it is goes into infinite .

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

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".

[1,2,3]!==[1,2,3] while "123"==="123" when you set the array as a dependency and use THAT array as a state, the array "change" everything when setSeries which in turn trigger render in turn trigger useEffect which in turn trigger setSeries so on and so forth

Related