React · Lesson 5

Rendering & performance

What a render really is, how reconciliation and keys decide what survives, when memo, useMemo and useCallback help (and when they don't), the React Compiler, virtualised lists, transitions and deferred values, and how to measure with the Profiler.

18 min read

In short

  • A render calls functions; the commit touches the DOM
  • State, parent renders and context trigger renders
  • New objects and functions defeat memo
  • Move state down and pass content as children
  • Defer slow children; virtualise long lists; measure

Most React performance problems at work aren't slow JavaScript. They're too much rendering (a context that re-renders the whole page on every keystroke, a parent that re-renders 500 rows when one changes) or too much DOM (a table with 10,000 rows). The fix is rarely "wrap everything in useMemo". It's knowing what triggers a render, what React does with the result, and measuring before you change anything.

React itself can't run in the lab, so the React snippets below have no ▶ Try button. The plain TypeScript snippets do, and the exercises rebuild the mechanisms (shallow comparison, list windowing, keyed reconciliation, interruptible rendering) in plain TypeScript.

Render, then commit

import { useState } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);
  console.log('render', count); // runs on every render (twice per render in development with Strict Mode)
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Every update goes through the same three steps:

  1. Trigger. The first root.render(<App />), or a state update: a useState setter, a useReducer dispatch, a context value that changed, or an external store (Redux, Zustand) whose snapshot changed.
  2. Render. React calls the component whose state changed, and then, by default, every component it renders, all the way down. Rendering is just calling functions to get a new tree of elements. React compares that tree with the previous one (reconciliation) to work out what changed. Nothing touches the DOM yet.
  3. Commit. React applies only those differences to the DOM. Then it runs useLayoutEffect callbacks, the browser paints, and the useEffect callbacks run.

So a render is not a DOM update. A component can render 50 times and change the DOM zero times. Renders cost CPU time on the main thread, and that's what you optimise.

What happenedWhat re-renders
A component's state changed (not Object.is-equal to the old value)That component and everything below it
Its parent re-renderedThe component, unless it's wrapped in memo and its props are shallowly equal
A context value changed (by Object.is)Every component that reads that context, even below a memo that skipped
An external store's snapshot changedThe components subscribed to it (useSyncExternalStore)
"Its props changed" on their ownNever. Props only change because the parent rendered

Two consequences:

  • Setting state to the same value (Object.is) bails out: React doesn't re-render the children. So setItems(items) after mutating items in place does nothing visible, which is why state must be replaced, not mutated.
  • Rendering must be pure: no requests, no mutation of anything that existed before the render. React may call your component more often than you think (Strict Mode calls it twice in development; concurrent rendering can start a render and throw it away).

Reconciliation and keys

React compares the old and new trees position by position:

  • Same element type at the same position: React keeps the instance (state, DOM node, effects) and updates its props.
  • Different type: React destroys the old subtree (state gone, effect cleanups run) and mounts a new one.
  • In a list, the key decides which old child a new child matches, instead of its position.
// (not runnable here) same position, different type: the input remounts and loses what was typed
{isEditing ? <input defaultValue={name} /> : <span>{name}</span>}
import { memo } from 'react';

type Todo = { id: string; text: string; done: boolean };

const TodoRow = memo(function TodoRow({ todo }: { todo: Todo }) {
  return <li className={todo.done ? 'done' : ''}>{todo.text}</li>;
});

export function TodoList({ todos }: { todos: Todo[] }) {
  return <ul>{todos.map((todo) => <TodoRow key={todo.id} todo={todo} />)}</ul>; // a stable id from the data
}
  • Index keys (key={i}) match children by position. Insert at the top, delete, sort or filter, and the state of each row (typed text, an open menu, a checkbox in an uncontrolled input) stays at its position and ends up next to the wrong item. They're only safe for static lists without state.
  • Random keys (key={Math.random()}, or crypto.randomUUID() during render) give every row a new identity on every render: everything remounts every time.
  • Keys only have to be unique among siblings, not globally.
  • Changing a key on purpose resets a component: <ProfileForm key={userId} /> gives you a fresh form for each user.
  • A component defined inside another component is a new type on every render, so React remounts it every time:
