
Learn the useCallback Hook in React
10 August, 2022
10
10
1
Contributors
What is the useCallback hook?
useCallback()
returns a memoized callback.
Memoization, also known as memoisation, is a technique used in computing to speed up computer programmes by caching the results of heavy function calls and returning the cached result when the same inputs are used again. Consider memoization to be the act of storing a value such that it does not have to be recalculated.
This allows us to separate resource-intensive functions so they don't have to be re-executed on every render; as a result, it will only run when one of its dependencies updates.
Syntax
When to use the useCallback hook?
One reason to use useCallback
is to prevent a component from re-rendering unless its props have changed.
Using a simple Todo
example:
Try running this, and click on the increment button, i.e <button onClick={increment}>+</button>
You’ll notice the Todo
component re-renders even when the todo
does not change.
Why does this not work? We are using memo
, so the Todo
component should not re-render since neither the todo
state nor the addTodo
function are changing when the count is incremented.
This is because of something called "referential equality".
Every time a component re-renders, its functions get recreated. Because of this, the addTodo
function has actually changed.
Solution
Wrap the addTodo()
in a useCallback()
Alternative to the useCallback hook
The useCallback()
and the useMemo()
are similiar. The main difference is that the useMemo()
returns a memoized value while the useCallback()
returns a memoized function.
react
javascript
react-hooks