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
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>
);
}<App> for the first time: it calls the App function.useState runs for the first time, so React stores the starting value for name and returns it: "Ada".useState runs for the first time, so React stores the starting value for count and returns it: 0.App returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Avatar returns JSX: a description of what the screen should show, <strong>[A]</strong>. React has not changed the page yet.<Greeting> for the first time: it calls the Greeting function. Its props: name = "Ada".Greeting returns JSX: a description of what the screen should show, <span> Hello, Ada! </span>. React has not changed the page yet.setCount(count + 1) does not change count right away: React queues the update and will render again. In this call count is still 0.<App> again (render 2): it calls App once more, from the top.useState returns the value React has kept for name: "Ada". The starting value is only used on the first render.useState returns the value React has kept for count: 1. The starting value is only used on the first render.App returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Greeting returns JSX: a description of what the screen should show, <span> Hello, Ada! </span>. React has not changed the page yet.Answer: Shallowly, with Object.is
Answer: Every time: a new object each render
← Derived State: Calculate, Don't Store · useMemo: Caching a Calculation →