React useCallback Explained with Parent–Child Example (Stop Unnecessary Re-renders)
React useCallback Explained – Parent & Child Re-render Problem
In this section, we will understand React useCallback using
small code examples, and then connect it to a real
Parent–Child re-render problem.
The goal is to clearly see why unnecessary re-renders happen
and how useCallback helps fix them.
🎥 Watch the Video Explanation
I have explained this exact example with live rendering and console logs in my YouTube video:
1. The Real Problem: Parent Re-renders
In React, whenever a component re-renders, all functions inside it are created again. This is normal JavaScript behavior.
2. Parent–Child Example (Without useCallback ❌)
count→ used by the childdark→ unrelated UI state
function Parent() {
const [count, setCount] = useState(0);
const [dark, setDark] = useState(false);
const handleIncrement = () => {
setCount(c => c + 1);
};
return (
<>
<button onClick={() => setDark(d => !d)}>
Toggle Theme
</button>
<Child
count={count}
onIncrement={handleIncrement}
/>
</>
);
}
Now observe what happens:
- Clicking Toggle Theme updates
dark - Parent re-renders
handleIncrementis recreated- Child receives a new function prop
- Child re-renders unnecessarily ❌
3. Why Does the Child Re-render?
React compares props using reference equality. Since functions are objects, a new function means a new reference.
New function reference = React thinks prop changed
4. What Does useCallback Actually Do?
“Don’t create a new function on every render. Reuse the same function unless dependencies change.”
5. Fixing the Problem with useCallback ✅
const handleIncrement = useCallback(() => {
setCount(c => c + 1);
}, []);
Now when dark changes:
- Parent re-renders
handleIncrementreference stays the same- Child receives the same prop
- Unnecessary re-render is avoided ✅
6. Important: useCallback Works Best with React.memo
const Child = React.memo(function Child({ count, onIncrement }) {
console.log("Child rendered");
return (
<button onClick={onIncrement}>
Count: {count}
</button>
);
});
useCallback stabilizes the function
React.memo prevents unnecessary re-renders
7. Interview-Friendly Summary
- useCallback memoizes function references
- Prevents unnecessary child re-renders
- Useful when passing functions as props
- Should not be used everywhere
useCallback is used to memoize a function so its reference doesn’t change across renders, preventing unnecessary re-renders in child components.
👉 Also read: JavaScript Closures Explained with Real React Example
👩💻 Written by Code With Sanyogita
Frontend Developer & content creator sharing beginner-friendly tutorials on React, JavaScript, and Web Development.
If this post helped you, consider subscribing on YouTube for more real-world coding examples 🚀
Comments
Post a Comment
Share your doubt or feedback below 👇