Consider this example:
let memoizedCb = React.useCallback(
memoize((param) => () => someFunction(param)),
[]
);
where memoize
is from external library like "fast-memoize". Above code gives warning:
React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead
I found this thread which if we adapt to my use case would suggest this as solution (if I am not wrong):
const memoizedCb = React.useMemo(
() => memoize((param) => () => someFunction(param)),
[]
);
What is the warning about? why does useMemo
fix this problem?
NOTE: someFunction
is defined outside the function component so it is not needed as a dependency.
CodePudding user response:
From React docs
useCallback
will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders
You are seeing the warning because you are not passing any dependencies when using useCallback
hook.
Also,
useCallback(fn, deps)
is equivalent touseMemo(() => fn, deps)
.
CodePudding user response:
As far as I know, the useCallback expects an inline function. If you pass a returned function from another function, eslint won't be able to figure out what are the dependancies of the function, so it will show this warning.
Here I think, eslint is failing to determine the dependancies of somefunction
and thus it cannot evaluate the react-hooks/exhaustive-deps
rule because to evaluate this rule eslint should be able to identify is there any dependancy like state, props for the function passed to useCallback hook. So eslint is asking you to pass an inline function which it will understand and can evalute for lint rules.
CodePudding user response:
Ok I think I have partial answer why the warning goes away so I will probably accept this. If someone has additional info why the warning exists in the first place, feel free to comment, or maybe post an answer.
It seems the warning goes away in the second example because there we passed an inline function as the warning told us:
React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead
So it is not that using useMemo
gets rid of that warning, but rather using an inline function. You have same warning if you just replace useCallback
with useMemo
in the first example:
// For testing
// Doesn't work: gives same warning
let memoizedCb = React.useMemo(
memoize((param) => () => someFunction(param)),
[]
);