Sobes.tech
Middle

Code review: you have a piece of production code. Find problems and suggest improvements. Will React.memo perform memoization correctly if functions and objects are passed in props?

sobes.tech AI

Answer from AI

React.memo memoizes a component, preventing re-rendering if props haven't changed compared to the previous render. However, if functions or objects are passed in props, memoization may not work correctly because new references to functions and objects are created on each render, and React.memo's shallow comparison will detect changes.

To improve this:

  • Use useCallback to memoize functions so that references don't change unnecessarily.
  • Use useMemo to memoize objects or arrays passed in props.

Example:

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

  // Function is memoized, reference doesn't change on re-render
  const handleClick = React.useCallback(() => {
    console.log('Clicked');
  }, []);

  // Object is memoized
  const options = React.useMemo(() => ({ enabled: true }), []);

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

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

Without useCallback and useMemo, Child will re-render every time, even if the props haven't logically changed.

Code review: you have a piece of production code… - sobes.tech