JAVASCRIPT
Optimizing Callbacks with `useCallback` to Prevent Re-renders
Discover how to use React's `useCallback` hook to memoize functions, preventing unnecessary re-renders of child components that receive callbacks as props and enhancing performance.
import React, { useState, useCallback } from 'react';
// A child component that will only re-render if its props change
const Button = React.memo(({ onClick, label }) => {
console.log(`Rendering ${label} button`);
return <button onClick={onClick}>{label}</button>;
});
function ParentComponent() {
const [count, setCount] = useState(0);
const [otherState, setOtherState] = useState(0);
// Without useCallback, handleIncrement would be a new function on every ParentComponent re-render,
// causing Button to re-render even if its label and count don't change.
const handleIncrement = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []); // Empty dependency array means this function reference is stable
const handleOtherAction = useCallback(() => {
setOtherState(prevOtherState => prevOtherState + 1);
}, []); // Stable reference
return (
<div>
<h1>Count: {count}</h1>
<Button onClick={handleIncrement} label="Increment Count" />
<Button onClick={handleOtherAction} label="Change Other State" />
<p>Other State: {otherState}</p>
<button onClick={() => setCount(count + 1)}>Force Parent Re-render (without changing state that affects Button props)</button>
</div>
);
}
How it works: `useCallback` memoizes a function, returning a memoized version that only changes if one of its dependencies has changed. In this example, `handleIncrement` and `handleOtherAction` are wrapped in `useCallback` with empty dependency arrays, ensuring their reference remains stable across renders of `ParentComponent`. When these stable functions are passed to the `Button` child component (which is wrapped in `React.memo`), `Button` will only re-render if its *props* (including the `onClick` function reference) actually change, thereby preventing unnecessary re-renders and improving application performance, especially in large component trees.