The useCallback hook helps you keep a function the same between renders unless its inputs change. This saves work and avoids mistakes when React checks for changes.
useCallback hook in React
const memoizedFunction = useCallback(() => { // function code here }, [dependencies]);
The first argument is the function you want to keep the same.
The second argument is an array of values that, when changed, will recreate the function.
count changes.const increment = useCallback(() => { setCount(count + 1); }, [count]);
const sayHello = useCallback(() => { console.log('Hello!'); }, []);
This component shows a count and a button. The increment function is created once and reused, so React won't recreate it on every render. Clicking the button increases the count.
import React, { useState, useCallback } from 'react'; function Counter() { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount(c => c + 1); }, []); return ( <div> <p>Count: {count}</p> <button onClick={increment} aria-label="Increment count">Increase</button> </div> ); } export default Counter;
Using useCallback helps React avoid unnecessary work but don't overuse it; only use when you see performance issues or pass functions to optimized child components.
Remember to include all variables your function uses in the dependency array to keep it updated correctly.
useCallback keeps a function the same between renders unless dependencies change.
It helps improve performance by avoiding unnecessary function recreations.
Use it when passing functions to child components or hooks that depend on stable functions.