Tags: web-dev reference

Reference - React

Language: React 19.3.1 — a UI library, not a framework. See Libraries, Frameworks and Toolkits
Checked: 2026-10-30


A component is a function from props and state to a description of the UI. You never touch the DOM: you change state, React calls your function again, compares the new description with the last one and applies the difference. Almost every hook rule and every “why did that happen” follows from that one call.


§0 The one idea

UI is a function of state. UI = f(state). A component is a plain function that returns a description of what the screen should look like right now. Rendering means React calling that function. Reconciling means React diffing the new description against the previous one and making the smallest set of DOM changes to match — see Virtual DOM and Declarative vs Imperative UI. How this compares with signal-based frameworks: Reactivity.

vs JS: in plain DOM code you write the transitions — find the node, change its text, add a class, remember to undo it. In React you write the destination, and the transitions are React’s job.

PLAIN DOM                                REACT

state lives in the DOM itself            state lives in React (useState)
  ↓                                        ↓
event → find node → mutate it            event → setState(next)
  ↓                                        ↓
every transition hand-written            React calls Component() again
  (open→closed, closed→open,               ↓
   loading→error…)                       new description vs old → diff
  ↓                                        ↓
bugs = a transition you forgot           React patches only what changed
                                         bugs = state you modelled wrong

The consequences worth holding:

  • Render must be pure. Same props and state in, same output out, no side effects. React may call your function more often than you expect, abandon a render half-way, or (in dev) call it twice on purpose
  • Each render is a snapshot. Variables inside a component are the values for that render. Changing state doesn’t change them — it schedules a new call with new values. This is Closures doing exactly what closures do, and it explains stale values, “setState didn’t work” and most effect bugs
  • React is the library; the framework is something else. React has no router, no data layer, no server. Next.js and React Router supply those — see Reference - Next.js and Reference - React Router. This note is the layer underneath both

What’s actually React, and what’s just JS. The subtraction this note is for:

Looks like React magicActually
JSXSyntax sugar for a function call. Compiles away
PropsFunction arguments (one object)
Conditionals, loops in markup&&, ternaries, .map() — plain expressions
Event handlersFunctions passed as values
Stale state in a callbackA closure over the render’s variables
Custom hooksFunctions whose name starts with use
useState, useEffect, context, keys, reconciliationGenuinely React. This is what there is to learn

1. The smallest working form

A complete React app. Nothing omitted beyond the HTML page with a <div id="root"> and a bundler that understands JSX.

import { createRoot } from "react-dom/client";
 
function App() {
  return <h1>Hello</h1>;
}
 
createRoot(document.getElementById("root")).render(<App />);

That’s all of it. A component is a function returning JSX. createRoot attaches React to one DOM node and owns everything inside it from then on.

  • react is the component model — hooks, JSX runtime, reconciliation. Platform-free
  • react-dom is the renderer for the browser. React Native is another renderer for the same model
  • In Next.js you never write the createRoot line — the framework does. It’s still there

2. JSX — a function call

JSX is not HTML and not a template language. It’s an expression that compiles to a function call returning a plain object (a React element — a description, not a DOM node).

What you write:

const el = <a href="/basket" className="link">Basket ({count})</a>;

What the compiler emits (the automatic runtime, which is what every modern toolchain uses):

import { jsx as _jsx } from "react/jsx-runtime";
 
const el = _jsx("a", {
  href: "/basket",
  className: "link",
  children: ["Basket (", count, ")"],
});

What that call returns — just data:

{ type: "a", props: { href: "/basket", className: "link", children: [...] }, key: null }

The two forms are equivalent. React.createElement("a", { href: "/basket" }, "Basket") is the older classic-runtime form, still valid, and the reason old files have import React from "react" at the top even when React is never mentioned.

Rules that follow from it being a function call:

  • One root per expression — a function returns one value. Wrap siblings in a Fragment: <>…</> (or <Fragment key={id}> when it needs a key)
  • className, htmlFor — these are JS object keys, and class/for are reserved words. Attributes are camelCase (tabIndex, onClick) except aria-* and data-*
  • {} holds any expression, never a statement. No if, no for inside JSX — use ternaries, && and .map()
  • Capitalised = component, lowercase = HTML tag. <button> becomes the string "button"; <Button> becomes a reference to your Button function
  • style takes an object: style={{ marginTop: 8 }} — the outer braces are “expression”, the inner are the object

Conditionals are plain JS:

function Badge({ count }) {
  if (count === 0) return null;                 // render nothing
 
  return (
    <span>
      {count > 99 ? "99+" : count}              {/* ternary */}
      {count > 10 && <em>busy</em>}             {/* short-circuit */}
    </span>
  );
}

The && trap: {count && <em>…</em>} renders a literal 0 when count is 0, because 0 && x is 0 and React renders numbers. Use count > 0 &&.


3. Props — function arguments

Props are the single object argument to your component. Destructuring, defaults and rest are all JS.

