UseCallback
The useCallback hook in React is used to memoize a function so that it is only re-created when its dependencies change. This is particularly useful when passing functions as props to child components, helping to avoid unnecessary re-renders of those children.
Syntax
const memoizedCallback = useCallback(() => {
// Function logic here
}, [dependencies]);`
- Function: The function to be memoized.
- Dependency Array: A list of dependencies that determine when the function should be re-created. If any of these dependencies change, the function is updated; otherwise, it remains the same across renders.
Example: Optimizing Child Component Re-renders
In this example, useCallback is used to prevent the increment function from being recreated unnecessarily, which helps optimize performance by avoiding unnecessary re-renders of the Child component.
import React, { useState, useCallback } from 'react';
function Parent() {
const [count, setCount] = useState(0);
const [otherCount, setOtherCount] = useState(0);
// Memoize the increment function to prevent unnecessary re-renders
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setOtherCount(otherCount + 1)}>Increment Other Count</button>
<p>Other Count: {otherCount}</p>
<Child increment={increment} />
</div>
);
}
function Child({ increment }) {
console.log("Child component rendered");
return (
<div>
<button onClick={increment}>Increment Count in Parent</button>
</div>
);
}
export default Parent;`
Explanation
- Memoized Function: The
incrementfunction is wrapped inuseCallback, so it only changes ifcountchanges. - Avoiding Re-Renders in Child: Because
incrementis memoized, it won't be recreated whenotherCountchanges, which means theChildcomponent will not re-render unless the actual function reference (increment) changes. - Optimization:
useCallbackhelps to prevent unnecessary re-renders ofChildby ensuring the function reference remains the same whenotherCountchanges, reducing performance overhead.
When to Use useCallback
- Use
useCallbackwhen passing functions to components that depend on reference equality to prevent unnecessary re-renders. - It's useful in conjunction with
React.memo, which only re-renders a component if its props change, makinguseCallbackan efficient way to keep function references stable.