useCallback Hook
Learn how to use the useCallback Hook to cache function definitions between renders and optimize components when stable function references are useful.
1. What Is the useCallback Hook?
The useCallback Hook is a built-in React Hook that caches a function definition between renders. React can reuse the cached function while its dependencies remain unchanged.
It is useful when passing callbacks to memoized child components or when a function is used as a dependency of another Hook.
2. Syntax of useCallback
The basic syntax is:
const cachedFunction = useCallback(() => {
// Function logic
}, [dependencies]);
- Function: The function definition that React can cache.
- Dependencies: Reactive values used inside the function.
- cachedFunction: The function returned by useCallback.
3. How useCallback Works
React compares the dependencies between renders. If the dependencies remain unchanged, the cached function can be reused. Otherwise, React uses the new function definition.
4. Example: Using useCallback
In this example, useCallback creates a function that displays a message when a button is clicked.
Example Code
import { useCallback, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const showMessage = useCallback(() => {
console.log("Hello from React!");
}, []);
return (
<div>
<h2>useCallback Example</h2>
<p>Count: {count}</p>
<button onClick={() =>
setCount(previousCount =>
previousCount + 1
)
}>
Increase Count
</button>
<button onClick={showMessage}>
Show Message
</button>
</div>
);
}
export default App;
Expected Output
useCallback Example
Count: 0
After clicking Increase Count: Count: 1
After clicking Show Message, the console displays:
Hello from React!5. useCallback with React.memo
A new function is normally created when a component renders. When a function is passed as a prop to a memoized child component, a different function reference can cause the child to render again. useCallback can help keep that reference stable when its dependencies do not change.
Example Code
import {
memo,
useCallback,
useState
} from "react";
const Child = memo(function Child({ onClick }) {
console.log("Child rendered");
return (
<button onClick={onClick}>
Click Child
</button>
);
});
function App() {
const [count, setCount] = useState(0);
const handleChildClick = useCallback(() => {
console.log("Child button clicked");
}, []);
return (
<div>
<h2>Memoized Child Example</h2>
<p>Count: {count}</p>
<button onClick={() =>
setCount(previousCount =>
previousCount + 1
)
}>
Increase Count
</button>
<Child onClick={handleChildClick} />
</div>
);
}
export default App;
Expected Output
Memoized Child Example
Count: 0
[ Increase Count ]
[ Click Child ]
Clicking Increase Count updates the parent count. The memoized child can skip rendering because its callback prop remains the same.
Clicking Click Child displays a message in the console.
6. Understanding Dependencies
If a callback uses state or props, include those reactive values in the dependency array so that the function uses the latest values.
Example Code
import { useCallback, useState } from "react";
function App() {
const [name, setName] = useState("Samadhan");
const showName = useCallback(() => {
console.log(name);
}, [name]);
return (
<div>
<h2>Callback Dependencies</h2>
<p>Name: {name}</p>
<button onClick={() =>
setName("Samiksha")
}>
Change Name
</button>
<button onClick={showName}>
Show Name
</button>
</div>
);
}
export default App;
Expected Output
Initially: Name: Samadhan
After clicking Change Name: Name: Samiksha
Click Show Name.
Console output: Samiksha7. Difference Between useMemo and useCallback
- useMemo: Caches the result of a calculation.
- useCallback: Caches a function definition.
- useMemo example: Calculating a total price from quantity and price.
- useCallback example: Keeping a callback reference stable when passing it to a memoized child component.
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
8. Important Points About useCallback
- Import useCallback from React.
- Call Hooks at the top level of a component or custom Hook.
- Include all reactive values used by the callback in its dependency array.
- useCallback returns a function; it does not execute that function automatically.
- It is most useful when stable function identity provides a real performance benefit.
- Avoid using useCallback unnecessarily for every function in a component.
9. Practice Tasks
Complete the following exercises:
- Create a function using useCallback that logs a message.
- Create a counter and a callback that displays its value.
- Pass a callback to a child component wrapped in React.memo.
- Create a callback that displays a student's name and update it when the name changes.
- Explain the difference between useMemo and useCallback.