useCallback for Performance
In React, functions are recreated on every render. When you pass these newly created functions as props to child components that are memoized (with React.memo), the child components will re-render unnecessarily because the function reference changes each time. **useCallback** solves this by memoizing the function itself.
What is useCallback?
useCallback is a React Hook that returns a memoized version of a callback function. It only changes if one of its dependencies changes. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
Think of useCallback as useMemo but for functions. It "remembers" the function so it doesn't get recreated unless necessary.
Syntax
const memoizedCallback = useCallback(() => { doSomething(a, b);}, [a, b]); <!-- dependencies -->Example: Preventing Child Re-renders
import React, { useState, useCallback, memo } from 'react';
<!-- Memoized child component -->const Button = memo(({ onClick, children }) => { console.log(`Rendering button: ${children}`); return <button onClick={onClick}>{children}</button>;});
function Counter() { const [count, setCount] = useState(0); const [other, setOther] = useState(0);
<!-- Without useCallback: new function on every render --> const handleClick = () => { setCount(count + 1); };
<!-- With useCallback: same function as long as count doesn't change --> const handleClickMemoized = useCallback(() => { setCount(count + 1); }, [count]);
return ( <div> <p>Count: {count}</p> <Button onClick={handleClickMemoized}>Increment</Button> <button onClick={() => setOther(other + 1)}>Other: {other}</button> </div> );}When to Use useCallback
- When passing callbacks to memoized child components (wrapped in React.memo).
- When the callback is used as a dependency in other hooks like useEffect.
- When the function is expensive to create (rare).
useCallback vs useMemo
| useCallback | useMemo |
|---|---|
| Memoizes a function | Memoizes a value |
| Returns the function itself | Returns the result of calling the function |
Two Minute Drill
- useCallback memoizes functions to prevent unnecessary re-creation.
- It's essential when passing callbacks to memoized child components.
- The function only changes when its dependencies change.
- Don't wrap every function only when needed for performance optimization.
- useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
Need more clarification?
Drop us an email at career@quipoinfotech.com