function Price({ amount, currency = "GBP", ...rest }) {
  const text = new Intl.NumberFormat("en-GB", { style: "currency", currency }).format(amount);
  return <span {...rest}>{text}</span>;
}
 
<Price amount={19.99} className="price" />

children is just a prop — whatever sits between the tags:

function Card({ title, children }) {
  return (
    <section>
      <h2>{title}</h2>
      {children}
    </section>
  );
}
 
<Card title="Delivery">
  <p>Free over £50</p>
</Card>

Props are read-only. Data flows down; a child changes something by calling a function the parent passed it. That’s the whole of React’s “one-way data flow” — see Component Models.

Any value can be a prop — strings, numbers, objects, functions, other elements. Passing JSX or a function as a prop is how React does slots and render-props; there’s no separate mechanism.


4. State — useState

State is memory that survives between renders and triggers a re-render when it changes. A local variable doesn’t survive (the function runs fresh every time) and changing it doesn’t re-render.

import { useState } from "react";
 
function Quantity() {
  const [qty, setQty] = useState(1);            // [current value, setter]
 
  return (
    <div>
      <button onClick={() => setQty(qty - 1)} disabled={qty <= 1}>−</button>
      <span>{qty}</span>
      <button onClick={() => setQty(qty + 1)}>+</button>
    </div>
  );
}

setQty doesn’t change qty. It asks React to render again with a new value. In the render that’s already running, qty is a const — it can’t change.

CLICK "+" THREE TIMES IN ONE HANDLER

handler code                 qty in THIS render    what React queues
setQty(qty + 1)              1                     "set to 2"
setQty(qty + 1)              1   ← still 1         "set to 2"
setQty(qty + 1)              1   ← still 1         "set to 2"
→ next render: qty = 2       ← not 4

setQty(q => q + 1)           –                     "add 1 to whatever it is"
setQty(q => q + 1)           –                     "add 1"
setQty(q => q + 1)           –                     "add 1"
→ next render: qty = 4       ← updater form chains

Use the updater form setX(prev => …) whenever the next value depends on the previous one.

Batching: all setState calls in one event (or one promise callback, timeout, anything — automatic since React 18) produce one re-render, not one each.

Never mutate state. React decides whether to re-render by comparing the old and new value with Object.is. Mutate an object in place and it’s the same reference — React sees no change.

// ✗ same array, mutated. Object.is(old, new) === true → no re-render
items.push(newItem);
setItems(items);
 
// ✓ new array
setItems([...items, newItem]);
 
// ✓ new object, one field changed
setUser({ ...user, name: "Alex" });
 
// ✓ remove, update
setItems(items.filter(i => i.id !== id));
setItems(items.map(i => (i.id === id ? { ...i, qty: i.qty + 1 } : i)));

Lazy initial state: useState(() => readFromStorage()) runs the function on the first render only. useState(readFromStorage()) calls it every render and throws the result away.

useReducer is the equivalent form for state with several related transitions — same model, the update logic moves into a pure function:

import { useReducer } from "react";
 
function reducer(state, action) {
  switch (action.type) {
    case "inc": return { ...state, qty: state.qty + 1 };
    case "dec": return { ...state, qty: Math.max(1, state.qty - 1) };
    default: throw new Error(action.type);
  }
}
 
function Quantity() {
  const [state, dispatch] = useReducer(reducer, { qty: 1 });
  return <button onClick={() => dispatch({ type: "inc" })}>{state.qty}</button>;
}

Where state should live — this component, a parent, a store — is Component State vs Application State and State Management Patterns.


5. Events

Pass a function, don’t call one.

<button onClick={handleClick}>        {/* ✓ passes the function */}
<button onClick={() => remove(id)}>   {/* ✓ passes a new function that calls remove */}
<button onClick={remove(id)}>         {/* ✗ calls remove during render */}

The event object is a SyntheticEvent — a wrapper with the standard DOM interface (e.target, e.preventDefault(), e.stopPropagation()). React attaches one listener per event type at the root and dispatches from there; the underlying mechanism is ordinary delegation — see Event Handling. e.nativeEvent is the real one.

function Search({ onSearch }) {
  const [q, setQ] = useState("");
 
  function handleSubmit(e) {
    e.preventDefault();                 // same as the DOM
    onSearch(q);
  }
 
  return (
    <form onSubmit={handleSubmit}>
      <input value={q} onChange={e => setQ(e.target.value)} />
    </form>
  );
}
  • onChange on an input fires on every keystroke — it behaves like the DOM’s input event, not the DOM’s change event. A React quirk, not a platform one
  • value + onChange = controlled input (React state is the source of truth). defaultValue alone = uncontrolled (the DOM is). Both are legitimate — see Forms in Frameworks
  • Event handlers are where side effects belong. Not render, and usually not effects (§7)

6. Lists and keys

function Basket({ lines }) {
  return (
    <ul>
      {lines.map(line => (
        <li key={line.id}>{line.name} × {line.qty}</li>
      ))}
    </ul>
  );
}

