In JavaScript, a function() {} or () => {} always creates a different function, similar to how the {} object literal always creates a new object. Normally, this wouldn’t be a problem, but it means that props receiving this function will never be the same, and your memo optimization won’t work. This is where useCallback comes in handy:
- useCallback is a React Hook that lets you cache a function definition between re-renders.
- By default, when a component re-renders, React re-renders all of its children recursively.
Usage
- Skipping re-rendering of components: to cache the functions that you pass to child components. As function is defined on every render thus rendering all children in the component tree recursively.
- Updating state from a memoised callback
- Preventing an Effect from firing too often: When a function is passed as a dependency of an effect hook.
- Optimising a custom Hook: If you’re writing a custom Hook, it’s recommended to wrap any functions that it returns into useCallback
During subsequent renders, it will either return an already stored function from the last render (if the dependencies haven’t changed) or return the function you have passed during this render.