memo: Skipping a Re-render

Wrap a component in memo and React skips it when its props have not changed. Compare it with an ordinary child.

React · intermediate · 7 min · 18 steps · free

What you'll learn

Memo.jsx

import { memo, useState } from 'react';

const Avatar = memo(function Avatar({ name }) {
  return <strong>[{name[0]}]</strong>;
});

function Greeting({ name }) {
  return <span> Hello, {name}! </span>;
}

export default function App() {
  const [name] = useState('Ada');
  const [count, setCount] = useState(0);

  return (
    <div>
      <Avatar name={name} />
      <Greeting name={name} />
      <button onClick={() => setCount(count + 1)}>Clicked {count}</button>
    </div>
  );
}

Step by step

  1. React renders <App> for the first time: it calls the App function.
  2. useState runs for the first time, so React stores the starting value for name and returns it: "Ada".
  3. useState runs for the first time, so React stores the starting value for count and returns it: 0.
  4. App returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  5. Avatar is wrapped in memo. On its first render it runs like any component.
  6. Avatar returns JSX: a description of what the screen should show, <strong>[A]</strong>. React has not changed the page yet.
  7. React renders <Greeting> for the first time: it calls the Greeting function. Its props: name = "Ada".
  8. Greeting returns JSX: a description of what the screen should show, <span> Hello, Ada! </span>. React has not changed the page yet.
  9. React turns the JSX into real page elements and shows them: look at the Screen panel.
  10. You click the button. Only count changes; name is still "Ada".
  11. setCount(count + 1) does not change count right away: React queues the update and will render again. In this call count is still 0.
  12. React renders <App> again (render 2): it calls App once more, from the top.
  13. useState returns the value React has kept for name: "Ada". The starting value is only used on the first render.
  14. useState returns the value React has kept for count: 1. The starting value is only used on the first render.
  15. App returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  16. Greeting renders again, because its parent did. Avatar did not: memo compared its props, name = "Ada" both times, and skipped it.
  17. Greeting returns JSX: a description of what the screen should show, <span> Hello, Ada! </span>. React has not changed the page yet.
  18. The React group shows Avatar rendered once and Greeting twice.

Common mistakes

Best practices

Key takeaways

Check yourself

memo compares props how?

Answer: Shallowly, with Object.is

<Avatar style={{ color: "red" }} /> with memo re-renders?

Answer: Every time: a new object each render

·

More in Performance