JAVASCRIPT
Prevent Unnecessary Re-renders with useCallback Hook
Discover how to use React's useCallback hook to memoize functions, preventing child components from re-rendering unnecessarily when functions are passed as props.
import React, { useState, useCallback } from 'react';
const ChildComponent = React.memo(({ onClick }) => {
console.log('ChildComponent re-rendered');
return <button onClick={onClick}>Click Child</button>;
});
function ParentComponent() {
const [count, setCount] = useState(0);
const [anotherCount, setAnotherCount] = useState(0);
// Memoized version: the function reference remains stable unless its dependencies change
const memoizedHandleClick = useCallback(() => {
setCount(c => c + 1);
}, []); // Empty dependency array means this function reference will be stable across renders
return (
<div>
<p>Count: {count}</p>
<p>Another Count: {anotherCount}</p>
<button onClick={() => setAnotherCount(c => c + 1)}>Increment Another Count</button>
<ChildComponent onClick={memoizedHandleClick} />
</div>
);
}
export default ParentComponent;
How it works: The `useCallback` hook memoizes a function, ensuring its reference remains stable across re-renders as long as its dependencies haven't changed. When `memoizedHandleClick` is passed to `ChildComponent` (which is wrapped in `React.memo`), `ChildComponent` will only re-render if its `onClick` prop's reference actually changes, or if its own state/props change. In this example, `ChildComponent` won't re-render when `anotherCount` updates, because `memoizedHandleClick`'s reference stays the same due to its empty dependency array.