Harry Yates
I'm a web developer focused on TypeScript, React, and Three.js.
React's useCallback
hook is a key tool in the optimisation of React applications, ensuring that functions maintain their identity across renders unless their dependencies change.
This technique is particularly useful in complex component trees, helping to improve performance by avoiding unnecessary re-renders.
Imagine a craftsman creating a key just once and then using it for all doors until the lock's design changes.
This illustrates the principle of useCallback
in React. It enables you to maintain a function's identity across renders, which helps avoid unnecessary re-renders of child components that use that function as a prop.
useCallback
takes a function and an array of dependencies as its arguments. It memoises (or preserves) the function so that it can be reused until one of the dependencies changes.useCallback
should be used with discernment, as its inappropriate use can lead to complexity and even degrade performance. Here are some scenarios where useCallback
shines:
React.memo
, using useCallback
ensures that the handler doesn’t cause unnecessary re-renders.useEffect
), memoisation (useMemo
), or other useCallback
hooks, keeping its identity stable can prevent cascading re-renders.Consider a component that renders a list of items. Each item has a "Delete" button which, when clicked, removes the item from the list:
In this scenario, useCallback
ensures that handleDelete
function is not recreated unless items
changes, thereby preventing unnecessary re-renders of ItemComponent
.
useCallback
and useMemo
are both tools in React to help your app run faster, but they're used for different things:
useCallback
keeps a function from being recreated every time your component re-renders. Imagine telling React, "Keep using the same function as before unless something important changes." It's handy when you pass functions to components that don't change often.useMemo
is like saving the answer to a complex math problem so you don't have to solve it again unless the numbers change. It remembers a value, so you don't have to recalculate it every time your component updates, saving time for calculations that take a lot of effort.So, useCallback
is all about saving functions, and useMemo
is about saving values. Both help make your app more efficient by avoiding unnecessary work.
useCallback
only when you have identified a performance bottleneck that it can solve.