Last Updated : 08 Feb, 2025
The useCallback Hook is a built-in React Hook that memoizes a callback function, preventing it from being recreated on every render unless its dependencies change. This is useful for optimizing performance, especially when passing functions as props to child components.
Syntax
const memoizedCallback = useCallback(() => { // Function logic }, [dependencies]);
Now let's see the actual difference the useCallback hook causes
Without the useCallback HookThis example creates a counter app without using the useCallback Hook.
JavaScript
import React, { useState } from "react";
const funcSet = new Set();
const App = () => {
const [cnt, setCnt] = useState(0);
const [num, setNum] = useState(0);
const incCnt = () => setCnt(cnt + 1);
const decCnt = () => setCnt(cnt - 1);
const incNum = () => setNum(num + 1);
funcSet.add(incCnt);
funcSet.add(decCnt);
funcSet.add(incNum);
alert(funcSet.size);
return (
<div>
<h2>Without useCallback Hook</h2>
<button onClick={incCnt}>Increase Counter</button>
<button onClick={decCnt}>Decrease Counter</button>
<button onClick={incNum}>Increase Number</button>
</div>
);
};
export default App;
In this example
The issue here is that every time the component re-renders, new function references are created, causing unnecessary re-renders of child components and inefficient memory usage.
Using useCallback HookTo solve this problem, we can use the useCallback hook. The useCallback hook is essential for optimizing performance in React applications, especially when passing callbacks to child components.
JavaScript
import React, { useState, useCallback } from "react";
const funcSet = new Set();
const App = () => {
const [cnt, setCnt] = useState(0);
const [num, setNum] = useState(0);
const incCnt = useCallback(() => setCnt(cnt + 1), [cnt]);
const decCnt = useCallback(() => setCnt(cnt - 1), [cnt]);
const incNum = useCallback(() => setNum(num + 1), [num]);
funcSet.add(incCnt);
funcSet.add(decCnt);
funcSet.add(incNum);
alert(funcSet.size);
return (
<div>
<h2>With useCallback Hook</h2>
<button onClick={incCnt}>Increase Counter</button>
<button onClick={decCnt}>Decrease Counter</button>
<button onClick={incNum}>Increase Number</button>
</div>
);
};
export default App;
In this example
Output
When to Use useCallback?You should use useCallback when
However, avoid overusing useCallback, as it adds an extra layer of complexity and can sometimes lead to premature optimizations.
useCallback vs useMemoThe useCallback and useMemo Hooks are similar, but they serve different purposes:
Using useCallback
correctly can enhance performance, but excessive use may introduce unnecessary complexity. Here are some best practices:
useCallback
may not be needed.useCallback
.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4