JAVASCRIPT
Memoize Callback Functions with useCallback
Optimize React performance with `useCallback`. Prevent unnecessary child component re-renders by memoizing functions passed as props, ensuring stable references.
import React, { useState, useCallback, memo } from 'react';
const Button = memo(({ onClick, label }) => {
console.log(`Rendering ${label} button`);
return <button onClick={onClick}>{label}</button>;
});
function ParentComponent() {
const [count, setCount] = useState(0);
const [anotherState, setAnotherState] = useState(0);
// This function will only be recreated if `count` changes
const handleIncrement = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []); // Empty dependency array means this function is created once
// This function will only be recreated if `anotherState` or `count` changes
const handleDoSomethingElse = useCallback(() => {
console.log("Doing something else, count is:", count);
setAnotherState(prev => prev + 1);
}, [anotherState, count]); // Recreates if anotherState or count changes
return (
<div>
<p>Count: {count}</p>
<p>Another State: {anotherState}</p>
<Button onClick={handleIncrement} label="Increment Count" />
<Button onClick={handleDoSomethingElse} label="Do Something Else" />
<button onClick={() => setCount(count + 1)}>Force Parent Re-render</button>
</div>
);
}
export default ParentComponent;
How it works: This snippet demonstrates `useCallback` to memoize functions. When `ParentComponent` re-renders, `handleIncrement` and `handleDoSomethingElse` functions would normally be recreated, leading to `Button` components (which are `memo`-ized) re-rendering unnecessarily. By wrapping them in `useCallback` with appropriate dependency arrays, the functions' references remain stable across re-renders, preventing child components from re-rendering unless their actual props change, thus optimizing performance.