Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger useEffect hook when only one element in an array change

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading