The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·22

React

React from its mental model up: components, JSX, props, state, events, lists and keys; every core hook; the render–reconcile–commit cycle; and modern React 19: concurrent rendering, transitions, Suspense, streaming, Server Components, hydration, actions, error boundaries, the React Compiler and view transitions.

48 topics · ~42 min read · 32-question quiz
Updated Suggest a correction

Start here: your first React app

What React is

React is a JavaScript library for building user interfaces out of components. It implements chapter 21's idea directly: you write functions that describe what the UI should look like for the current state, and React works out the DOM changes (by diffing, chapter 21) whenever state changes. It's the most widely used UI library, maintained by Meta and a large community, and the foundation of frameworks such as Next.js and React Router (chapter 24).

JSX: HTML-like syntax inside JavaScript

React components return JSX, which looks like HTML but is JavaScript:

JSX
const el = <li className={item.done ? "done" : ""}>{item.text} <b>₹{item.price}</b></li>;

A compiler (Babel, esbuild, SWC; your build tool runs it) turns that into ordinary function calls that create plain objects describing the element:

JavaScript
const el = jsxs("li", { className: item.done ? "done" : "", children: [
  item.text, " ", jsxs("b", { children: ["₹", item.price] })
] });

JSX rules worth knowing on day one:

  • Curly braces { } embed any JavaScript expression: variables, calls, ternaries, map. Not statements (if, for): use &&, ? : or compute beforehand.
  • Attributes use the DOM property names: className (not class), htmlFor (not for), onClick (camelCase events), style={{ color: "red" }} (an object).
  • A component returns one root; wrap siblings in a fragment <>…</>.
  • Text in braces is escaped automatically, so user data can't inject HTML (the lab adds <img src=x onerror=…> as an item; it shows as text, like textContent in chapter 17).
  • Component names start with a capital letter (<Item />); lowercase names are HTML elements.

Components and props

A component is a function that takes props (one object) and returns JSX:

JSX
function Item({ item, onToggle, onRemove }) {
  return (
    <li className={item.done ? "done" : ""}>
      <span>{item.text}</span>
      <button type="button" onClick={() => onToggle(item.id)}>{item.done ? "Undo" : "Done"}</button>
      <button type="button" onClick={() => onRemove(item.id)}>Remove</button>
    </li>
  );
}

onToggle and onRemove are functions passed down by the parent: events flow up (chapter 21). Props are read-only: a component never changes its own props.

State with useState

State is data that changes over time and should update the screen. useState gives a component a state variable and a function to change it:

JSX
const [text, setText] = useState("");

Calling setText("Idli") stores the new value and tells React to re-render the component: call the function again and update the DOM to match. That's the only correct way to change state. Functions starting with use are hooks; call them at the top level of a component (never inside ifs or loops), because React identifies each hook by the order of the calls.

The shopping list in React

Chapter 17's app, rebuilt:

