useCallback() is a React Hook used to memoize a callback function, preventing it from being recreated on every render unless its dependencies change.
🔹 Syntax:
const memoizedCallback = useCallback(() => {
// function logic
}, [dependencies]);
🔹 Why Use useCallback()?
- Prevents unnecessary re-renders of child components that receive functions as props.
- Useful when passing callbacks to memoized components (e.g., with
React.memo). - Helps optimize performance in large or frequently-updating components.
🔹 Example:
import React, { useState, useCallback } from 'react';
const Button = React.memo(({ onClick, label }) => {
console.log('Rendering button:', label);
return <button onClick={onClick}>{label}</button>;
});
function Counter() {
const [count, setCount] = useState(0);
const [other, setOther] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
return (
<div>
<p>Count: {count}</p>
<Button onClick={increment} label="Increment" />
<button onClick={() => setOther(other + 1)}>Update Other State</button>
</div>
);
}
Without
useCallback, theincrementfunction would be recreated on every render, causing theButtonto re-render too.
📝 In Summary:
useCallbackreturns a memoized version of the callback function.- It's mainly used for performance optimization.
- Re-creates the function only when dependencies change.