Sobes.tech
Middle+

Tell me about memoization in React: useMemo, useCallback, and React.memo. How do they work and why are they needed?

sobes.tech AI

Answer from AI

In React, memoization helps optimize performance by preventing unnecessary re-computations and re-renders.

  • useMemo — memoizes the result of a computation. It is used when you need to remember a complex calculation and only recalculate it when dependencies change.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • useCallback — memoizes the function itself, returning the same reference if dependencies haven't changed. This is useful to avoid creating new functions on every render, especially when passing functions to child components.
const memoizedCallback = useCallback(() => { doSomething(a); }, [a]);
  • React.memo — is a Higher Order Component (HOC) that memoizes the component itself. It prevents re-rendering the component if props haven't changed.
const MemoizedComponent = React.memo(MyComponent);

Together, these tools help reduce unnecessary renders and computations, which is especially important in large applications with heavy components or complex calculations.

Tell me about memoization in React: useMemo… - sobes.tech