Sobes.tech
Senior

Tell me about optimization and memoization options at the intersection of parent and child components.

sobes.tech AI

Answer from AI

Optimization and memoization at the intersection of parent and child components in React (or similar frameworks) aim to minimize unnecessary re-renders and calculations.

Main approaches:

  • React.memo for the child component — prevents re-rendering if props haven't changed based on shallow comparison.
  • useMemo and useCallback in the parent component — memoize calculations and functions passed to the child to avoid creating new objects/functions on each render.
  • Passing primitive values or memoized objects — if passing a new object or function each time, React.memo won't work because prop comparison will be false.

Example:

const Child = React.memo(({ onClick, data }) => {
  console.log('Child render');
  return <button onClick={onClick}>{data.label}</button>;
});

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

  // useCallback memoizes the function so the reference doesn't change
  const handleClick = React.useCallback(() => {
    setCount(c => c + 1);
  }, []);

  // useMemo memoizes the data object
  const data = React.useMemo(() => ({ label: `Count: ${count}` }), [count]);

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

Thus, Child will not re-render unnecessarily because the props do not change references without a real reason.

Important: Memoization is a tool that helps optimize, but it's not always necessary. Profiling the application is essential to understand where it is truly beneficial.

Tell me about optimization and memoization options at… - sobes.tech