// (not runnable here)
function OrdersPage({ orders }: { orders: Order[] }) {
  function Row({ order }: { order: Order }) {   // ❌ a new component type each time OrdersPage renders
    return <tr><td><input defaultValue={order.note} /></td></tr>;
  }
  return <table><tbody>{orders.map((o) => <Row key={o.id} order={o} />)}</tbody></table>; // inputs lose focus
}

For lists, React walks the new children once, reusing old ones by key (the "Keys keep state" exercise in the Components & props topic builds that matching). A reused child whose old position is before the last one it kept in place has to move. That one-pass rule is cheap for the common cases (append, remove, edit), and it means moving the last item to the front moves every other DOM node. Exercise 5 builds the moves and the DOM operations.

Referential equality: where most memo bugs come from

JavaScript compares objects and functions by reference, and React does the same with Object.is for state bail-outs, dependency arrays, memo props and context values:

▶ Try
const a = { color: 'red' };
const b = { color: 'red' };
const f = () => 1;
const g = () => 1;
const notANumber = Number('abc'); // NaN
console.log(a === b, Object.is(a, a), f === g); // false true false
console.log(Object.is(notANumber, notANumber), notANumber === notANumber); // true false
console.log(Object.is(0, -0), 0 === -0); // false true

A component body runs again on every render, so every object, array and function literal in it is new each time:

▶ Try
// Calling this twice is what two renders of a component do.
function renderToolbar(theme: string) {
  return {
    style: { color: theme }, // style={{ color: theme }}
    tags: ['new', 'sale'], // tags={['new', 'sale']}
    onSave: () => console.log('save'), // onSave={() => save()}
  };
}

const first = renderToolbar('dark');
const second = renderToolbar('dark');
console.log(first.style === second.style, first.tags === second.tags, first.onSave === second.onSave);
// false false false: a memoised child that receives these re-renders every time

The same thing breaks effects: useEffect(() => { ... }, [options]) where options = { pageSize: 20 } is created during render runs after every render.

memo, useMemo and useCallback

import { memo, useCallback, useMemo, useState } from 'react';

type Product = { id: string; name: string; price: number };

const ProductRow = memo(function ProductRow({ product, onSelect }: { product: Product; onSelect: (id: string) => void }) {
  return <li onClick={() => onSelect(product.id)}>{product.name}</li>;
});

export function ProductList({ products, query }: { products: Product[]; query: string }) {
  const [selected, setSelected] = useState<string | null>(null);
  const visible = useMemo(() => products.filter((p) => p.name.includes(query)), [products, query]);
  const onSelect = useCallback((id: string) => setSelected(id), []);
  return (
    <ul>
      {visible.map((p) => <ProductRow key={p.id} product={p} onSelect={onSelect} />)}
      {selected && <li>Selected: {selected}</li>}
    </ul>
  );
}
  • memo(Component, arePropsEqual?) skips re-rendering when every prop is Object.is-equal to last time (a shallow comparison, exercise 1). It doesn't stop re-renders from the component's own state or from a context it reads.
  • useMemo(compute, deps) keeps a computed value between renders and recomputes only when a dependency changes (Object.is per dependency).
  • useCallback(fn, deps) is useMemo(() => fn, deps): the same function object while the dependencies stay the same.

When they don't help:

  1. useCallback passed to a child that isn't wrapped in memo. The child re-renders anyway, because its parent did.
  2. One unstable prop defeats memo: an inline style={{ ... }}, an inline arrow, or children. <Card><Icon /></Card> creates a new <Icon /> element object on every render of the parent, so a memoised Card re-renders every time.
  3. Dependencies that change every render (an object created during render) make useMemo recompute every time, plus the overhead of checking.
  4. Cheap components. Comparing props and storing results costs something too. Memoise what the Profiler shows is slow, not everything.
  5. Correctness. useMemo is a performance hint, not a guarantee: React may throw the cache away (it does when a component suspends during its first mount, and in development when you edit the file). Don't use it to keep something alive, like a subscription or a socket. Use a ref, state or an effect for that.

