20. What are the differences between `useCallback` and `useMemo` hooks in React?

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:

  1. Usage: useCallback is used to memoize functions, while useMemo is used to memoize values.
  2. Syntax: useCallback(fn, deps) returns a memoized version of the function fn, useMemo(fn, deps) returns a memoized value returned by the function fn.
  3. 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> ); }
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.