React Memo and useCallback Error Fix
In this tutorial, you'll learn about React Memo and useCallback Error Fix. We cover key concepts, practical examples, and best practices.
The Problem
React.memo does not prevent a child component from re-rendering even when props appear unchanged.
Wrong
const Child = React.memo(({ onClick }) => {
console.log('Child rendered')
return <button onClick={onClick}>Click</button>
})
function Parent() {
const [count, setCount] = useState(0)
// New function every render
const handleClick = () => setCount(c => c + 1)
return (
<div>
<Child onClick={handleClick} />
<p>Count: {count}</p>
</div>
)
}
Output: console logs Child rendered every time count changes, even though the child is memoized.
Right
Wrap the callback in useCallback:
const Child = React.memo(({ onClick }) => {
console.log('Child rendered')
return <button onClick={onClick}>Click</button>
})
function Parent() {
const [count, setCount] = useState(0)
const handleClick = useCallback(() => {
setCount(c => c + 1)
}, []) // Stable reference — never changes
return (
<div>
<Child onClick={handleClick} />
<p>Count: {{ count }}</p>
</div>
)
}
Expected output: Child renders only once. useCallback provides a stable function reference across re-renders.
Prevention
- Wrap callbacks passed to memoized children with
useCallback - Ensure
React.memohas a proper comparison function for complex props - Profile re-renders with React Devtools before optimizing
Common Mistakes with memo use callback
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro