I am trying to trigger the useEffect hook only when a specific element in an array changes. Right now, I have something similar to this:
const [array, setArray] = useState(["someText", "someOthersText"]);
useEffect(()=>{
// some function to run
}, [array[0]])
It is working pretty well but I get this warning with my eslint:
React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked.
It suggests to instead of having "array[0]" put "array" in the dependencies. The problem is that I don't want to have my useEffect triggered when the array[1] changes but only the element at the index 0.
Do you have a solution to avoid this warning and still have it working correctly or it is not possible?
CodePudding user response:
I believe it is telling you to do this:
const [array, setArray] = useState(["someText", "someOthersText"]);
let item = array[0];
useEffect(()=>{
// some function to run
}, [item]);