React.memo: which component instance is used for comparison as previous props?

19 Views Asked by At

Does a React.memo memoized component compare props with the previous component instance/invocation of the component or with the same component instance from the previous render cycle? Or, in other words, where does prevProps in the comparison function come from?

1

There are 1 best solutions below

0
zhulien On

Each instance of React.memo memoized component compares props with the same instance from the previous render cycle.

Having the following example:

import React, { useState } from "react";

interface Item {
  id: string;
}

interface IComponentProps {
  item: Item;
}

const Component: React.FC<IComponentProps> = ({ item }) => {
  console.log(`Component rendered with item: ${item.id}`);

  return <div>{item.id}</div>;
};

const MemoizedComponent = React.memo(Component, (prev, next) => {
  console.log("Props comparion: ", prev.item.id, next.item.id);

  return prev.item.id === next.item.id;
});

export default function App() {
  const [items, setItems] = useState<Item[]>([
    { id: "1" },
    { id: "2" },
    { id: "3" },
  ]);

  const [renderCount, setRenderCount] = useState<number>(0);

  console.log(`App rerendered. Render count: ${renderCount}`);

  return (
    <>
      {items.map((x) => {
        return <MemoizedComponent item={x} key={x.id} />;
      })}

      <button onClick={() => setRenderCount((rc) => rc + 1)}>Rerender</button>
    </>
  );
}

We get:

Props comparion:  1 1
Props comparion:  2 2
Props comparion:  3 3

Beware: various AI models get this wrong and state that prevProps comes from the previous invocation of the component in the same rendering cycle or in other words - items[1] will be compared to items[0] which is false.