When the following code is run in a React component, it causes an endless loop. Why does passing an array as a dependency to useEffect
(in this case, args
), cause that to happen? How can I stop the endless loop from happening? The code should only run once.
I've read that I can use [args.length]
to stop this from happening, but then the ESLint rule react-hooks/exhaustive-deps
throws an error, so I want to avoid doing it that way.
import React, { useEffect, useState } from 'react';
export default function Home() {
const args = ['a'];
const [value, setValue] = useState(['b']);
useEffect(() => {
setValue(['c']);
}, [args]);
console.log('value', value);
}
Notice in the code above, that I don't even use or modify args
at all, in the useEffect
callback.
If I change the value of args
to a string, like const args = 'a'
, then there is no endless loop. So the problem seems to occur when the dependency is an array.