The useCallback
and useMemo
hooks in React are used for performance optimization in functional components by remembering values between renders.
useCallback
:
Returns a memoized version of the callback that only changes if one of the dependencies has changed. It is used to optimize passing callbacks to child components.
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
useMemo
:
Returns a memoized value that only re-computes when one of the dependencies has changed. It is used to optimize expensive calculations.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Differences:
- Usage:
useCallback
is used to memoize functions, whileuseMemo
is used to memoize values. - Syntax:
useCallback(fn, deps)
returns a memoized version of the functionfn
,useMemo(fn, deps)
returns a memoized value returned by the functionfn
. - Optimization:
useCallback
helps prevent re-creating functions on every render, which is useful when passing callbacks as props.useMemo
helps prevent expensive calculations on every render.
Example of using both hooks:
function MyComponent({ a, b }) { const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); return ( <div> <ChildComponent onClick={memoizedCallback} value={memoizedValue} /> </div> ); }