Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 132 ยท Performance

memo, Referential Equality and Avoiding Re-renders

Learn how React.memo works, why shallow comparison breaks with objects and functions, and the cheaper fixes first - moving state down, lifting content up and passing children.

By default, when a component renders, React renders every component below it, whether or not their props changed. That sounds wasteful, and sometimes it is, but most of the time it is cheap and harmless: rendering is just calling functions, and React only touches the DOM for the parts that actually differ. You should not fight it by reflex.

Still, there are moments when a re-render is expensive, for instance a big chart, a thousand-row table or a heavy form, and the parent re-renders on every keystroke. This lesson shows the tool React gives you for that, memo, why it often silently does nothing, and the cheaper structural fixes that you should try first. It builds on Rendering in Depth and useMemo and useCallback.

The default: parents render children

Here a parent holds a counter, and renders an unrelated child that takes no props at all. Click the button and watch the console.

A child re-renders with its parent

On the first render the console shows App rendered, count = 0 and Greeting rendered. After each click you get both lines again, with the new count. Greeting has no props and nothing it shows can change, yet it ran again. The rule is: a render of a component renders all of its children, regardless of props. This is the behavior memo changes.

React.memo

memo wraps a component so that React compares the new props with the previous props and, if they are equal, skips rendering it and reuses the last result.

JSX
import { memo } from 'react';

const Greeting = memo(function Greeting() {
  return <p>Hello from a component with no props.</p>;
});

The comparison is shallow: each prop is compared with Object.is, one by one. Strings, numbers and booleans are equal when their values are equal. Objects, arrays and functions are equal only when they are the same object in memory.

memo skips the child

Now each click logs only App rendered, count = N. Greeting rendered for Ada appears once, on mount. The prop name is the string "Ada" every time, so the shallow comparison says "nothing changed" and React reuses the previous output.

memo only looks at props. If the memoized component has its own state, or reads a context, it still re-renders when those change. Memo skips renders caused by the parent, nothing else.

Why memo often does nothing: referential equality

JavaScript compares objects and functions by identity. Every time a component renders, an object literal or an inline arrow function creates a new object. So this "unchanged" prop is, to memo, a different value on every render:

JSX
<Chart options={{ color: 'teal' }} onSelect={() => select(id)} />

{ color: 'teal' } looks identical to last time, but Object.is({}, {}) is false. The memo wrapper sees a new options and a new onSelect and renders anyway, plus it paid for the comparison. This is the number one reason people say "memo doesn't work".

memo defeated by an inline object

After the first click the console shows --- App rendered 1 --- followed by only Badge rendered: inline object. The badge that receives a new style object on every render re-renders; the one that receives fixedStyle, defined once outside the component, is skipped.

Making props stable

There are three ways to give a memoized child the same identity across renders:

  1. Define it outside the component when it does not depend on props or state (like fixedStyle above). Free and obvious.
  2. useMemo for objects and arrays computed from props or state.
  3. useCallback for functions.
A stable callback and a stable object

Type ab into the box. The console shows Editor rendered for the mount and for each keystroke, but Toolbar rendered (light) only once, at mount. Both props are stable: theme comes from useMemo with no dependencies, and handleSave has an empty dependency array because it reads the latest text from a ref instead of closing over text.

That last detail is the trap. If handleSave had been written as useCallback(() => ..., [text]), it would get a new identity on every keystroke, and Toolbar would re-render every time even though it is memoized. A memoized child only skips work if all its props are stable, so memoization is a chain, and one weak link (an inline function, a dependency that changes constantly) breaks it. Refs are covered in Refs with useRef.

Fix the structure before reaching for memo

The cheapest way to avoid re-rendering something is to not have the state above it in the first place. Two structural moves solve the majority of cases without any memoization.

Move state down

If only one small part of the tree uses a piece of state, move that state into its own component. Then only that component re-renders when it changes.

Moving state down

Type ab. The console shows SearchBox rendered: "a" and SearchBox rendered: "ab" while App and SlowReport print only once, at mount. The state lives in SearchBox, so a keystroke renders SearchBox and nothing else. If query had been in App, SlowReport would have rendered on every key. This is called state colocation: keep state as close as possible to where it is used.

Lift content up: the children trick

Sometimes the state does have to wrap the slow part, for example a hover or scroll tracker around a big tree. The trick: pass the slow part in as children. The element <SlowReport /> is then created by a component that does not re-render, so React sees the very same element object and skips it.

The children prop trick

Click the button: only Highlighter rendered, on = true is logged. App created the <SlowReport /> element once and handed it down; when Highlighter re-renders it just places the same element in the output, and React bails out when it meets an element it has already rendered. No memo involved. The mechanics are explained in Children and Composition.

When memo is the right tool

After the structural fixes, memo earns its place when all of these hold:

  • The component is measurably slow to render, or it appears many times (rows in a list).
  • It re-renders often with props that are the same as last time.
  • You can keep its props stable (primitives, or objects and functions that are properly memoized).

List rows are the classic case: a parent with a text filter renders 500 <Row> items; with memo and stable callbacks, typing in an unrelated field no longer re-renders the rows.

Custom comparison

memo(Component, areEqual) accepts a second function that receives the previous and next props and returns true to skip. Use it rarely: it is easy to forget a prop and ship stale UI. A deep comparison of big objects can also cost more than the render it saves.

JSX
const Row = memo(RowImpl, (prev, next) => prev.item.id === next.item.id && prev.item.version === next.item.version);

Pitfalls professionals know

  • Do not memo everything. Each memo adds a comparison on every parent render. For a small component that comparison costs about as much as rendering it.
  • Children are props. <Card><p>Hi</p></Card> passes a brand new element as children every render, so a memoized Card re-renders. Memoize the element or restructure.
  • Context bypasses memo. A memoized component that calls useContext still re-renders when that context value changes.
  • Measure first. Use the Profiler to see which components render and how long they take.
  • The compiler may make this unnecessary. With the React Compiler, components and values are memoized automatically, and hand-written memo, useMemo and useCallback become mostly an escape hatch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A parent component re-renders. It renders a child that takes no props and is not wrapped in memo. What happens to the child?

    Without memo, React does not compare props. A parent render always renders its children. Props only matter once the child is wrapped in memo.
  2. 2. Why does <Badge style={{ color: 'red' }} /> defeat memo(Badge)?

    Shallow comparison treats two different objects as different even if their contents match. Define the object outside the component or wrap it in useMemo to keep its identity.
  3. 3. A highlighter holds hover state and wraps a slow tree. Which approach avoids re-rendering the slow tree without memo?

    The children element is created by the parent and reused by React when the highlighter re-renders, so the slow component is not rendered again.
  4. 4. A memoized Toolbar receives a stable theme object and an onSave function recreated on every render. What happens when the parent re-renders?

    The shallow comparison checks every prop. A single changed identity makes memo give up, so stabilize all the props or the memo is wasted.
  5. 5. What does memo NOT prevent?

    memo only skips renders triggered by the parent. State changes inside the component, and changes in a context it reads, still cause renders.

Summary

  • A component render renders all its children by default; memo skips a child when its props are shallowly equal to last time.
  • Shallow equality uses Object.is: primitives compare by value, objects and functions by identity.
  • Inline objects, arrays and functions create new identities every render and quietly defeat memo; stabilize them with constants outside the component, useMemo or useCallback.
  • Every prop must be stable for memo to help.
  • Try structure first: move state down, or pass slow content as children so its element is not recreated.
  • Use memo for components that are measurably slow or repeated many times, and measure with the Profiler.

Next: Reconciliation and Keys in Depth