A key tells React which item is which between renders. Without it React matches by position. With it, React matches by identity — so it can move, insert and delete correctly, and state attached to an item stays with that item.

REMOVE THE FIRST ITEM — each row has an <input> the user typed into

key = index                              key = line.id

before         after                     before          after
0  Shirt  [S]  0  Socks  [S] ← wrong     a1 Shirt  [S]   b2 Socks [M]
1  Socks  [M]  1  Hat    [M] ← wrong     b2 Socks  [M]   c3 Hat   [L]
2  Hat    [L]  (2 removed)               c3 Hat    [L]   (a1 removed)

React thinks the LAST row was deleted     React deletes the right row,
and the others changed text — inputs      inputs stay with their items
keep the old positions' values

Rules:

  • Stable, unique among siblings, from the data. A database ID, a SKU. Not Math.random() (new key every render → remount every render)
  • Index is fine only if the list never reorders, filters or inserts and items hold no state
  • Keys aren’t props — the child can’t read props.key. Pass id separately if it needs it
  • Changing a key on purpose resets a component. <Checkout key={userId} /> throws away all of Checkout’s state when the user changes. The cleanest reset there is

7. Effects — useEffect

An effect synchronises a component with something outside React — a subscription, a timer, a third-party widget, the document title, a network connection. It runs after React has updated the DOM.

import { useEffect, useState } from "react";
 
function OnlineStatus() {
  const [online, setOnline] = useState(navigator.onLine);
 
  useEffect(() => {
    const update = () => setOnline(navigator.onLine);
    window.addEventListener("online", update);
    window.addEventListener("offline", update);
 
    return () => {                                    // cleanup
      window.removeEventListener("online", update);
      window.removeEventListener("offline", update);
    };
  }, []);                                             // dependencies
 
  return <span>{online ? "Online" : "Offline"}</span>;
}

The dependency array decides when it re-runs:

ArrayRuns
omittedafter every render
[]after the first render (mount) only
[roomId]after mount, and whenever roomId changed (Object.is)

Cleanup runs before the effect re-runs and when the component unmounts. Anything you subscribe to, you unsubscribe from; anything you start, you stop.

roomId: "a" → "b" → unmount

mount           setup("a")
roomId → "b"    cleanup("a")  setup("b")
unmount         cleanup("b")

The dependency array is not a choice — it’s a description. Every reactive value the effect reads (props, state, anything derived from them) must be listed. The react-hooks/exhaustive-deps lint rule enforces it. Leaving one out to “make it run once” is how stale-closure bugs are made (see Where it bites).

When not to use an effect

Most effects in real codebases shouldn’t exist. The test: is this synchronising with an external system? If not, there’s a simpler place for it.

You wrote an effect to…Instead
Compute a value from props/state (setFullName(first + " " + last))Compute it during render. const fullName = first + " " + last
React to a user action (POST on click, toast after submit)Do it in the event handler. You know what happened there
Reset state when a prop changesA key on the component (§6)
Fetch data for a pageThe framework’s data layer or a Server Component. Hand-rolled fetch-in-effect means waterfalls, races and no caching — see Data Fetching Patterns
Notify a parent of a changeCall the parent’s callback in the same handler that changed the state

Fetching in an effect still works and is fine in a small client-only app. It needs a cleanup to ignore stale responses:

useEffect(() => {
  let ignore = false;
  fetch(`/api/product/${sku}`)
    .then(r => r.json())
    .then(data => { if (!ignore) setProduct(data); });   // ← drop the stale one
  return () => { ignore = true; };
}, [sku]);

useEffectEvent — reading the latest value without re-running

Shipped in React 19.2. For logic inside an effect that should see current props but shouldn’t trigger it.

import { useEffect, useEffectEvent } from "react";
 
function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showToast("Connected", theme);           // always the latest theme
  });
 
  useEffect(() => {
    const conn = connect(roomId);
    conn.on("connected", () => onConnected());
    return () => conn.disconnect();
  }, [roomId]);                              // theme is NOT a dependency — no reconnect on theme change
}

Not a way to silence the lint rule — only for code that is genuinely an event fired from the effect.

Also: useLayoutEffect is the same API but runs synchronously before the browser paints — for measuring layout and avoiding a flicker. Rarely needed. Escape hatches in general: Framework Escape Hatches.


8. Refs — useRef

A ref is a mutable box ({ current: … }) that survives renders and doesn’t trigger one when changed. The opposite trade to state.

StateRef
Survives re-renderyesyes
Changing it re-rendersyesno
Read during renderyesno — value may be stale or mid-change
Use forwhat’s on screentimer IDs, DOM nodes, previous values, anything React doesn’t display

Holding a DOM node:

import { useRef } from "react";
 
function SearchBox() {
  const inputRef = useRef(null);
 
  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Search</button>
    </>
  );
}

React sets inputRef.current to the <input> element after it mounts and back to null when it unmounts.

Holding a value that isn’t UI:

