React Hooks: useCallback vs useMemo
The key difference: useCallback memoizes functions, useMemo memoizes values. Use wisely!
Technologies Discussed
Understanding React Hooks for Performance
React provides powerful hooks for optimizing component performance. Among the most misunderstood are useCallback and useMemo. Let's break down the differences.
useCallback: Memoizing Functions
useCallback returns a memoized callback function. Use it when you need to pass a stable function reference to child components.
javascript
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
When to use: - Passing callbacks to optimized child components - Avoiding unnecessary re-renders in child components - Using with React.memo for performance optimization
useMemo: Memoizing Values
useMemo returns a memoized value. Use it to avoid expensive computations on every render.
javascript
const memoizedValue = useMemo(
() => computeExpensiveValue(a, b),
[a, b],
);
When to use: - Avoiding expensive calculations - Creating object references that need to be stable - Optimizing complex renders
Key Differences
| Aspect | useCallback | useMemo | |--------|------------|---------| | Memoizes | Functions | Values | | Returns | Function | Any value | | Use case | Callbacks | Computations | | Performance | Prevents re-renders | Avoids recalculation |
Real World Example
javascript
function Parent() {
const [count, setCount] = useState(0);// Memoized function const handleClick = useCallback(() => { console.log(count); }, [count]);
// Memoized value const expensiveList = useMemo(() => { return items.filter(item => item.active); }, [items]);
return <Child onClick={handleClick} list={expensiveList} />; }
Common Mistakes
1. Using them without profiling 2. Adding everything to dependencies 3. Using when not needed 4. Not understanding closure
When NOT to Use
These hooks have a performance cost. Only use when: - You've profiled and found performance issues - Passing to child components with React.memo - Computing expensive values
Conclusion
useCallback and useMemo are powerful optimization tools, but they're not silver bullets. Use them wisely, profile your code, and optimize where it matters.