Better first moves fix the structure, so nothing needs memoising:

  • Move state down. Keep hover, open/closed and input state in the small component that needs it, not in the page.
  • Lift content up. Pass the expensive part as children. When the wrapper's state changes, children is still the same element object created by its parent, so React skips it:
import { useState, type ReactNode } from 'react';

function ScrollShadow({ children }: { children: ReactNode }) {
  const [scrolled, setScrolled] = useState(false); // changes while scrolling
  return (
    <div className={scrolled ? 'shadow' : ''} onScroll={(e) => setScrolled(e.currentTarget.scrollTop > 0)}>
      {children /* not re-rendered when `scrolled` changes */}
    </div>
  );
}
// <ScrollShadow><ExpensiveDashboard /></ScrollShadow>
  • Stabilise context values. <AuthContext value={{ user, logout }}> creates a new object on every render of the provider, so every consumer re-renders. Wrap the value in useMemo, or split one big context into a value context and a dispatch context, so components that only dispatch don't re-render when the value changes.
  • Don't copy props into state and sync them with an effect. Compute derived values during render (with useMemo if it's expensive). It's fewer renders and fewer bugs.

The React Compiler

The React Compiler (stable since version 1.0 in October 2025) is a build-time tool: a Babel plugin, with integrations for Vite, Next.js and Expo. It analyses each component and hook and adds the memoisation for you: derived values, callbacks and JSX are cached and recomputed only when their inputs change. It's more fine-grained than hand-written useMemo, and it can memoise after an early return, where hooks aren't allowed.

// (not runnable here) what you write
function Price({ amount, currency }: { amount: number; currency: string }) {
  const format = new Intl.NumberFormat('en', { style: 'currency', currency });
  return <span className="price">{format.format(amount)}</span>;
}
roughly what the compiler emits: a per-component cache ($) checked against the inputs
function Price({ amount, currency }) {
  const $ = _c(5);
  let format;
  if ($[0] !== currency) { format = new Intl.NumberFormat(...); $[0] = currency; $[1] = format; } else { format = $[1]; }
  let span;
  if ($[2] !== amount || $[3] !== format) { span = <span ...>{format.format(amount)}</span>; $[2] = amount; $[3] = format; $[4] = span; } else { span = $[4]; }
  return span;
}
  • It relies on the Rules of React: rendering is pure, props and state are never mutated, hooks are called unconditionally. Components it can't prove safe are left as they are. The rules are checked by the eslint-plugin-react-hooks recommended config, so turn that on first.
  • The "use no memo" directive at the top of a component opts it out, which is useful when you suspect the compiler is involved in a bug.
  • For new code, write plain code and let the compiler memoise. Leave existing useMemo/useCallback calls in place unless you test the change, because removing them can change what gets cached.
  • What it doesn't fix: a slow first render, 10,000 DOM rows (virtualise), index keys, state that lives too high, effects that fetch too often, or code it skipped. You still measure.

Long lists: virtualisation

Rendering 10,000 rows means 10,000 component calls and 10,000 DOM subtrees to create, lay out and keep in memory. memo doesn't help with the first render, and it doesn't make the DOM smaller. Virtualisation (windowing) renders only the rows in the viewport plus a few extra (the overscan), inside a spacer as tall as the whole list:

▶ Try
const rowHeight = 32;
const viewportHeight = 480;
const rowCount = 10_000;
const overscan = 3;

function windowAt(scrollTop: number) {
  const start = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
  const end = Math.min(rowCount, Math.ceil((scrollTop + viewportHeight) / rowHeight) + overscan);
  return { start, end, rendered: end - start, offsetTop: start * rowHeight };
}

