Passing a function as a useEffect dependency

A function as a useEffect dependency

I currently have a useEffect that simply calls a function. That's it. Nothing else. However, I get this error in the linter:

Line 127:6: React Hook useEffect has a missing dependency: 'myFunc'. Either include it or remove the dependency array

Adding it to the dependency array causes the dependencies of the useEffect hook (ie itself?) to change on every render.

The options are then move the entire function into the useEffect (which would actually be fine in my case as I'm not using it anywhere else) or memoize the function. This begs the question - what is memoization and how do I do it?

Memoization

Memoization is basically built around the idea that we want to avoid recalculating things that we already have. The value you got before is the same one you'll get back.

There are three APIs for memoizations in React: memo, useMemo, and useCallback. In React they only keep around the most recent value of the input and result. So if you call a memoized function with some values, new values, then the old ones again - it will recalculate the result every time.

So why do we have to do it with the original function? Well the function is created within the component and that means it will be new every render (as functions expressions are referentially different each time), hence will trigger the useEffect and a re-render, causing the useEffect to be triggered and a re-render, then causing the useEffect to be triggered and a re-render etc etc etc

useMemo vs useCallback

One thing I didn't get out of all this is what the heck the difference between useMemo and useCallback is. So let's find out.

The big difference is useCallback is just for functions. useMemo can be used for any value type. Both allow you to ensure that the item passed to them isn't reinitialized on every render.

Should you use them every time then? No. If the value (or variable's value inside a function if it's a functions ) is derived from props or other variables is initialised within the body of the function the better, more efficient and nicer looking way of preventing re-initialization on every render is to simply move it outside the function.

So for my initial function in the useEffect - I should just simply move this function outside the component. This is better as well, as it means I can then move it to another file, export it and use it elsewhere - increasing code reusability. What's more, you now don't need to pass the function as a dependency to the useEffect as it is now an outer scope value, which when mutated doesn't re-render the component.

All rights reserved © Joshua Bosman 2025