Understanding dependency caching and referencing of useCallback in React
P粉044526217
2023-08-15 19:29:37
<p>Does the useCallback hook only cache the function reference or also the value/result of the function itself? Also, does using ref in a dependency array actually have any effect, like a component's ref? If not, is there a way to ensure that changes to the ref value have the appropriate effect? </p>
<p>I originally thought that only function references would be cached, but after reading an article I learned that useCallback(fn, deps) is equivalent to useMemo(() => fn, deps), and I'm not sure if this is the case This is actually the case. Also, I tried using the component's ref as a dependency (like Video.js and react-slick), but I think it doesn't have much impact compared to other dependencies. </p>
Yes, the purpose of
useCallback
is to allow a function to keep its reference between renders unless the dependencies you specify have changed.For example, if you have a function
f(x,y)=>x y
, you can use an empty dependency arrayuseCallback((x,y)=>x y,[ ])
, this function will never change. It always produces consistent behavior because it only uses its arguments to parse the output. However, it may change if you have another functionh
and another external valuez
, andh
is defined ash(x ,y)=>x y z
, then you need to includez
in the dependencies so that ifz
changes, the value returned fromuseCallback
The function will have a new reference.So the purpose of
useCallback
is typically when you pass a function so it doesn't trigger a child component to re-render, or when you use a function as a function in a child component'suseEffect
declaration dependencies. If the operations inside the function are expensive, thenuseCallback
is less useful and you should memorize the results separately.Regarding the
ref
thing, I think includingref
in the dependency doesn't do anything, it's like the array is empty. Maybe ifref
was stored in the state it might be useful, but I'm not really sure.Here is a link https://stackblitz.com/edit/stackblitz-starters-wwyw9f?file=src/App.tsx, which has some examples, which may be useful.
If it might be deleted, I can also paste it over.
hope it is of help to you