...
/Optimizing Re-Renders with useCallback and useMemo
Optimizing Re-Renders with useCallback and useMemo
Discover how useCallback and useMemo help prevent unnecessary re-renders, keeping components fast and efficient.
We'll cover the following...
As our React applications grow, we might notice that updating one small part of the UI can sometimes cause unnecessary re-renders in other components. Even if the output looks the same, React still re-renders child components because new function or object references are created on every render.
To tackle this, React provides two performance Hooks, useCallback and useMemo, that let us control when values and functions are re-created.
The useCallback and useMemo Hooks
Both Hooks belong to the same family; they memoize results between renders to avoid recomputation or re-creation.
Understanding useCallback
The useCallback Hook memoizes a function, returning the same instance between renders unless its dependencies change. It helps prevent unnecessary re-renders in memoized child components that depend on callback props. It is often used in conjunction with React.memo or useMemo to optimize deeply nested components.
Syntax
const memoizedCallback = useCallback(callbackFunction, dependencyArray);
Parameters:
callbackFunction: The function we want to memoize.dependencyArray: A list of dependencies that trigger a new function ...