Sobes.tech
Middle

What is React.memo, how does it differ from hooks useMemo/useCallback, and how are they related?

sobes.tech AI

Answer from AI

React.memo is a higher-order component that optimizes the rendering of functional components by preventing their re-rendering if props haven't changed. It is similar to PureComponent for class components.

useMemo and useCallback are hooks that help memoize values and functions within a component to avoid recreating them on every render.

  • useMemo memoizes the result of a computation (e.g., complex calculations), returning a cached value.
  • useCallback memoizes a function, returning the same reference if dependencies haven't changed.

Relationship: React.memo uses shallow comparison of props to decide whether to re-render the component. If props are functions or objects that are recreated on each render, React.memo won't help because references change.

This is where useMemo and useCallback come in: they stabilize references to functions and objects passed as props so that React.memo can compare efficiently and avoid unnecessary renders.

Example:

const Child = React.memo(({ onClick }) => {
  console.log('Child rendered');
  return <button onClick={onClick}>Click me</button>;
});

function Parent() {
  const [count, setCount] = React.useState(0);

  // Without useCallback, the function would be recreated on every render
  const handleClick = React.useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return <Child onClick={handleClick} />;
}

In this example, React.memo prevents re-rendering of Child if the onClick prop doesn't change, and useCallback ensures the handleClick function reference remains stable.