useCallback
is used to memoize functions so that they are not re-created on every render unless one of the dependencies changes. This is particularly useful when passing callbacks to child components that rely on referential equality to avoid unnecessary renders.
import React, { useState, useCallback } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((prevCount) => prevCount + 1);
}, []);
return (
<div>
<ChildComponent onClick={increment} />
<p>Count: {count}</p>
</div>
);
}
function ChildComponent({ onClick }) {
console.log('Child component re-rendered');
return <button onClick={onClick}>Increment</button>;
}