Cog
Cog

Reputation: 1705

Best way to resolve react-hooks/exhaustive-deps warning

Consider this contrived code snippet.

const foo = () => {return 1;} 
const bar = useMemo(() => {return foo();}, [foo])

When I trigger a react-hooks/exhaustive-deps warning, I'll get a message like this.

The 'foo' function makes the dependencies of useMemo Hook (at line 2) change on every render. Move it inside the useMemo callback. Alternatively, wrap the definition of 'foo' in its own useCallback() Hook.

The warning gives me 2 recommendations: 1) bring foo inside of bar's useMemo callback, or 2) wrap the function inside a useCallback.

I could certainly do either. I'm just wondering: Is either of those options preferable over the other, and if so then why? And if your answer is "it depends", what exactly does it depend on?

Upvotes: 9

Views: 7814

Answers (2)

Ntshembo Hlongwane
Ntshembo Hlongwane

Reputation: 1051

With useEffect how I like to resolve this is having a cleanup function

const [mounted, setMounted] = useState(true);


useEffect(()=>{

    if (mounted){
        buzz();

    }

    //Cleanup function
    return ()=>{
        setMounted(false);
    }
}, [mounted]) //hook dependency 

Upvotes: 0

Zachary Haber
Zachary Haber

Reputation: 11027

Both ways work just fine. The preference is based on the code and what you are doing with them.

For instance, if you use foo in more than that one location, then moving it inside the useMemo callback wouldn't work.

If you are only using foo in the useMemo callback, then it makes sense to define it in there.

In that case, it would look something like:

const bar = useMemo(() => {
  const foo = () => 1;
  return foo();
  // include foo's dependencies in the deps array
}, []);

or you could define it inline:

const bar = useMemo(() => {
  return 1;
  // include foo's dependencies in the deps array
}, []);

Upvotes: 11

Related Questions