useCallback is a React hook that returns a memoized callback function.
It's useful for optimizing performance by preventing unnecessary re-renders of child components that depend on the callback.
useCallback is a React Hook that returns a memoized callback function.
It only creates a new function when one of its dependencies has changed.
This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
It's particularly beneficial when you have expensive child components that re-render frequently.
import React, { useCallback, useState } from 'react';
function ParentComponent() { const [count, setCount] = useState(0); const [text, setText] = useState('');
// This callback only changes when 'count' changes const handleIncrement = useCallback(() => { setCount(c => c + 1); }, [count]);
// This callback only changes when 'text' changes const handleTextChange = useCallback((newText: string) => { setText(newText); }, [text]);
return ( <div> <p>Count: {count}</p> <button onClick={handleIncrement}>Increment</button> <input value={text} onChange={(e) => handleTextChange(e.target.value)} placeholder="Enter text..." /> <ChildComponent onIncrement={handleIncrement} /> </div> ); }
// This component will only re-render when its props actually change const ChildComponent = React.memo(({ onIncrement }) => { console.log('ChildComponent rendered'); return <button onClick={onIncrement}>Increment from Child</button>; });