3

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try:

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

2 Comments

needed to go after the closing bracket
While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.