React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
What is useCallback and why is it used?
junior LevelCode ExampleHooks
The useCallback is a React Hook used to memoize callback functions across renders. It prevents unnecessary re-renders of optimized child components (React.memo) that rely on reference equality of function props:
jsx
import React, { useState, useCallback } from 'react';
function Parent() {
const [count, setCount] = useState(0);
// Function reference is preserved unless dependencies change
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<MemoizedChild onClick={handleClick} />
</div>
);
}