What Is useCallback Hook?
The useCallback hook memoizes a function so that it is not recreated on every render. It’s useful when passing functions to memoized child components to avoid unnecessary re-renders.
Basic Syntax
const memoizedCallback = useCallback(() => {
// function logic
}, [dependencies]);
memoizedCallback→ memoized functiondependencies→ array controlling when function updates
Example
import React, { useState, useCallback } from "react";
const Child = React.memo(({ handleClick }) => {
console.log("Child rendered");
return <button onClick={handleClick}>Click Me</button>;
});
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
return (
<div>
<Child handleClick={handleClick} />
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<p>Count: {count}</p>
</div>
);
}
✅ Child does not re-render when count changes because handleClick is memoized.
Key Points
- Memoizes functions in functional components
- Prevents unnecessary re-renders of memoized children
- Works with dependencies to update function when needed
- Combine with
React.memofor optimal performance
Conclusion
useCallback is essential for optimizing React apps, reducing re-renders, and improving performance when passing functions as props.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP