简体   繁体   中英

React warning React Hook useEffect has a missing dependency when the deps are []

I am trying to clean up the warnings in my DOM, and for every useEffect where the deps are [] I get an error that says useEffect has a missing dependency. I want to trigger the effect when the component mounts, and I was under the impression that this was the way to do it. If thats the case, why the warning?

Here is the simple code im using

useEffect(() => {
   setDispContext("NEW");
}, []);

Warning is React warning React Hook useEffect has a missing dependency: 'setDispContext'. Either include it or remove the dependency array react-hooks/exhaustive-deps React warning React Hook useEffect has a missing dependency: 'setDispContext'. Either include it or remove the dependency array react-hooks/exhaustive-deps

Everything that you use unside useEffect must be inside the dependency array, so the right way would be:

useEffect(() => {
   setDispContext("NEW");
}, [setDispContext]);

But sometimes you just need the useEffect to run once. If setDispContext won´t be change it can be put inside a useCallback. Otherwise the only waty would be to use:

useEffect(() => {
   setDispContext("NEW");
}, []);// eslint-disable-line

So the eslint warning won´t show.

Try:

useEffect(() => {
   setDispContext("NEW");
// eslint-disable-line
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM