React useCallback
React useCallback
Hook returns a memoized callback function.
It is done so that it does not need to be recalculated resulting in improved performance.
If we don't use useCallback
, the function would run on every render. This helps us to memoize resource-intensive functions so that they will not automatically run on every render.
With useCallback
Hook, the memoized function only runs when any of its dependencies update.
When to use useCallback?
You may think we can use memo
and stop a component from re-rendering, but if there is a case where you are passing a function as a prop to a component, then it will re-render irrespective of memo
. This is because of something called "referential equality". Every time a component re-renders, its function gets recreated. Hence, memo
is working, but because the function is getting recreated, the component will re-render. To avoid this, we can use useCallback
!
Like this:
const handleState = useCallback(() => {
setState({...state, type: 'CONFIRMED'});
}, [state])
Like this, we are memoizing the function and only letting it run when the dependency state
changes!