📝Do not overuse React.useCallback
- tags
Wrapping every callback function in useCallback
isn’t worth it. The cost of optimization is likely higher than updating the child.
Pass an inline callback and an array of dependencies. 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 (e.g.
shouldComponentUpdate
). [emphasis mine]
Two legible use cases for useCallback
are:
the child component uses
React.memo
orshouldComponentUpdate
(→ React.useCallback breaks encapsulation)the callback is used as a dependency in
useEffect
Resources
Hooks FAQ > Are Hooks slow because of creating functions in render? – React—another mention that
useCallback
is specifically forshouldComponentUpdate
to work.