JAVASCRIPT
Optimizing Performance with useCallback to Memoize Functions
Discover how React's `useCallback` hook prevents unnecessary re-renders of child components by memoizing callback functions, thereby improving application performance.
import { useState, useCallback } from 'react';
function ChildComponent({ onClick }) {
console.log('ChildComponent rendered');
return <button onClick={onClick}>Click me</button>;
}
function ParentComponent() {
const [count, setCount] = useState(0);
const [text, setText] = useState('');
// Without useCallback, this function would be recreated on every render of ParentComponent,
// causing ChildComponent to re-render even if its props haven't conceptually changed.
const handleClick = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []); // Empty dependency array means this function is created once and reused.
return (
<div>
<p>Count: {count}</p>
<p>Text: {text}</p>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
<ChildComponent onClick={handleClick} />
</div>
);
}
How it works: The `useCallback` hook returns a memoized version of the callback function that only changes if one of the dependencies has changed. In React, when a parent component re-renders, any function defined inside it will be re-created, leading to a new reference for that function. If this function is passed as a prop to a child component, the child will re-render even if its state or other props haven't changed. `useCallback` ensures that the same function instance is passed, preventing unnecessary re-renders of optimized child components (e.g., those wrapped in `React.memo`), thereby improving performance.