function Stopwatch() {
  const intervalRef = useRef(null);
  const start = () => { intervalRef.current = setInterval(tick, 1000); };
  const stop  = () => clearInterval(intervalRef.current);
  // …
}

ref as a prop (React 19)

Function components can take ref as an ordinary prop. Before 19 you needed forwardRef; that’s now unnecessary and slated for deprecation. Both forms work in 19 and are equivalent:

// React 19
function TextInput({ ref, ...props }) {
  return <input ref={ref} {...props} />;
}
 
// pre-19 — still works
const TextInput = forwardRef(function TextInput(props, ref) {
  return <input ref={ref} {...props} />;
});

Ref callbacks can return a cleanup (React 19) — for attaching observers to a node:

<div
  ref={node => {
    const obs = new IntersectionObserver(onSeen);
    obs.observe(node);
    return () => obs.disconnect();          // runs when the node goes away
  }}
/>

Fragment refs — <Fragment ref={…}> giving a FragmentInstance that can add listeners and observers to all of a fragment’s children without a wrapper <div> — are stable from 19.3.


9. Context

Context passes a value to every component below a point, without threading it through each layer’s props. It’s dependency injection, not a state manager — it holds whatever you put in it, and every consumer re-renders when the value changes.

import { createContext, useContext, useState } from "react";
 
const CurrencyContext = createContext("GBP");          // default if no provider above
 
function App() {
  const [currency, setCurrency] = useState("GBP");
  return (
    <CurrencyContext value={currency}>                 {/* React 19 form */}
      <ProductPage />
    </CurrencyContext>
  );
}
 
function PriceTag({ amount }) {
  const currency = useContext(CurrencyContext);        // nearest provider above
  return <Price amount={amount} currency={currency} />;
}

Equivalent forms:

  • Provider: <CurrencyContext value> (19+) and <CurrencyContext.Provider value> (older, still works, to be deprecated)
  • Reading: useContext(Ctx) and use(Ctx) (19+). use differs in one way — it may be called inside an if

Its cost: every component that reads the context re-renders when value changes. Putting an object literal in value creates a new object every render, so every consumer re-renders every time the provider does. Context is right for things that change rarely — theme, locale, current user, a store handle. For fast-changing shared state see State Management Patterns.


10. Custom hooks

A custom hook is a function whose name starts with use and which calls other hooks. That’s the entire mechanism — no registration, no API.

import { useEffect, useState } from "react";
 
function useMediaQuery(query) {
  const [matches, setMatches] = useState(() => matchMedia(query).matches);
 
  useEffect(() => {
    const mql = matchMedia(query);
    const update = () => setMatches(mql.matches);
    mql.addEventListener("change", update);
    return () => mql.removeEventListener("change", update);
  }, [query]);
 
  return matches;
}
 
function Nav() {
  const isMobile = useMediaQuery("(max-width: 600px)");
  return isMobile ? <Burger /> : <FullNav />;
}

Hooks share logic, not state. Two components calling useMediaQuery each get their own useState. To share the value, lift it to a common parent or put it in context.

The use prefix is a convention the linter relies on — it’s how the rules of hooks are checked inside your function. A function that calls no hooks shouldn’t have the prefix.


11. The rules of hooks — and why

Two rules:

  1. Only call hooks at the top level of a component or custom hook. Not inside if, loops, nested functions, or after an early return
  2. Only call hooks from React functions — components and custom hooks, not ordinary helpers or class methods

Why: React identifies each hook by its call order. useState(1) has no name. React keeps an array of hook slots per component instance, and on each render it walks that array in step with your calls. First useState → slot 0, second → slot 1. If the order changes between renders, every slot after the change gets the wrong state.

A sketch of the mechanism (not React’s real code, but the same shape):

let slots = [];        // one array per component instance, kept by React
let i = 0;             // reset to 0 before each render
 
function useState(initial) {
  const index = i++;                              // ← identity IS the position
  if (slots[index] === undefined) slots[index] = initial;
  const set = v => { slots[index] = v; rerender(); };
  return [slots[index], set];
}
 
function Form({ showEmail }) {
  const [name, setName] = useState("");           // slot 0
  if (showEmail) {
    const [email] = useState("");                 // slot 1 — sometimes
  }
  const [agree, setAgree] = useState(false);      // slot 1 OR 2 ← breaks
}
render 1 (showEmail = true)     render 2 (showEmail = false)
slot 0  name   ""               slot 0  name   ""
slot 1  email  ""               slot 1  agree  → reads email's ""   ← wrong
slot 2  agree  false            slot 2  (orphaned)

use is the one exception — it can be called conditionally, because it doesn’t keep a slot.

The eslint-plugin-react-hooks rules (rules-of-hooks, exhaustive-deps) catch both rules mechanically. Treat them as errors.


12. Memoisation

Re-rendering is the normal, cheap case. A parent re-render re-runs every child function by default. Usually that’s fine — the diff finds nothing and the DOM isn’t touched. Memoisation is for the cases where the function call itself is expensive, or where an unchanged reference matters.

