The React useCallback Hook returns a memoized callback function.
This allows us to isolate resource intensive functions so that they will not automatically run on every render.
useCallback Hook only runs when one of its dependencies update.
This can improve performance.
One reason to use
useCallback is to prevent a component from re-rendering unless its props have changed.
In this example, you might think that the
Todos component will not re-render unless the
You will notice that the
Todos component re-renders even when the
todos do not change.
Why does this not work? We are using
memo, so the
Todos component should not re-render since neither the
todos 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.
To fix this, we can use the
useCallback hook to prevent the function from being recreated unless necessary.
useCallback Hook to prevent the
Todos component from re-rendering needlessly: