Sobes.tech
Middle+

Tell about useMemo, useCallback, and their interaction with React.memo. Features of interaction.

sobes.tech AI

Answer from AI

useMemo and useCallback are React hooks for performance optimization that help avoid unnecessary recalculations and re-creations of functions.

  • useMemo memoizes the result of a function calculation so that it is not recalculated on every render if dependencies haven't changed.
  • useCallback memoizes the function itself, returning the same reference if dependencies haven't changed.

React.memo is a higher-order component (HOC) that memoizes a component, preventing it from re-rendering if its props haven't changed by reference.

Interaction:

If you pass functions as props to a memoized component (React.memo) without useCallback, these functions will be recreated on every render, causing the component to re-render because the props change by reference.

Using useCallback allows passing stable function references, which helps React.memo effectively prevent unnecessary re-renders.

Example:

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

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

  // Without useCallback, the function is recreated on every render
  // const handleClick = () => setCount(c => c + 1);

  // With useCallback, the function is memoized
  const handleClick = React.useCallback(() => setCount(c => c + 1), []);

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

In this example, Child will not re-render unnecessarily if handleClick is memoized with useCallback.

useMemo is useful when you need to memoize computations, such as complex calculations or creating objects that are passed as props.

Tell about useMemo, useCallback, and their… - sobes.tech