ToolCachesUse when
useMemo(() => compute(a, b), [a, b])a computed valuethe calculation is measurably slow, or the result is passed to something that compares by reference
useCallback(fn, [deps])a function referencethe function is a prop to a memo child, or a dependency of an effect
memo(Component)a component’s renderit re-renders often with the same props and its render is slow
import { memo, useCallback, useMemo, useState } from "react";
 
const ProductGrid = memo(function ProductGrid({ products, onAdd }) {
  return products.map(p => <Card key={p.id} product={p} onAdd={onAdd} />);
});
 
function Shop({ products, query }) {
  const [basket, setBasket] = useState([]);
 
  const visible = useMemo(
    () => products.filter(p => p.name.includes(query)),     // only recomputed when these change
    [products, query]
  );
 
  const onAdd = useCallback(id => setBasket(b => [...b, id]), []);
 
  return <ProductGrid products={visible} onAdd={onAdd} />;  // memo skips if both refs unchanged
}

Why useCallback exists at all: () => … written in a component is a new function every render. memo compares props with Object.is, so a new function prop defeats it every time. useCallback(fn, deps) is exactly useMemo(() => fn, deps) — equivalent forms.

memo is all-or-nothing. One unstable prop (an inline object, an inline function, children JSX) and it re-renders every time anyway — while still paying for the comparison.

The React Compiler

A build-time tool that inserts this memoisation automatically, at a finer grain than you’d write by hand. v1.0, stable, released October 2025 (npm babel-plugin-react-compiler, latest = 1.0.0). It works with React 17+ and is wired in through the bundler or the framework config.

  • With it on, new code mostly doesn’t need useMemo/useCallback/memo. Existing manual memoisation is left alone or worked around where it can’t be proven safe
  • It assumes your code follows the rules — pure render, no mutation of props or state, hooks at top level. Code that breaks them gets skipped (it “bails out”) rather than miscompiled
  • The compiler-powered lint rules live in eslint-plugin-react-hooks and work without the compiler installed — worth having either way
  • Opt-in, not default — in Next.js it’s reactCompiler: true in the config (stable there since Next 16); details in Reference - Next.js. Per-component escape: the "use no memo" directive

13. Actions — React 19

An Action is an async function run inside a transition. React tracks its pending state, its errors and optimistic updates for you — the shape of every “submit → spinner → result” flow, built in.

useTransition with an async function

import { useState, useTransition } from "react";
 
function SaveButton({ data }) {
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState(null);
 
  return (
    <button
      disabled={isPending}
      onClick={() => startTransition(async () => {
        const err = await save(data);
        if (err) setError(err);
      })}
    >
      {isPending ? "Saving…" : "Save"}
    </button>
  );
}

isPending is true from the start of the async function until it finishes. No setLoading(true) / finally { setLoading(false) }.

Form actions

<form action={fn}> accepts a function. React calls it with the FormData on submit, runs it as an Action, and resets uncontrolled fields afterwards.

function Newsletter() {
  async function subscribe(formData) {
    await api.subscribe(formData.get("email"));
  }
 
  return (
    <form action={subscribe}>
      <input name="email" type="email" />
      <button>Subscribe</button>
    </form>
  );
}

<button formAction={fn}> does the same per button.

useActionState — an action with a result

import { useActionState } from "react";
 
async function addToBasket(prevState, formData) {         // (previous state, form data)
  const res = await api.add(formData.get("sku"));
  return res.ok ? { message: "Added" } : { message: "Out of stock" };
}
 
function AddButton({ sku }) {
  const [state, formAction, isPending] = useActionState(addToBasket, { message: "" });
 
  return (
    <form action={formAction}>
      <input type="hidden" name="sku" value={sku} />
      <button disabled={isPending}>Add</button>
      <p>{state.message}</p>
    </form>
  );
}

Whatever the action returns becomes state on the next render. Equivalent to a useReducer whose reducer is async.

useFormStatus — the pending state of the enclosing form

From react-dom. Reads the status of the nearest parent <form>, so a design-system button can show a spinner without being passed anything:

import { useFormStatus } from "react-dom";
 
function SubmitButton() {
  const { pending } = useFormStatus();
  return <button disabled={pending}>{pending ? "…" : "Submit"}</button>;
}

useOptimistic — show the result before the server confirms

import { useOptimistic } from "react";
 
function Likes({ count, likeAction }) {
  const [optimisticCount, addOptimistic] = useOptimistic(
    count,
    (current, delta) => current + delta           // how to apply an optimistic update
  );
 
  async function like() {
    addOptimistic(1);                             // UI shows count + 1 immediately
    await likeAction();                           // when this settles, React drops back to the real `count`
  }
 
  return <form action={like}><button>♥ {optimisticCount}</button></form>;
}

The optimistic value only lives for the duration of the action. When it finishes, optimisticCount reverts to whatever count now is — the new server value on success, the old one on failure. No manual rollback.

