Sobes.tech
Middle+

Tell about memoization in React: useMemo, useCallback, React.memo. When to use them?

sobes.tech AI

Answer from AI

Memoization in React is an optimization that helps avoid unnecessary recalculations and re-renders by storing the results of computations or functions between renders.

  • useMemo — a hook that memoizes the result of a computation. It is used when there are expensive calculations dependent on certain dependencies. React will recalculate the value only if dependencies change.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • useCallback — memoizes a function, returning the same reference unless dependencies change. Useful for preventing unnecessary re-renders of child components that depend on the function in props.
const memoizedCallback = useCallback(() => { doSomething(a); }, [a]);
  • React.memo — a higher-order component that memoizes the component itself, preventing re-rendering if props haven't changed (by shallow comparison).
const MemoizedComponent = React.memo(MyComponent);

When to use:

  • useMemo — for optimizing heavy calculations.
  • useCallback — when passing functions to optimized child components to avoid creating new functions on each render.
  • React.memo — for optimizing functional components that often receive the same props.

It's important not to overuse memoization, as it has overhead itself. Use it where there are real performance issues.