console.log(windowAt(0)); // 18 rows rendered, not 10,000
console.log(windowAt(160_000));
import { useRef } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

type Order = { id: string; customer: string };

export function OrderList({ orders }: { orders: Order[] }) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const virtualizer = useVirtualizer({
    count: orders.length,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 32,
    overscan: 5,
  });
  return (
    <div ref={scrollRef} style={{ height: 480, overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
        {virtualizer.getVirtualItems().map((row) => (
          <div
            key={orders[row.index].id}
            style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: row.size, transform: `translateY(${row.start}px)` }}
          >
            {orders[row.index].customer}
          </div>
        ))}
      </div>
    </div>
  );
}

Trade-offs: rows that aren't rendered can't be found with Ctrl+F, screen readers only see what's in the DOM (add aria-rowcount and aria-rowindex to grids), and variable row heights need measuring. Pagination or "load more" is often the better UX for lists people search through. For long pages that aren't huge lists, the CSS content-visibility: auto property skips layout and paint for off-screen sections with no JavaScript at all. Exercise 2 does the windowing math.

Keeping input responsive: transitions and deferred values

React's rendering is interruptible. Updates have priorities: typing and clicking are urgent, and updates you mark as transitions can wait and can be interrupted. React renders a transition in slices of about 5 ms, checking between components, and gives the main thread back to the browser between slices (see the Event loop & async topic). It can't stop in the middle of one component, so slow work only benefits when it's spread over many components (rows, cells), not done in one.

import { useState, useTransition } from 'react';
import { Results, Spinner } from './search';

export function Search() {
  const [text, setText] = useState('');
  const [query, setQuery] = useState('');
  const [isPending, startTransition] = useTransition();
  return (
    <>
      <input
        value={text}
        onChange={(e) => {
          setText(e.target.value); // urgent: the input must update now
          startTransition(() => setQuery(e.target.value)); // can wait, and can be interrupted
        }}
      />
      {isPending && <Spinner />}
      <Results query={query} />
    </>
  );
}

useDeferredValue does the same when you receive a value instead of owning the setter:

import { memo, useDeferredValue, useState } from 'react';
import { searchProducts } from './api';
import { ResultRow } from './result-row';

const SlowResults = memo(function SlowResults({ query }: { query: string }) {
  // Each row is its own component, so React can pause between rows when typing interrupts.
  return <ul>{searchProducts(query).map((p) => <ResultRow key={p.id} product={p} />)}</ul>;
});

export function Search() {
  const [text, setText] = useState('');
  const deferredText = useDeferredValue(text); // lags behind `text` while React catches up
  const isStale = text !== deferredText;
  return (
    <>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <div style={{ opacity: isStale ? 0.6 : 1 }}>
        <SlowResults query={deferredText} />
      </div>
    </>
  );
}

On each keystroke React first renders with the old deferred value. That render is fast, because SlowResults is memoised and its props didn't change. React commits it (the input updates), then renders SlowResults with the new value in the background. If you type again before that finishes, React throws the unfinished render away and starts over with the latest value. Users only ever see complete renders. Exercise 6 builds this scheduling.

  • Without memo on the slow component, useDeferredValue doesn't help: the urgent render re-renders it anyway.
  • Never put the input's own value in a transition. A controlled input whose state lags behind the keyboard drops characters and feels broken.
  • Transitions don't make work faster, they make it interruptible. There's no fixed delay either, so this isn't a debounce, and it doesn't reduce network requests (debounce and cache for that).
  • If a transition causes a component to suspend, React keeps showing the old UI instead of the Suspense fallback. The Testing & architecture topic covers Suspense.
  • In React 19, startTransition also accepts async functions, called Actions. The Forms & data topic covers them.

Measuring