use — read a promise or context during render

import { use, Suspense } from "react";
 
function Reviews({ reviewsPromise }) {
  const reviews = use(reviewsPromise);            // suspends until resolved
  return reviews.map(r => <p key={r.id}>{r.text}</p>);
}
 
<Suspense fallback={<p>Loading reviews…</p>}>
  <Reviews reviewsPromise={reviewsPromise} />
</Suspense>
  • The promise must come from outside render — passed from a Server Component, or from a cache. A fetch() created inside a Client Component’s render is a new promise every render, and React warns about it
  • While pending, the nearest <Suspense> shows its fallback. If it rejects, the nearest error boundary catches it
  • use can sit inside if and loops — the one hook that can

How suspense fits fetching patterns generally: Data Fetching Patterns.


14. Server Components and the directives

The React-level model only. How Next.js wires it up — which files, caching, routing — is Reference - Next.js. The concept itself is Server Components.

A Server Component (RSC, React Server Component) runs only on the server (or at build time). Its code and its dependencies never ship to the browser. It can be async and can read a database directly. It cannot use state, effects, event handlers or browser APIs — it renders once, there’s nothing to re-render.

// ProductPage.jsx — a Server Component (the default in an RSC-enabled framework)
import { db } from "./db";
import { AddButton } from "./AddButton";
 
export default async function ProductPage({ sku }) {
  const product = await db.product.find(sku);     // runs on the server, no API route
  return (
    <main>
      <h1>{product.name}</h1>
      <AddButton sku={sku} />                     {/* a Client Component, rendered here */}
    </main>
  );
}

'use client' marks a module as the boundary into client code. That module, and everything it imports, is bundled for the browser and hydrated.

// AddButton.jsx
"use client";
 
import { useState } from "react";
 
export function AddButton({ sku }) {
  const [added, setAdded] = useState(false);
  return <button onClick={() => setAdded(true)}>{added ? "Added" : "Add"}</button>;
}

'use server' marks a function as a Server Function — callable from the client, executed on the server. React turns the import into a reference that makes a network request. Used as a form action, it’s what’s usually called a Server Action.

// actions.js
"use server";
 
export async function addToBasket(formData) {
  await db.basket.add(formData.get("sku"));
}
// in a Client Component
"use client";
import { addToBasket } from "./actions";
 
export function AddForm({ sku }) {
  return (
    <form action={addToBasket}>
      <input type="hidden" name="sku" value={sku} />
      <button>Add</button>
    </form>
  );
}

The directive table — the commonest confusion:

MarksMeans
(none)—Server Component, in an RSC framework
"use client"a modulethe server→client boundary. Not “only runs on the client” — Client Components are still server-rendered to HTML on first load
"use server"a module or a function”callable from the client over the network”. Not “this is a Server Component”

What can cross the boundary as props: serialisable values — primitives, plain objects, arrays, Date, Map, Set, promises, JSX, and Server Functions. Not ordinary functions or class instances. Passing an onClick from a Server Component to a Client Component fails.

Server Components can render Client Components and pass them Server Components as children. A Client Component can’t import a Server Component, but it can receive one as a prop.

Server Components need a framework. Bundler integration, a server and a streaming protocol are required; plain createRoot doesn’t do RSC. Rendering modes in general: Framework Rendering Modes.

Security note: December 2025 saw a critical remote code execution vulnerability in the RSC implementation, fixed in 19.0.1 / 19.1.2 / 19.2.1. Server Functions are public endpoints — validate their input and check auth inside them, as with any API route.


15. Newer APIs worth recognising

Shipped in stable releases since 19.0; not needed day to day.

  • <Activity mode="visible" | "hidden"> (19.2) — hides part of the tree while keeping its state, and deprioritises it. Tabs that remember their scroll and inputs, pre-rendering the likely next screen
  • useEffectEvent (19.2) — §7
  • <ViewTransition> (stable in 19.3) — wraps the browser’s View Transitions API so state updates in a transition animate. DOM only for now
  • Fragment refs (stable in 19.3) — §8
  • cacheSignal (19.2) — an AbortSignal for when a cache()d call’s lifetime ends. Server Components only
  • Document metadata (19.0) — <title>, <meta> and <link> rendered anywhere in the tree are hoisted into <head>
  • Class components still work. componentDidMount / this.setState in older code is the same model with methods instead of hooks; error boundaries are still class-only — react.dev says there’s no function-component equivalent yet; most code uses the react-error-boundary package. Frameworks usually supply one per route

Required vs optional

