useCallback Hook
In React, functions are recreated on every render. If you pass a function as a prop to a child component that is memoized (with `React.memo`), the child 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 Unnecessary Rerenders
import React, { useState, useCallback, memo } from 'react';
<!-- Child component wrapped in React.memo -->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, this function is recreated on every render --> const handleIncrement = useCallback(() => { setCount(count + 1); }, [count]); <!-- Only recreate when count changes -->
return ( <div> <p>Count: {count}</p> <Button onClick={handleIncrement}>Increment</Button> <button onClick={() => setOther(other + 1)}>Change Other ({other})</button> </div> );}Example: useCallback with Dependencies
function SearchComponent() { const [query, setQuery] = useState(''); const [results, setResults] = useState([]);
const handleSearch = useCallback( async () => { const data = await fetch(`/api/search?q=${query}`).then(res => res.json()); setResults(data); }, [query] <!-- Recreate when query changes --> );
return ( <div> <input value={query} onChange={(e) => setQuery(e.target.value)} /> <button onClick={handleSearch}>Search</button> <ul> {results.map(item => <li key={item.id}>{item.name}</li>)} </ul> </div> );}When to Use useCallback
- When passing callbacks to child components that are 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).
Two Minute Drill
- `useCallback` memoizes a function so it's not recreated on every render.
- It's useful when passing functions to memoized child components to prevent unnecessary re-renders.
- The dependency array determines when the function should be recreated.
- Don't wrap every function in `useCallback` 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