Measure first, change one thing, measure again.

  • Use a production build. Development builds are much slower, and Strict Mode renders twice. Throttle the CPU (4x or 6x in Chrome DevTools) to see what users on slower laptops see.
  • React DevTools Profiler. Record an interaction, then read the flame graph (each commit, which components rendered and how long they took) and the ranked chart (the slowest components). In the settings, turn on "Record why each component rendered while profiling", and "Highlight updates when components render" to see renders happen live.
  • Chrome Performance panel. Recent React versions add React's own tracks there (scheduler and component renders) next to the browser's own timeline, so you can see a long render next to the layout and paint it caused.
  • <Profiler> in code, for numbers you can log or send to telemetry:
import { Profiler, type ProfilerOnRenderCallback } from 'react';
import { appInsights } from './telemetry';
import { OrdersGrid } from './OrdersGrid';

const onRender: ProfilerOnRenderCallback = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
  if (actualDuration > 16) {
    appInsights.trackMetric({ name: `render:${id}`, average: actualDuration }, { phase });
  }
};

export const OrdersPage = () => (
  <Profiler id="OrdersGrid" onRender={onRender}>
    <OrdersGrid />
  </Profiler>
);
onRender argumentMeaning
phase'mount', 'update', or 'nested-update' (state set during a commit, usually in useLayoutEffect: a synchronous re-render before paint)
actualDurationms spent rendering this subtree for this commit. Low when memoisation skips most of it
baseDurationms a full re-render of the subtree would take with no skipping: the worst case
startTime, commitTimewhen React started rendering this update, and when it committed it

<Profiler> is turned off in normal production builds. To measure in production, use React's profiling build (alias react-dom/client to react-dom/profiling in the bundler). Exercise 4 turns these samples into a report and a batched telemetry sink.

The metric users feel is INP (Interaction to Next Paint): the time from a click or keystroke to the next frame. Long renders, nested updates and huge DOMs all show up there. The web-vitals library measures it (onINP), and you can send it to your monitoring service as a custom metric (Amazon CloudWatch, Azure Application Insights, Google Cloud Monitoring, or a vendor such as Datadog).

Common mistakes

  • Wrapping everything in useMemo and useCallback "just in case", while still passing inline objects to the memoised children.
  • key={index} on lists that reorder or hold state, and random keys generated during render.
  • Components defined inside other components.
  • A context value created inline in the provider, so every consumer re-renders on every provider render.
  • Copying props into state and syncing them with useEffect.
  • Measuring in development mode and optimising what isn't slow in production.
  • Putting a controlled input's state in a transition, or expecting useDeferredValue to help without memo on the slow child.

In a real codebase

Side note
  • Big grids (orders, audit logs): a virtualised table (TanStack Table with TanStack Virtual, or AG Grid), server paging and sorting, row ids as keys, and memoised row components with stable callbacks.
  • Search as you type: an urgent input, deferred results, and a server cache keyed by the query (Forms & data topic), plus a debounce for the network.
  • Dashboards: state colocated in each widget, split contexts, charts that get stable props, and a <Profiler> around each widget that reports slow renders.
  • Code review habits: "why does this re-render?" is answered with the Profiler, not by adding memo.

Angular for comparison

Side note
ReactAngular
A parent render re-renders its childrenDefault change detection checks the whole component tree
memo(Component)ChangeDetectionStrategy.OnPush: re-check only when an input changes by reference, an event fires inside, or a signal read in the template changes
key={item.id}@for (item of items; track item.id)
useMemocomputed()
TanStack VirtualCDK cdk-virtual-scroll-viewport
lazy() + <Suspense>@defer blocks

The same lesson applies to both: new object references defeat the cheap checks, and stable identities make them work.

The exercises

  1. shallowEqual and memo: the comparison behind memo, with the NaN, -0 and missing-key edge cases.
  2. Virtual list window: the math of windowing with overscan and clamping.
  3. Why did this render?: tell real prop changes from new references and new functions.
  4. Profiler report and telemetry: a ranked report from onRender samples, and a batched sink for slow renders.
  5. Keyed list reconciliation: React's one-pass key matching, moves and DOM operations.
  6. Interruptible rendering (useDeferredValue): background renders that resume, restart and commit all at once.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app