QuestionAnswer
Does a component need to be a function?Yes for new code. Classes still work; nothing new targets them
Does it need to return JSX?No — it may return a string, a number, null (render nothing), an array, or JSX
Do I need JSX at all?No. createElement / jsx() calls are equivalent; JSX is convenience
Do I need import React?No, with the automatic runtime (every current toolchain). Only for classic-runtime builds
Does every list need keys?Every list rendered from an array, yes. Static sibling elements written out by hand, no
Can the key be the index?Only if the list never reorders, filters or inserts, and items hold no state
Do I need useEffect to fetch?No. Prefer the framework’s loader, a Server Component, or a fetching library. An effect works, with a race guard
Do I need useEffect to compute a value from state?No — never. Compute it in render
Does an effect need a dependency array?No — but without one it runs after every render, which is rarely meant
Does an effect need a cleanup?Only if it starts something — a subscription, listener, timer, connection
Do I need memoisation?Usually no. With the React Compiler on, mostly never. Without it, only where profiling shows a slow render or a reference matters
Do I need forwardRef?Not in React 19+ — ref is a normal prop
Do I need .Provider on context?Not in 19+ — <Ctx value> works
Do I need a state library?Not by default. useState + lifting + context covers most apps — see Component State vs Application State
Do I need 'use client' on every interactive file?Only on the boundary module. Its imports are client automatically
Can I use Server Components without a framework?Not practically. They need bundler and server integration
Do I need Strict Mode?No, but leave it on — it’s dev-only and surfaces impure renders and missing cleanups

Kitchen sink — every feature at once

Not a pattern to copy. Every rung in one component, to show where each piece sits relative to the others.

"use client";
 
import {
  createContext, memo, use, useActionState, useCallback, useContext,
  useEffect, useEffectEvent, useMemo, useOptimistic, useRef, useState,
} from "react";
import { useFormStatus } from "react-dom";
 
const CurrencyContext = createContext("GBP");
 
function useDebounced(value, ms) {                                // custom hook
  const [v, setV] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setV(value), ms);
    return () => clearTimeout(t);                                 // cleanup
  }, [value, ms]);
  return v;
}
 
const Row = memo(function Row({ item, onRemove }) {               // memo
  const currency = useContext(CurrencyContext);                   // context
  return (
    <li>
      {item.name} — {item.price} {currency}
      <button onClick={() => onRemove(item.id)}>×</button>        {/* event */}
    </li>
  );
});
 
function Submit() {
  const { pending } = useFormStatus();                            // form status
  return <button disabled={pending}>Add</button>;
}
 
export function BasketEditor({ initialItems, savedPromise, addAction, theme, ref }) {  // ref as prop
  const saved = use(savedPromise);                                // use(promise)
  const [items, setItems] = useState(initialItems);               // state
  const [query, setQuery] = useState("");
  const q = useDebounced(query, 200);
  const inputRef = useRef(null);                                  // DOM ref
 
  const visible = useMemo(                                        // derived, memoised
    () => items.filter(i => i.name.toLowerCase().includes(q.toLowerCase())),
    [items, q]
  );
 
  const onRemove = useCallback(id =>                              // stable callback
    setItems(prev => prev.filter(i => i.id !== id)), []);         // updater form
 
  const [optimisticItems, addOptimistic] = useOptimistic(         // optimistic
    visible, (list, newItem) => [...list, newItem]
  );
 
  const [state, formAction] = useActionState(async (prev, formData) => {   // action state
    const name = formData.get("name");
    addOptimistic({ id: "pending", name, price: "…" });
    const item = await addAction(name);
    setItems(list => [...list, item]);
    return { last: name };
  }, { last: null });
 
  const onFocus = useEffectEvent(() => console.log("theme", theme));        // effect event
  useEffect(() => {
    inputRef.current?.focus();
    onFocus();
  }, []);
 
  return (
    <CurrencyContext value="GBP">                                 {/* provider */}
      <section ref={ref}>
        <p>Last saved {saved.at} · last added {state.last ?? "—"}</p>
        <input ref={inputRef} value={query} onChange={e => setQuery(e.target.value)} />
        <ul>
          {optimisticItems.map(item => (                          // list + key
            <Row key={item.id} item={item} onRemove={onRemove} />
          ))}
        </ul>
        <form action={formAction}>                                {/* form action */}
          <input name="name" />
          <Submit />
        </form>
      </section>
    </CurrencyContext>
  );
}

One complete file

A small, realistic client-only app: a filterable product list with a basket. What a React file usually looks like — state at the top, derived values computed in render, handlers that set state, one effect for one external system, and no memoisation.

// main.jsx — the whole app
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
 
const PRODUCTS = [
  { id: "tee-blk", name: "T-shirt, black", price: 18 },
  { id: "tee-wht", name: "T-shirt, white", price: 18 },
  { id: "hoodie",  name: "Hoodie",         price: 45 },
  { id: "socks",   name: "Socks (3 pack)", price: 9  },
];
 
const gbp = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });
 
