When not passing a callback to a child and just using it on the present component, Is there a benefit to wraping the callback in a useCallback?
This:
const Foo = (
const [count, setCount] = useState(500);
const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setCount(Number(e.target.value));
}, [setCount]);
return (
<>
<div>
Delay: <input value={count} onChange={onChange} type="number" />
</div>
</>
);
Verse This:
const Foo = (
const [count, setCount] = useState(500);
const onChange =(e: React.ChangeEvent<HTMLInputElement>) => {
setCount(Number(e.target.value));
};
return (
<>
<div>
Delay: <input value={count} onChange={onChange} type="number" />
</div>
</>
);
Codesandbox: https://codesandbox.io/s/loving-stonebraker-48xhs?file=/src/Counter.tsx
I see no benefit there when used internally since each state update (setCount(Number(e.target.value));) necessarily rerenders the component anyway and all the callback is doing is enqueueing a state update.
There may be a small (very negligible) improvement in memory usage if using a single declared, memoized function for the life of the component.
If the callback was used in an useEffect hook it could be provided as a stable reference and be removed from dependency arrays, but typically here you'd just move the function into the effect callback. This doesn't fit the use case you are asking about, but it's a valid use case that isn't passing callbacks down to children.