JSX
import { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";

function ShoppingList() {
  const [items, setItems] = useState(() => JSON.parse(localStorage.getItem("items") ?? "[]"));
  const [text, setText] = useState("");

  useEffect(() => { localStorage.setItem("items", JSON.stringify(items)); }, [items]);   // save whenever items change

  function add(event) {
    event.preventDefault();
    if (!text.trim()) return;
    setItems([...items, { id: crypto.randomUUID(), text, done: false }]);
    setText("");
  }
  const toggle = id => setItems(items.map(i => (i.id === id ? { ...i, done: !i.done } : i)));
  const remove = id => setItems(items.filter(i => i.id !== id));
  const left = items.filter(i => !i.done).length;            // derived: computed, never stored

  return (
    <main>
      <h1>Shopping list</h1>
      <form onSubmit={add}>
        <label htmlFor="item">New item</label>
        <input id="item" value={text} onChange={e => setText(e.target.value)} />
        <button>Add</button>
      </form>
      <ul>
        {items.map(item => <Item key={item.id} item={item} onToggle={toggle} onRemove={remove} />)}
      </ul>
      <p>{left} item{left === 1 ? "" : "s"} left</p>
    </main>
  );
}

createRoot(document.getElementById("root")).render(<ShoppingList />);

Driven in Chromium (add three items, mark the first done, remove the second):

Text
[x] Rice (5 kg), [ ] Toor dal, [ ] <img src=x onerror=alert(1)> | 2 items left
[x] Rice (5 kg), [ ] <img src=x onerror=alert(1)> | 1 item left
saved: Rice (5 kg) ✓, <img src=x onerror=alert(1)>

Read it against chapter 17's version. There's no querySelector, no createElement, no manual counter update: the component describes the whole UI from items and text, and React updates the DOM. Notice:

  • The input is controlled: its value comes from state and every keystroke goes through setText, so state is the single source of truth (and clearing it is just setText("")).
  • items.map(item => <Item key={item.id} … />): each list element needs a stable key (chapter 21's lab shows the bug without one).
  • Updates create new arrays and objects ([...items, x], items.map(...), { ...i, done: !i.done }) instead of changing the old ones. React decides whether something changed by comparing references, so mutating in place (items.push(x)) is invisible to it.
  • left is derived: computed during render from items, never stored in its own state, so it can't drift.
  • useState(() => …) with a function reads localStorage only on the first render.

Effects: synchronising with the outside world

Rendering must be pure: given the same props and state, return the same JSX, without side effects. Work that talks to the outside world (saving to storage, fetching data, subscribing to a socket, setting a timer) goes in an effect, which React runs after the screen updates:

JSX
useEffect(() => {
  localStorage.setItem("items", JSON.stringify(items));
}, [items]);                         // the dependency array: re-run only when items changes

An effect can return a cleanup function that undoes it (disconnect, cancel, clear the timer); React runs it before re-running the effect and when the component disappears. Fetching data, the classic example:

JSX
useEffect(() => {
  let ignore = false;
  fetch(`/api/dishes/${id}`).then(r => r.json()).then(dish => { if (!ignore) setDish(dish); });
  return () => { ignore = true; };    // a newer id arrived: ignore this response if it comes late
}, [id]);

The lab shows why the ignore flag matters (chapter 15's out-of-order responses, again). In real apps, prefer a data library (TanStack Query, or your framework's loaders, chapters 24–25) over hand-written fetching effects.

Four mistakes everyone makes once

Measured in Chromium:

Text
after mutating and setting the same array: dosa                 (items.push("idli"); setItems(items))
after setting a new array:                 dosa, idli, vada     (setItems([...items, "vada"]))
+2 written as setCount(count + 1) twice:   1
+2 written as setCount(c => c + 1) twice:  3                    (1 from before, +2)
effect with no dependency array ran 50 times (stopped by a guard at 50)
console.error: Each child in a list should have a unique "key" prop.
  1. Mutating state: push changed the array but setItems received the same array, so React saw no change and didn't re-render. Worse, the hidden "idli" reappeared later with the next real update: the state was silently corrupted.
  2. Stale values: inside one click, count is a fixed snapshot (0), so both calls set 1. When the next value depends on the previous one, pass an updater function (c => c + 1).
  3. Effect loops: an effect without a dependency array runs after every render; if it sets state, that causes another render, forever. Always give a dependency array, and include every value the effect reads.
  4. Missing keys in lists: React warns in the console, and list items can keep the wrong state.

How deep to go in React

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Read JSX, components, props, state and effects
L2 Build apps with hooks, controlled forms, lists with keys, context and a data-fetching library
L3 Explain rendering and reconciliation (Fiber), batching, effects' lifecycle, concurrent features, Suspense, Server Components and hydration
L4 Diagnose extra re-renders, stale closures, effect loops, races, hydration mismatches and slow interactions with the Profiler
L5 Design component and state architecture, server/client boundaries and data loading for a product
L6 Run React at scale: upgrades, the React Compiler, design systems, performance budgets across teams

Fundamentals

The mental model: UI as a function of state

React's core idea is UI = f(state). You describe what the UI should look like for the current state, and React works out how to update the DOM to match. You never write "find the badge and increment its text". You write "the badge shows count" and change count. That's declarative programming (Vol. 1 ch. 2) applied to the DOM, and it's the main reason React (2013) displaced jQuery-style imperative DOM code.

React is a library for building component trees. The rendering target is pluggable: react-dom for the browser, React Native for iOS and Android, and others for PDFs, terminals and 3D. Routing, data fetching and bundling come from frameworks around it (chapter 24).

Components

A React component is a function that returns JSX (class components still work but are legacy):

TSX
type Props = { name: string; unread?: number };

export function Greeting({ name, unread = 0 }: Props) {
  return (
    <header className="greeting">
      <h1>Hello, {name}</h1>
      {unread > 0 && <p>You have {unread} unread messages</p>}
    </header>
  );
}

Rules:

  • Component names start with a capital letter. <greeting> would be treated as an HTML tag.
  • Components must be pure during rendering: the same props, state and context must produce the same output, with no side effects while rendering (no fetching, no mutating external variables, no subscribing). Side effects belong in event handlers or effects. React may call your component more than once, out of order, or abandon a render (concurrent rendering, below). In development, Strict Mode deliberately double-invokes components and effects to expose impurity.
  • A component returns one root (use <>…</> fragments to group without a wrapper div).

JSX

JSX is syntax sugar for React.createElement (in React 17+, the automatic runtime's jsx()). It compiles into plain objects called React elements, which are lightweight descriptions of UI, not DOM nodes:

TSX
<button className="btn" onClick={save} disabled={busy}>Save</button>
// compiles to roughly:
jsx("button", { className: "btn", onClick: save, disabled: busy, children: "Save" })
// → { type: "button", props: { className: "btn", onClick: save, disabled: busy, children: "Save" }, key: null }

JSX facts:

  • Expressions go in {}: {user.name}, {items.length}, {cond ? <A/> : <B/>}, {cond && <A/>}. Watch out: {count && <Badge/>} renders 0 when count is 0, so use {count > 0 && …}.
  • Attributes use DOM property names: className, htmlFor, tabIndex, onClick. aria-* and data-* stay hyphenated.
  • style takes an object: style={{ marginTop: 8 }}.
  • Text is escaped automatically, so {userInput} can't inject HTML. The escape hatch, dangerouslySetInnerHTML={{ __html }}, is named that way on purpose (chapter 28).
  • null, undefined, false and true render nothing.

Props

Props are a component's inputs, passed from parent to child. They're read-only (never mutate them), and they can be any value: strings, numbers, objects, functions (callbacks), JSX (children and slots), even components.

TSX
function Dialog({ title, children, onClose }: { title: string; children: React.ReactNode; onClose: () => void }) {
  return (
    <div role="dialog" aria-labelledby="dlg-title">
      <h2 id="dlg-title">{title}</h2>
      {children}
      <button onClick={onClose}>Close</button>
    </div>
  );
}

Data flows one way: down, through props. Changes flow up through callbacks (onChange, onClose). This unidirectional data flow makes it easy to trace where values come from, unlike two-way binding, where any widget can change any model.

State

State is data a component remembers between renders that changes over time. useState declares it:

TSX
function Counter() {
  const [count, setCount] = useState(0);          // [current value, setter]
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

How state actually behaves:

  • Setting state schedules a re-render. It doesn't change the variable in the currently running render. count is a constant snapshot for that render.
  • Updates are batched. Several setX calls in one event handler (and since React 18, also in promises and timeouts) produce one re-render.
  • Updater functions compute from the latest pending value: setCount(c => c + 1). Use them when the new state depends on the old.
TSX
function handleClick() {
  setCount(count + 1);
  setCount(count + 1);          // both use the same snapshot → +1 total
  setCount(c => c + 1);
  setCount(c => c + 1);         // queued updaters → +2 more
  console.log(count);           // still the OLD value: state is a snapshot per render
}
  • Treat state as immutable. Create new objects and arrays instead of mutating, because React compares with Object.is and a mutated object looks unchanged:
TSX
setTodos(todos.map(t => (t.id === id ? { ...t, done: !t.done } : t)));   // ✓ new array, new object
setTodos([...todos, newTodo]);                                         // ✓
todos.push(newTodo); setTodos(todos);                                  // ✗ same reference: no re-render
  • State lives at a position in the tree, not in the function. Two <Counter/>s each have their own count. Moving a component to a different position, or changing its key, resets its state.
  • Lift state up to the closest common parent when siblings need the same data. Don't duplicate or derive state you can compute: const total = items.reduce(…) during render, not a total state kept in sync by an effect.

Events

React event handlers are props named onX, which receive a synthetic event (a cross-browser wrapper around the native event, with the same API: preventDefault, stopPropagation, target, currentTarget):

TSX
<form onSubmit={(e) => { e.preventDefault(); submit(new FormData(e.currentTarget)); }}>
  <input onChange={(e) => setQuery(e.target.value)} value={query} />
  <button type="submit">Search</button>
</form>

Pass a function (onClick={handle} or onClick={() => handle(id)}), not a call (onClick={handle()}, which runs during render). React delegates events at the root container (chapter 17). Controlled inputs (value + onChange) keep React state as the single source of truth. Uncontrolled inputs (defaultValue + reading the value through a ref or FormData) leave the DOM in charge. They're simpler and faster for large forms, and React 19's form actions favour them.

Lists and keys

Render lists with map, giving each item a key that's stable, unique among siblings, and tied to the item's identity:

TSX
<ul>
  {orders.map(order => (
    <OrderRow key={order.id} order={order} />      // ✓ a database id
  ))}
</ul>

Keys tell the reconciler (below) which item is which across renders. Without good keys, React matches items by position:

Key choice Consequence when items are inserted, removed or reordered
Stable id (order.id) Correct: the right components move, keeping their state and DOM (focus, input text, animations)
Array index State and DOM stick to positions: delete row 2 and row 3's typed text appears in row 2. It's acceptable only for static lists that never reorder
Math.random() / crypto.randomUUID() during render A new key every render: every item remounts, losing state, and it's slow

You can also change a key on purpose to reset a component: <ProfileForm key={userId} /> gives a fresh form state when the user changes.

Composition and children

Chapter 21 covered composition. In React it's done with children and slot-like props:

TSX
function Layout({ sidebar, children }: { sidebar: React.ReactNode; children: React.ReactNode }) {
  return <div className="layout"><aside>{sidebar}</aside><main>{children}</main></div>;
}
<Layout sidebar={<Filters />}><ProductGrid /></Layout>

Passing elements as props also helps performance. If Layout re-renders because of its own state, the sidebar and children elements were created by the parent, so React can skip re-rendering them unless the parent re-renders.

Hooks

Hooks are functions starting with use that let function components use React features. Two rules (enforced by eslint-plugin-react-hooks): call hooks only at the top level (not inside loops, conditions or nested functions), and only from components or other hooks. React identifies each hook by its call order in the component, so the order must be the same on every render.

useState and useReducer

useState (above) suits independent values. useReducer suits state with several related fields and transitions, or when the next state depends on the previous one in complex ways. It's the same pattern as Redux and Elm, and the same as a state machine's transition function:

TSX
type State = { status: "idle" | "loading" | "success" | "error"; items: Item[]; error?: string };
type Action =
  | { type: "fetch" }
  | { type: "success"; items: Item[] }
  | { type: "failure"; error: string };

function reducer(state: State, action: Action): State {   // pure: (state, action) → new state
  switch (action.type) {
    case "fetch":   return { ...state, status: "loading", error: undefined };
    case "success": return { status: "success", items: action.items };
    case "failure": return { ...state, status: "error", error: action.error };
  }
}

function Items() {
  const [state, dispatch] = useReducer(reducer, { status: "idle", items: [] });
  // dispatch({ type: "fetch" }) … the logic lives in one testable pure function
}

useEffect

useEffect synchronises a component with an external system: a subscription, a WebSocket, a third-party widget, the document title, a timer, or a non-React DOM API. It runs after the component renders and the browser paints:

TSX
function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    const conn = createConnection(roomId);    // set up
    conn.connect();
    return () => conn.disconnect();           // clean up: before re-running and on unmount
  }, [roomId]);                                // dependencies: re-sync when roomId changes
  // …
}

The dependency array lists every reactive value the effect uses (props, state, and values derived from them). React re-runs the effect when any of them changes (compared with Object.is). [] means "on mount only", and omitting the array means "after every render". Don't lie about dependencies to stop re-runs. Restructure instead: move the value inside the effect, use updater functions, or use useEffectEvent for non-reactive logic.

You probably don't need an effect (the React docs have a whole page with that title). Common misuses:

Misuse Instead
Computing derived data in an effect + state (useEffect(() => setTotal(sum(items)), [items])) Compute during render (useMemo if expensive)
Resetting state when a prop changes key the component
Responding to an event (POST on submit) in an effect Do it in the event handler
Fetching data in effects A data library (TanStack Query, SWR), framework loaders, or Server Components (chapters 24–25). Effects bring race conditions, waterfalls, no caching and no SSR
Chains of effects setting state that trigger other effects Compute in one place, often a reducer

When you do fetch in an effect, handle races (chapter 15):

TSX
useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/users/${id}`, { signal: controller.signal })
    .then(r => r.json()).then(setUser)
    .catch(e => { if (e.name !== "AbortError") setError(e); });
  return () => controller.abort();            // a stale request can't overwrite newer data
}, [id]);

useLayoutEffect runs synchronously after DOM mutations and before paint. Use it only to measure layout and adjust before the user sees the frame (tooltip positioning), because it blocks painting. useInsertionEffect is for CSS-in-JS libraries.

useRef

useRef returns a mutable box { current } that persists across renders without causing re-renders. It has two uses:

TSX
function SearchBox() {
  const inputRef = useRef<HTMLInputElement>(null);            // 1. a reference to a DOM node
  const timerRef = useRef<number | undefined>(undefined);     // 2. any mutable value that isn't UI state
  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current?.focus()}>Focus</button>
    </>
  );
}

Don't read or write ref.current during rendering (except for lazy initialisation), because that makes rendering impure. In React 19, ref is an ordinary prop for function components (forwardRef is no longer needed), and ref callbacks can return a cleanup function.

useMemo and useCallback

These cache values between renders:

TSX
const visible = useMemo(() => filterAndSort(products, query, sort), [products, query, sort]);  // cache a value
const handleSelect = useCallback((id: string) => setSelected(id), []);                        // cache a function

They exist for performance only. Use them when (1) a calculation is measurably expensive (over about 1 ms), or (2) referential stability matters: passing an object or function to a memo-wrapped child, or using it as an effect dependency. Every render otherwise creates new objects and functions, so a child memoised with React.memo would still re-render if it receives onSelect={() => …}.

The React Compiler (below) inserts this memoisation automatically, so in compiler-enabled codebases you rarely write useMemo or useCallback by hand.

useContext

Context passes values deep into the tree without prop drilling:

TSX
const ThemeContext = createContext<"light" | "dark">("light");

function App() {
  const [theme, setTheme] = useState<"light" | "dark">("light");
  return (
    <ThemeContext value={theme}>                     {/* React 19: <Context> works as the provider */}
      <Page />
    </ThemeContext>
  );
}
function Button() {
  const theme = useContext(ThemeContext);           // or use(ThemeContext), which can be called conditionally
  return <button className={`btn btn-${theme}`}>…</button>;
}

Context suits low-frequency, widely needed values: theme, locale, the current user, a router, a design-system configuration, a dependency-injected service. It's not a state manager: every consumer re-renders when the value changes, so putting fast-changing global state in one big context re-renders large parts of the app. Split contexts by update frequency, memoise provider values, or use a store with selectors (chapter 25).

Custom hooks

Custom hooks extract reusable stateful logic, not UI, into functions. They're React's main abstraction for sharing behaviour (chapter 21):

TSX
function useDebouncedValue<T>(value: T, delayMs = 300): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(t);
  }, [value, delayMs]);
  return debounced;
}

function useOnlineStatus() {
  return useSyncExternalStore(                        // the correct way to subscribe to external stores
    (cb) => { addEventListener("online", cb); addEventListener("offline", cb);
              return () => { removeEventListener("online", cb); removeEventListener("offline", cb); }; },
    () => navigator.onLine,
    () => true,                                       // server snapshot
  );
}

function Search() {
  const [q, setQ] = useState("");
  const debouncedQ = useDebouncedValue(q);
  const online = useOnlineStatus();
  const { data } = useQuery({ queryKey: ["search", debouncedQ], queryFn: ({ signal }) => search(debouncedQ, signal) });
  // …
}

Each component that calls a custom hook gets its own independent state. Hooks share logic, not state. Other built-in hooks: useId (stable unique IDs for aria-* and label wiring, SSR-safe), useSyncExternalStore, useTransition/useDeferredValue (below), useActionState/useFormStatus/useOptimistic (actions, below), use (read promises and context), useImperativeHandle, and useEffectEvent (non-reactive logic inside effects, newer).

Rendering

Render, reconcile, commit, paint

Text
state/props change
→ render         call components → new React element tree (pure, interruptible)
→ reconciliation diff the new tree against the previous one (Fiber)
→ commit         apply the minimal DOM mutations; run ref callbacks, layout effects
→ paint          browser style/layout/paint/composite (chapter 18)
→ passive effects (useEffect) run after paint
  1. Trigger: an initial root.render(), or a state update (setState, dispatch, a context change, an external store change).
  2. Render phase: React calls your components to get the new element tree. It recurses into children by default: when a component re-renders, all its descendants re-render too, unless they're memoised and their props are unchanged. Rendering is pure computation, and it can be paused, interrupted and resumed in concurrent mode.
  3. Reconciliation: React compares the new tree with the previous one to find the minimum changes (next section).
  4. Commit phase: React applies the DOM changes synchronously in one batch, attaches refs, and runs useLayoutEffect. Commit can't be interrupted, so the DOM is never left half-updated.
  5. Paint: the browser renders the frame.
  6. Passive effects (useEffect) run after paint.

Re-rendering is not the same as DOM updating. A component can re-render a hundred times and produce no DOM changes if its output is the same. Re-renders cost JavaScript time, which matters for INP (chapter 27), but they don't always touch the DOM.

Reconciliation and Fiber

Diffing two arbitrary trees optimally is O(n³). React uses an O(n) heuristic based on two assumptions:

  1. Different element types produce different trees. If <div> becomes <section>, or <Profile> becomes <Settings>, React tears down the old subtree (unmounting components and destroying their state and DOM) and builds the new one from scratch.
  2. Keys identify children across renders. For lists, React matches children by key, so it can move, insert and delete efficiently.

For the same type at the same position, React keeps the DOM node and component instance (and so the state) and updates only the changed attributes and props.

TSX
{isAdmin ? <AdminPanel /> : <UserPanel />}   // different types: switching remounts, state lost (usually desired)
{isEditing ? <input key="edit" /> : <p key="view">{text}</p>}
// Bug: a component *defined inside* another component is a NEW type each render → remounts every time
function Parent() {
  function Child() { return <input />; }      // ✗ defined during render: loses focus and state on every keystroke
  return <Child />;
}

Fiber (React 16+) is React's reconciliation engine. Every element becomes a fiber: a JavaScript object representing a unit of work, linked to its parent, child and sibling, and holding state, hooks (a linked list in call order, which is why hook order must be stable) and effects. Because work is split into fibers, React can pause rendering to let the browser handle input, prioritise urgent updates over less urgent ones (the lanes model), and discard work that's become stale. It's cooperative scheduling (Vol. 1 ch. 8) implemented in user space on the main thread, yielding at fiber boundaries.

React keeps two trees: the current tree (what's on screen) and the work-in-progress tree being built. On commit they swap. This is double buffering, the same technique graphics and game engines use.

Performance controls

  • React.memo(Component) skips re-rendering when props are shallowly equal.
  • Move state down: keep fast-changing state in the smallest component that needs it.
  • Lift content up: pass expensive subtrees as children so they aren't re-created.
  • Split contexts, or use selector-based stores (chapter 25).
  • Virtualise long lists (TanStack Virtual, react-window, chapter 27).
  • Measure first: React DevTools Profiler ("why did this render?"), the Chrome Performance panel, and <Profiler>.

Modern React

Concurrent rendering

Concurrent rendering (React 18+) means React can prepare multiple versions of the UI at once and interrupt a render in progress. It's still single-threaded: "concurrent" here means interleaved, not parallel (Vol. 1 ch. 8's distinction). Rendering yields to the browser periodically (roughly every 5 ms), so an expensive re-render no longer blocks typing. Urgent updates such as typing can interrupt non-urgent ones such as filtering a 10,000-row table. You opt into non-urgent rendering with transitions and deferred values.

Transitions

A transition marks a state update as non-urgent. React keeps showing the current UI and stays responsive while preparing the new one in the background, and it abandons the work if a newer update arrives:

TSX
function Search() {
  const [query, setQuery] = useState("");
  const [isPending, startTransition] = useTransition();
  const [results, setResults] = useState<Item[]>([]);

  function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    setQuery(e.target.value);                         // urgent: the input updates immediately
    startTransition(() => {
      setResults(filterHugeList(e.target.value));     // non-urgent: interruptible
    });
  }
  return (
    <>
      <input value={query} onChange={onChange} />
      <div style={{ opacity: isPending ? 0.6 : 1 }}><ResultList items={results} /></div>
    </>
  );
}

// useDeferredValue: the same idea, from the consumer side
const deferredQuery = useDeferredValue(query);   // lags behind query while rendering is busy
const list = useMemo(() => <ResultList query={deferredQuery} />, [deferredQuery]);

In React 19, startTransition accepts async functions ("actions"), and navigations in frameworks are wrapped in transitions, so the old page stays visible and interactive while the new one loads.

Suspense

<Suspense> lets a component wait for something (code, data, images, fonts) declaratively. While anything inside is suspended, React shows the nearest fallback:

TSX
const Settings = lazy(() => import("./Settings"));     // code splitting: loads on first render

<Suspense fallback={<PageSkeleton />}>
  <Header />
  <Suspense fallback={<FeedSkeleton />}>               {/* nested boundaries: reveal progressively */}
    <Feed />                                            {/* suspends while its data loads */}
  </Suspense>
  <Settings />
</Suspense>

How does a component "suspend"? It reads a promise that isn't resolved yet: through React 19's use(promise), through a Suspense-enabled data library (TanStack Query's useSuspenseQuery, Relay), through framework data loaders, or through lazy(). React catches the suspension, shows the fallback, and retries the render when the promise resolves.

TSX
function Feed({ feedPromise }: { feedPromise: Promise<Post[]> }) {
  const posts = use(feedPromise);                       // suspends until resolved; throws to an error boundary on rejection
  return posts.map(p => <PostCard key={p.id} post={p} />);
}

Suspense boundaries are a design tool: place them where a loading state makes sense to the user. Inside a transition, React won't replace already visible content with a fallback. It keeps the old UI until the new one is ready, which avoids jarring flashes. Combine Suspense with streaming for server rendering.

Streaming SSR

Server-side rendering (SSR) renders React to HTML on the server so users see content before JavaScript loads (chapter 24). Streaming SSR (renderToPipeableStream / renderToReadableStream) sends HTML progressively:

  1. Immediately flush the shell (layout, navigation, and the Suspense fallbacks for slow parts).
  2. As each suspended section's data resolves on the server, stream its HTML into the same response, along with a tiny inline script that swaps it into place.
  3. The browser shows content as it arrives (chapter 18: HTML parses incrementally), and hydrates each section independently (selective hydration), prioritising the parts the user interacts with.

The result is a fast first paint and time-to-first-byte, with no "the whole page waits for the slowest query".

Server Components

React Server Components (RSC) are components that run only on the server, at request time or at build time. Their code is never sent to the browser. They can be async and read from databases, file systems or internal services directly, and they send only their rendered output (a serialised element tree, the RSC payload) to the client:

TSX
// app/orders/page.tsx — a Server Component (the default in Next.js App Router)
import { db } from "@/server/db";
import { OrderFilters } from "./OrderFilters";          // a Client Component

export default async function OrdersPage({ searchParams }: { searchParams: Promise<{ status?: string }> }) {
  const { status } = await searchParams;
  const orders = await db.order.findMany({ where: { status }, take: 50 });   // runs on the server; no API layer needed
  return (
    <>
      <OrderFilters initialStatus={status} />          {/* interactive island */}
      <table>{orders.map(o => <OrderRow key={o.id} order={o} />)}</table>   {/* zero client JS for rows */}
    </>
  );
}

What they give you: less client JavaScript (heavy dependencies such as markdown parsers, date libraries and syntax highlighters stay on the server), direct data access with no API round trip and no client waterfalls, secrets stay on the server, and automatic code splitting at client boundaries.

What they can't do: hold state, run effects, attach event handlers, or use browser APIs. Those need Client Components.

Server and client boundaries

"use client" at the top of a file marks a boundary: that module and everything it imports become Client Components, which are included in the browser bundle and hydrated. Client Components are rendered on the server too (SSR), so "client" means "also runs in the browser", not "only in the browser".

Layout (server) ProductPage (server) AddToCartButton"use client": state, onClick Tabs ("use client") Reviews (server) as children props must be serialisable
Server and client component tree. Server components can render client components and pass them serialisable props, or server-rendered children.

Rules at the boundary:

  • Props passed from Server to Client Components must be serialisable: primitives, plain objects and arrays, Dates, Maps, Sets, typed arrays, promises (which the client can use()), JSX elements, and Server Functions. You can't pass ordinary functions or class instances.
  • A Client Component can't import a Server Component, but it can receive one as children or props. That's how you put server-rendered content inside interactive wrappers.
  • Mark the boundary as low in the tree as possible (leaf interactivity), so most of the page stays server-only.
  • Keep secrets out of client modules. import "server-only" makes accidental client imports fail the build.

Hydration

Hydration makes server-rendered HTML interactive. React runs your components in the browser, builds the fiber tree, and attaches event handlers and state to the existing DOM instead of recreating it (hydrateRoot).

Hydration mismatches happen when the client's first render produces different output than the server's HTML. Causes: Date.now(), Math.random() or new Date().toLocaleString() (server and client time zones differ), reading window or localStorage during render, invalid HTML nesting that the parser repairs differently (chapter 13), browser extensions that modify the DOM, and locale-dependent formatting. React 19 reports mismatches with a diff. Fixes: render time-dependent or browser-only content in an effect after hydration, use useSyncExternalStore with a server snapshot, suppressHydrationWarning for unavoidable single-element cases such as timestamps, and fix invalid HTML.

The cost of hydration is that the page is visible before it's interactive: the "uncanny valley" where clicks do nothing, measured by INP and TBT (chapter 27). Islands (chapter 24), Server Components (less to hydrate), selective hydration, and resumability (Qwik) are all ways to reduce that cost.

Actions and forms

React 19 introduced actions: async functions used for transitions and forms, with built-in pending, error and optimistic states.

TSX
"use client";
import { useActionState, useOptimistic } from "react";
import { useFormStatus } from "react-dom";
import { addComment } from "./actions";                     // a Server Function ("use server")

function SubmitButton() {
  const { pending } = useFormStatus();                      // the status of the enclosing <form>
  return <button disabled={pending}>{pending ? "Posting…" : "Post"}</button>;
}

export function Comments({ postId, comments }: { postId: string; comments: Comment[] }) {
  const [optimistic, addOptimistic] = useOptimistic(comments, (cur, text: string) =>
    [...cur, { id: "temp", text, pending: true }]);
  const [state, formAction] = useActionState(async (_prev: { error?: string }, formData: FormData) => {
    addOptimistic(String(formData.get("text")));
    const res = await addComment(postId, formData);          // runs on the server
    return res.ok ? {} : { error: res.error };
  }, {});

  return (
    <>
      <ul>{optimistic.map(c => <li key={c.id} style={{ opacity: c.pending ? 0.5 : 1 }}>{c.text}</li>)}</ul>
      <form action={formAction}>                             {/* works before JS loads (progressive enhancement) */}
        <textarea name="text" required />
        {state.error && <p role="alert">{state.error}</p>}
        <SubmitButton />
      </form>
    </>
  );
}
TypeScript
// actions.ts
"use server";
export async function addComment(postId: string, formData: FormData) {
  const session = await auth();                              // ⚠ Server Functions are public HTTP endpoints:
  if (!session) return { ok: false, error: "Sign in first" };// authenticate, authorise and validate every call
  const text = z.string().min(1).max(2000).parse(formData.get("text"));
  await db.comment.create({ data: { postId, text, userId: session.userId } });
  revalidatePath(`/posts/${postId}`);                        // framework cache invalidation (chapter 24)
  return { ok: true };
}

Server Functions ("use server", formerly "Server Actions") are called from the client like functions, but they're RPC endpoints. Anyone can call them with any arguments, so validate and authorise inside every one, exactly as you would a REST controller (Vol. 3). Avoid closing over secrets, and keep them small.

Error boundaries

An error boundary catches errors thrown during rendering, in lifecycle methods and in constructors of its subtree, and shows a fallback instead of unmounting the whole app. It's still a class component in React itself, or react-error-boundary, or a framework error.tsx file:

TSX
import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary
  fallbackRender={({ error, resetErrorBoundary }) => (
    <div role="alert"><p>Couldn't load orders.</p><button onClick={resetErrorBoundary}>Try again</button></div>
  )}
  onError={(error, info) => reportToSentry(error, info.componentStack)}
  resetKeys={[userId]}
>
  <Orders />
</ErrorBoundary>

Error boundaries don't catch errors in event handlers (use try/catch), async code outside render (handle the promise rejection, or rethrow it into render state), or SSR errors (handled by the framework). Place them around independent regions (a widget, a route segment) so one failure doesn't blank the page. React 19 adds root-level onCaughtError/onUncaughtError options for reporting.

The React Compiler

The React Compiler (stable 1.0 since late 2025) is a build-time compiler (a Babel or SWC plugin) that analyses components and hooks and automatically memoises values, callbacks and JSX at a fine granularity, often finer than hand-written useMemo/useCallback/memo. Code written following the Rules of React (pure render, immutable props and state, hooks rules) gets optimised re-rendering without manual memoisation.

TSX
// You write:
function ProductList({ products, query }) {
  const visible = products.filter(p => p.name.includes(query));
  return visible.map(p => <ProductCard key={p.id} product={p} onAdd={() => add(p.id)} />);
}
// The compiler emits code that caches `visible` until products or query change,
// and keeps ProductCard elements and onAdd callbacks stable across unrelated re-renders.

It skips components that break the rules (for example, those mutating props), so following the rules and using eslint-plugin-react-hooks (which includes the compiler's diagnostics) matters more than ever. Treat manual memoisation as an escape hatch in compiler-enabled projects.

View Transitions

React's <ViewTransition> component (experimental and canary in 2025, progressing toward stable) integrates the browser's View Transitions API (chapter 14). React starts a view transition automatically when updates inside a <ViewTransition> happen within a transition (startTransition, Suspense reveals, useDeferredValue), and you style it with CSS:

TSX
import { unstable_ViewTransition as ViewTransition } from "react";

<ViewTransition name={`photo-${photo.id}`}>     {/* shared element: morphs between list and detail */}
  <img src={photo.thumb} alt={photo.alt} />
</ViewTransition>

Because React coordinates when the DOM changes, it can snapshot correctly around concurrent rendering and Suspense, which is hard to do by hand. Respect prefers-reduced-motion in the CSS.

Fragment refs

Fragment refs (a newer React feature, landing in canary and experimental releases) let you attach a ref to a <Fragment>. You get a FragmentInstance that can manage its child DOM nodes as a group without a wrapper element: add event listeners to all of them, observe them with IntersectionObserver or ResizeObserver, focus the first focusable child, and get their bounding rectangles. Libraries (animation, focus management, visibility tracking) previously had to inject wrapper <div>s, which break layouts (flex and grid children), semantics and CSS selectors.

Trusted Types integration

Trusted Types (chapter 28) is a browser security feature that makes dangerous DOM sinks (innerHTML, script.src, eval) accept only typed objects created by a vetted policy, rather than raw strings. That stops DOM-based XSS at the source. React escapes text by default, but dangerouslySetInnerHTML and URL attributes like href="javascript:…" are sinks. React 19 supports Trusted Types: when the page enforces require-trusted-types-for 'script' through CSP, React passes TrustedHTML objects through to innerHTML instead of stringifying them, so your sanitising policy (DOMPurify's RETURN_TRUSTED_TYPE) works end to end. It also blocks javascript: URLs by default.

TSX
const policy = trustedTypes.createPolicy("app-html", { createHTML: (s) => DOMPurify.sanitize(s) });
<div dangerouslySetInnerHTML={{ __html: policy.createHTML(userMarkdownHtml) as unknown as string }} />

Lab: React's rendering behaviour, measured

React 19 bundled with esbuild and run in Chromium 153, in production mode unless stated. Each component counted its own renders in a global object (window.renders[name]++ at the top of the function), which is the simplest way to see what React actually does; the React DevTools Profiler shows the same thing graphically.

Experiment 1: what re-renders when state changes

A Menu component holds the search text in state and renders 100 rows, each containing a plain Price component and a memo-wrapped MemoPrice, with identical props:

JSX
function Price({ value }) { count("Price"); return <b>₹{value}</b>; }
const MemoPrice = memo(function MemoPrice({ value }) { count("MemoPrice"); return <b>₹{value}</b>; });
function Menu() {
  const [query, setQuery] = useState("");
  count("Menu");
  return <div><input value={query} onChange={e => setQuery(e.target.value)} />
    {Array.from({ length: 100 }, (_, i) => <span key={i}><Price value={i} /><MemoPrice value={i} /></span>)}</div>;
}

Typing "dosa" (four keystrokes):

Text
typing 4 letters re-rendered: Menu 4×, Price 400×, MemoPrice 0×

When a component's state changes, React re-renders it and all of its descendants by default, whether or not their props changed: 100 Prices × 4 keystrokes. Usually that's fine (rendering is just calling functions; the DOM is only touched where output differs). When children are expensive, memo makes a component skip rendering if its props are shallowly equal to last time, which here saved all 400 renders. The catch is that props must actually be equal: a new object, array or arrow function created during the parent's render is a new reference every time, which defeats memo unless wrapped in useMemo/useCallback. The React Compiler (stable since 2025) inserts that memoisation automatically at build time, which is why new code rarely needs hand-written useMemo.

Experiment 2: batching

JSX
<button onClick={() => { setA(a + 1); setB(b + 1); setC(c + 1); }}>{a}{b}{c}</button>
Text
three setState calls in one click → Batch rendered 1 time(s), shows 111

React batches state updates: it collects every update made in the same event (and, since React 18, in timeouts, promises and native handlers too) and renders once afterwards. That's also why state doesn't change immediately after you call a setter: console.log(a) right after setA(a + 1) still prints the old value, the snapshot of this render.

Experiment 3: effects in Strict Mode

A component connects to a chat room in an effect and disconnects in the cleanup, rendered inside <StrictMode>:

JSX
useEffect(() => { log("connect " + room); return () => log("disconnect " + room); }, [room]);
Text
development:  connect general → disconnect general → connect general
production:   connect general

In development, Strict Mode deliberately mounts, unmounts and remounts every component once, running effects, cleanups and effects again. It's a test: if your effect's cleanup doesn't fully undo it, you'll see duplicated connections, listeners or requests in development, which would otherwise surface in production when components remount (navigating back, Suspense, Fast Refresh, offscreen rendering). The fix is never to turn Strict Mode off; it's to write the cleanup.

Experiment 4: the fetch race in an effect

Two Dish components fetch /dish?id=… in an effect, one with the ignore flag in its cleanup and one without. The id changes from 1 to 2 immediately; the server answers id 1 after 600 ms and id 2 after 100 ms:

Text
id 1 → 2 quickly: no guard shows "Masala dosa", with ignore flag shows "Idli"

Without the guard, the slow, stale response for dish 1 arrived last and overwrote dish 2: the page shows the wrong dish for the selected id, permanently. With it, the cleanup that ran when id changed marked the first request as stale. (An AbortController aborted in the cleanup also cancels the network request.) Data libraries such as TanStack Query and framework loaders handle this, plus caching, deduplication and retries, which is why hand-written fetching effects are discouraged in React's own documentation.

Experiment 5: keeping typing responsive with useDeferredValue

A search box filters 400 results, each artificially slow to render (0.3 ms each, so a full list costs about 120 ms). The results component is wrapped in memo. Typing "Dish 1", measuring how long each keystroke took to appear in the input box:

JSX
const [text, setText] = useState("");
const deferred = useDeferredValue(text);
<input value={text} onChange={e => setText(e.target.value)} />
<Results q={mode === "deferred" ? deferred : text} />
Text
urgent    time until each keystroke appeared (ms): 159, 156, 156, 163, 157, 47
deferred  time until each keystroke appeared (ms):   3,  14,  13,  18,  18, 13

With the plain value, every keystroke waited for the whole list to re-render before the letter showed: typing felt broken. With useDeferredValue, React first rendered with the old deferred value (the memoised results skipped rendering entirely), committed the input change in milliseconds, then rendered the new results in the background as an interruptible, lower-priority update, abandoning it if another keystroke arrived. useTransition/startTransition does the same for state updates you start yourself (switching tabs, applying filters). The first version of this experiment forgot memo on the results and showed no improvement: the deferred value only helps if the expensive part can skip rendering when it's unchanged.

Try it yourself

  1. Install the React DevTools extension, enable "Highlight updates when components render", and type into a search box on a React site you use. How much re-renders per keystroke?
  2. Pass style={{ color: "red" }} to MemoPrice in experiment 1. What happens to its render count, and why? Fix it two ways.
  3. Remove the cleanup from experiment 3's effect and count connections after navigating between two rooms several times.
  4. Replace experiment 4's effect with TanStack Query's useQuery, and check what it does when the id switches back to 1.

Revision sheet: React

Key ideas

  • Components are functions of props and state returning JSX (compiled to jsx() calls); rendering must be pure; side effects go in event handlers or effects.
  • State: useState/useReducer; updates are immutable and batched; state is a per-render snapshot; updater functions for values derived from the previous state; derive instead of duplicating.
  • Effects synchronise with external systems after commit; dependency arrays; cleanups; Strict Mode's double-invoke in development; "you might not need an effect" for derived data and event-driven logic.
  • Refs (useRef) for mutable values that don't trigger renders and for DOM access; context for values many components need (theme, user), not as a general store.
  • Rendering pipeline: trigger → render (call components, build the new tree) → reconcile (Fiber diff with keys) → commit (DOM mutations, layout effects, then passive effects); a parent render re-renders its subtree unless memoised.
  • Concurrent features: transitions and useDeferredValue make updates interruptible; Suspense shows fallbacks while code or data loads; streaming SSR and selective hydration.
  • Server Components (RSC) render on the server and send a serialised tree; "use client" marks the client boundary; Server Functions ("use server") and Actions (useActionState, useOptimistic, form action) handle mutations.
  • React Compiler auto-memoises components and hooks at build time.

Numbers to remember

  • Lab: 4 keystrokes re-rendered 400 unmemoised children vs 0 memoised; deferred rendering cut keystroke latency from about 160 ms to about 15 ms.
  • Strict Mode in development: effects run, clean up, and run again once on mount.

Pitfalls

  • Mutating state; stale closures in handlers, effects and intervals; missing or index keys.
  • Effects for derived state or event logic; missing dependencies (lint with react-hooks/exhaustive-deps); fetch races without cleanup.
  • New object/function props defeating memo (absent the compiler); context values recreated each render causing app-wide re-renders.
  • Hydration mismatches (dates, random ids, window checks during render); use useId for ids.
  • Putting server-only secrets in client components; serialising huge props across the RSC boundary.

Glossary

  • Reconciliation: comparing the new element tree with the previous one to compute DOM changes.
  • Fiber: React's internal unit of work and data structure enabling interruptible rendering.
  • Commit: the phase where React applies changes to the DOM and runs layout effects.
  • Transition: a state update marked non-urgent and interruptible.
  • Hydration: attaching React to server-rendered HTML so it becomes interactive.
  • Client boundary: the "use client" module where the server component tree hands over to client components.