function useStoredState(key, initial) {
  const [value, setValue] = useState(() => {
    try { return JSON.parse(localStorage.getItem(key)) ?? initial; }
    catch { return initial; }
  });
 
  useEffect(() => {                                     // sync to an external system
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
 
  return [value, setValue];
}
 
function ProductList({ products, onAdd }) {
  return (
    <ul>
      {products.map(p => (
        <li key={p.id}>
          {p.name} — {gbp.format(p.price)}{" "}
          <button onClick={() => onAdd(p.id)}>Add</button>
        </li>
      ))}
    </ul>
  );
}
 
function Basket({ lines, onRemove }) {
  if (lines.length === 0) return <p>Basket is empty.</p>;
 
  const total = lines.reduce((sum, l) => sum + l.price * l.qty, 0);   // derived in render
  const freeDelivery = total >= 50;
 
  return (
    <>
      <ul>
        {lines.map(l => (
          <li key={l.id}>
            {l.name} × {l.qty}{" "}
            <button onClick={() => onRemove(l.id)} aria-label={`Remove ${l.name}`}>×</button>
          </li>
        ))}
      </ul>
      <p>
        Total {gbp.format(total)}
        {freeDelivery ? " — free delivery" : ` — ${gbp.format(50 - total)} to free delivery`}
      </p>
    </>
  );
}
 
function App() {
  const [query, setQuery] = useState("");
  const [basket, setBasket] = useStoredState("basket", {});   // { [id]: qty }
 
  // derived — never stored
  const visible = PRODUCTS.filter(p => p.name.toLowerCase().includes(query.toLowerCase()));
  const lines = PRODUCTS
    .filter(p => basket[p.id])
    .map(p => ({ ...p, qty: basket[p.id] }));
 
  function add(id) {
    setBasket(b => ({ ...b, [id]: (b[id] ?? 0) + 1 }));       // updater, new object
  }
 
  function remove(id) {
    setBasket(b => {
      const { [id]: _, ...rest } = b;                         // drop one key, immutably
      return rest;
    });
  }
 
  return (
    <main>
      <h1>Shop</h1>
      <input
        type="search"
        placeholder="Filter"
        value={query}
        onChange={e => setQuery(e.target.value)}
      />
      <ProductList products={visible} onAdd={add} />
      <h2>Basket</h2>
      <Basket lines={lines} onRemove={remove} />
    </main>
  );
}
 
createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Worth noticing: the only state is the query and the basket map. The visible list, the basket lines, the total and the free-delivery message are all computed during render — none of them is stored, so none can drift out of sync.


Where it bites

Stale closures in effects and callbacks. An effect or timer captures the variables of the render it was created in.

function Timer() {
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1);          // ✗ `count` is the 0 from the first render, forever → stuck at 1
    }, 1000);
    return () => clearInterval(id);
  }, []);                           // ← lied about dependencies
}

Fix: setCount(c => c + 1) (no need to read count), or list count and accept the re-subscribe, or useEffectEvent for reads that shouldn’t re-trigger. The lint rule catches the lie. Root cause: Closures.

Effects run twice in development. Strict Mode mounts every component, unmounts it, and mounts it again — so every effect runs setup → cleanup → setup. Components also render twice. Production does neither. It exists to expose missing cleanups: if the double run breaks something (two connections, two analytics events, a doubled POST), the effect was already wrong — it would break on a fast remount or route change too. Fix the cleanup; don’t remove Strict Mode. Analytics events fired from effects are the classic conversion-tracking casualty — fire them from the handler, or dedupe. From 19.3, Strict Mode also double-invokes effects during hydration.

Keys from the index. Fine for a static list. In a list that sorts, filters or inserts, state and DOM (input values, focus, animation) stick to positions and end up on the wrong item — §6. Also: a key generated during render (key={crypto.randomUUID()}) remounts every row every render.

Derived state stored in state.

// ✗ two sources of truth — fullName goes stale the moment one forgets to update it
const [fullName, setFullName] = useState("");
useEffect(() => setFullName(`${first} ${last}`), [first, last]);   // also costs an extra render
 
// ✓ computed every render
const fullName = `${first} ${last}`;

Same for “filtered list”, “total”, “is valid”, “selected item” (store the selected id, derive the item). Copying a prop into state (useState(props.value)) has the same problem — it reads the prop once and ignores later changes.

Over-memoisation. useMemo around a + b, useCallback on a handler passed to a plain <button>, memo on a component whose props are new objects every render. Each costs a dependency comparison and memory, and adds a dependency array that can go stale — for no saved work. Memoise after profiling, or let the compiler do it.

Mutating state. state.items.push(x); setState(state) — same reference, no re-render (§4). Shows up as “it updates on the next click”, when an unrelated state change finally triggers a render that reveals the mutation.

Object and array dependencies. useEffect(…, [options]) where options = { … } is created in render → new object every time → the effect runs every render. Depend on the primitive fields instead, or create the object inside the effect.

Setting state during render. setX() called at the top level of the component body → render → setX → render… React stops it with “Too many re-renders”. Usually it’s onClick={handle()} instead of onClick={handle}.

'use client' misread as “client-only”. Client Components are still rendered on the server for the first HTML. Code touching window or localStorage at render time fails on the server — read them in an effect, or in a lazy state initialiser guarded for the server. Hydration mismatches (server HTML ≠ first client render) come from the same place: dates, random values, typeof window branches.