2026-11-08·par Sijie Wang

react

React internals and practical use: virtual DOM, reconciliation, Fiber, Hooks, synthetic events, Context, Zustand, Redux, effects, pitfalls, hand-written problems, React 19, Server Components, and the Compiler.

React is a JavaScript library for building user interfaces: you describe what the page should look like for a given state, and React works out how to change the page from its old shape to the new one.

1. What React is

What it is. React is a JavaScript library for writing interfaces, open-sourced by Meta in 2013. The problem it solves: updating the DOM (Document Object Model) by hand is error-prone and messy. The DOM is the browser's live tree of the page: when state changes, you have to find which node to change and which attribute to set, and as the application grows, that manual patching rots.

What it is for. React switches to a declarative model: you only write "given this state, what the page looks like" — the interface is a function of state. How the page moves from its old shape to its new shape is React's job to compute.

2. From motivation to mechanism

The observation. The page is a tree, and state changes. Two naive paths: rebuild the whole page on every state change — slow, and it loses focus, scroll position, and the text in input boxes; or surgically update only the changed bit by hand — fast, but the code stops matching the state as the application grows.

React's third path. Keep a lightweight description of the page in memory, called the virtual DOM (Virtual DOM): an ordinary JavaScript object tree describing what the UI should be. When state changes, run the component functions again to produce a new virtual DOM, compare it with the previous one — this step is called reconciliation — and write only the changed parts into the real DOM.

The answer to the first question. React does not know in advance which small bit to change. It recomputes and compares every time, and patches only the difference.

3. The render loop

Five steps, in order.

  1. State changes — by calling setState, or the setter returned by useState.
  2. React schedules a re-render — not immediately; it batches multiple state updates together.
  3. Re-render — run the component functions again, producing a new virtual DOM.
  4. Reconcile — compare the new tree with the old tree at the same position: same type, update the props; different type, tear down and rebuild; lists use key to tell which item is which, or they misalign.
  5. Commit — write the computed minimal changes into the real DOM in one go, then the browser repaints.

4. Fiber

Why rendering can be interrupted. The old reconciler compared the whole tree in one synchronous pass — a big update blocked the main thread and the page froze. Fiber splits the work into small tasks: each component instance is one Fiber node, and nodes are linked into a tree by three pointers, child, sibling, and return. React does one small task at a time, can pause to let the browser handle input and repaint, then resumes. That is concurrent mode and time slicing.

Two phases. The render phase (computing the virtual DOM and reconciling) can be interrupted, discarded, and redone. The commit phase (writing the real DOM and running effects) is synchronous and cannot be interrupted.

Why discarding is safe: double buffering. React holds two trees: current, the one on screen, and workInProgress, the one being computed. They swap only when the computation finishes; discarding a half-built tree never touches the screen.

Deep dive: the Fiber node. Each Fiber carries the fields React needs: type (what it is — a host element such as div, or a component), key (its identity among siblings), stateNode (the real DOM node, or the class instance), memoizedProps (the props from the last render), pendingProps (the props for the next render), updateQueue (pending state updates and effects), flags (what this node needs in commit — Placement, Update, Deletion), and lanes (priority bits for this update).

The walk. Reconciliation walks the tree depth-first with the three pointers: go to child, then to sibling, then back up via return. There is no recursion and no call stack holding the position — the position lives in the pointers themselves. That is why the walk can stop and resume: the state of the walk is the current Fiber node, not a stack frame.

Where Hooks live. Each Fiber has a memoizedState field holding a linked list of Hook nodes, one per Hook call, in call order. useState stores the value and the update queue; useEffect stores the effect and its dependencies. React matches Hooks by position in this list, which is why the call order must never change.

The update flow. When state changes, React schedules work on the Fiber's lane, then begins the render phase from the root: it walks the tree, runs each component (or diffs each host element), reconciles children, and builds a new workInProgress tree. When the walk finishes, root.current is swapped to point at the finished workInProgress tree — that single pointer swap commits the new tree. The commit phase then walks the effect list and applies the flagged changes to the real DOM in one synchronous pass.

Lanes: prioritization. Each update carries a lane, a priority bit. Urgent updates (typing, clicks) get a high-priority lane and can jump ahead of low-priority work (rendering a big list). React processes the high-priority lane first and returns to the rest later — that is how input stays responsive while a heavy render is in flight.

Commit atomicity. Once the render phase finishes and root.current swaps, the commit phase runs synchronously to the end. There is no half-committed tree on screen: either the old tree is showing, or the new tree is fully applied.

Why Fiber can pause. Rendering is a walk over nodes linked by pointers, not a recursive function call. To pause, React stops walking and remembers the current node; to resume, it picks up from that node. A recursive reconciler cannot do this, because its position lives on the call stack — you cannot pause a call stack and return to it. (His own analogy, from running heavy tasks on workers at CERN while the main thread stayed free: the instinct is right — keep the main thread free — but the mechanism differs. Workers are true parallelism and cannot touch the DOM; Fiber is cooperative slicing on the same thread, a hand-written coroutine. It does not use async/await to yield, because await yields to a microtask and the browser cannot paint a frame in between.)

5. Hooks

Where state lives. Hooks such as useState and useEffect store state on the Fiber node, in a linked list called memoizedState. So Hooks must be called in the same order on every render: React matches them by position, not by name. Call a Hook inside a conditional branch, the positions shift, and state gets crossed onto the wrong Hook.

useEffect runs after commit. Side effects run only after the DOM has been updated.

What a Hook is. A Hook is a function whose name starts with use, and it lets a function component use React features: state, side effects, Context, memoization. Before Hooks (React 16.8), function components had no state and no lifecycle — you needed a class for that. Classes were verbose, this was easy to get wrong, and one feature's logic was split across lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount) while unrelated logic was mixed into a single method. Hooks let a function component use state and effects, and organize logic by feature instead of by lifecycle.

Custom Hooks. A custom Hook is a function starting with use that calls other Hooks, extracting reusable stateful logic. For example, the debounced search in §7.6 is written as useDebounce(value, delay) — any component can use it.

When to extract a custom Hook. Three signals, any one is enough: the same stateful logic is about to be written a second time; one component is getting long because a chunk of stateful logic (state plus effects) is stretching it; the logic has a clean input and output (a value and a delay in, a debounced value out). When not to: it is only used once and it is a few lines — keep it inline; it uses no Hooks at all — then it is an ordinary function, not a Hook; it is tangled with one component's specific rendering — a Hook holds logic and data, not what to render.

What is actually Hook-specific. The three criteria above are general code-extraction rules — they apply to extracting any function or component. What is specific to Hooks: it must use Hooks (otherwise it is just a function); it can only be called at the top level of a component or another Hook (the Rules of Hooks, because matching is by position); and each call gets its own independent state — component A and component B calling the same custom Hook each have their own timers and values, unlike a shared store, which is one copy for everyone.

6. Events

One listener at the root. React does not attach a listener to every element; it attaches one at the root and delegates everything there. The event object you receive is a synthetic event (SyntheticEvent), a wrapper that smooths over browser differences. That is why calling e.stopPropagation() in React stops propagation at the React layer, while the native event has already bubbled to the root.

How it works. React attaches a single native listener at the root container. When an event fires, it bubbles to the root, and React walks the virtual DOM path to find the handlers, calling them in order. Because the event flows through the virtual tree rather than the real one, React can normalize it: the synthetic event smooths over browser differences (different event objects, different property names), so handlers see one consistent shape.

Why stopPropagation behaves the way it does. Calling e.stopPropagation() stops propagation at the React layer — handlers further up the React tree do not run. But the native event has already bubbled to the root by the time React processes it, so a native listener attached outside React (for example on document) still fires. The two layers are separate.

7. Practical use: six blocks

Interviews ask two halves. The internals above are the harder half — "how React works". The other half is everyday use plus hand-written problems. The six blocks below are that half.

7.1 Components: controlled, uncontrolled, lifting state up

Where does an input's value live? A controlled component lets React state decide: the value comes from state, and every keystroke updates state through onChange. The value is always in your hands — you can validate it live, rewrite it, clear it — at the cost of a re-render per keystroke. An uncontrolled component lets the DOM own the value; you read it with a ref when you need it. That means fewer renders, and a file input can only be written this way (you cannot set its value); the downside is that you do not know the value until you read it, and you cannot validate it live. Use controlled when you need to know, validate, or rewrite the value live; use uncontrolled when you only read it once at submit time.

Lifting state up. When two sibling components need the same state, move it to their common parent, which passes down the value and the setter. The cost is that intermediate components have to pass it through — prop drilling — which leads to the next block.

Three pitfalls.

1. value without onChange is read-only. A controlled input with value but no onChange cannot be typed into — React keeps resetting it to the state value on every render, so the field looks frozen.

2. Never switch between controlled and uncontrolled. If value goes from undefined to a string (or the reverse), React warns and the input jumps. Fix it by initializing state to an empty string with useState(''), so the input is controlled from the first render.

3. A file input can only be uncontrolled. You cannot set a file input's value, so it must be uncontrolled: read the files through a ref (ref.current.files).

Rule of thumb. If anything else has to follow the input's value as it changes — live search suggestions, a password-strength meter — the value has to live in state, so the input has to be controlled.

7.2 Rendering and performance: memo, useMemo, useCallback

When does a component re-render? In three cases: its own state changed, its props changed, or its parent re-rendered. By default, when a parent renders, all its children render too, even if their props did not change.

memo wraps a component: skip the re-render if its props are shallowly equal. Shallow comparison compares references — for objects and arrays, only whether it is the same reference. So if the parent creates a new object or arrow function inline on every render and passes it as props, memo fails, because the reference is different every time. That is why useMemo and useCallback exist: useMemo caches a computed value (an expensive computation, or an object literal) and does not recompute it while its dependencies are unchanged, keeping the reference stable; useCallback caches a function, keeping its reference stable.

The catch. These three are not free: they trade memory plus comparison cost for skipped renders. Overusing them can be slower than just re-rendering. They are worth it only when rendering is genuinely expensive or the child is big.

Three pitfalls.

1. Shallow compare plus inline references break memo. memo compares props shallowly — by reference for objects and functions. If the parent creates a new object or arrow function inline on every render, the reference changes every time and memo never skips. useMemo and useCallback exist to keep those references stable.

2. Wrapping everything makes it slower. Every memo pays the comparison cost plus the render cost when it fails to skip. If props change most of the time, memo never skips and you pay both — slower than rendering directly. Only wrap when the render is genuinely expensive or the child is big.

3. The Compiler memoizes for you. React Compiler (see §8) automatically inserts the equivalent of memo/useMemo/useCallback at build time, so hand-written memo becomes less important.

Why he bans memo in his libraries (his own experience). He has broken an app with memo before — wrong data on screen, and sometimes the app got stuck on performance — so memo is banned in many of his libraries. The mechanism: memo is a bet that props mostly do not change and that rendering costs more than comparing. When the bet loses, it fails silently, with no error. Two failure modes: wrong data shown (content changes without a reference change, so shallow compare sees nothing and skips the render — the old data stays on screen; a custom areEqual that forgets to compare one prop does the same), and worse performance (props change every time, so the comparison never skips and you pay comparison plus render). The alternative he uses is Zustand or Redux: split at the state layer, not block at the component layer. Components subscribe to only the slice they need, and selectors return primitives compared by value, so there is no reference trap.

7.3 Where state lives: prop drilling, Context, Redux

Prop drilling. Lifting state up too far means intermediate components pass it through layer by layer. Context is React's built-in answer: provide above, consume below, and intermediates never touch it. It fits global state that changes infrequently (theme, language, the current user). Frequently-changing state in Context makes every consuming component re-render.

Redux (or Zustand and the like) moves state outside React, with a subscription mechanism: only components that actually use that slice of state re-render. Choose by scope and change frequency: local sharing, lift state up; global and low-frequency, Context; global, high-frequency, read and written in many places, Redux-like.

Context, step by step. Prop drilling is the motivation: a value needed deep in the tree has to be passed through every intermediate layer. Context has three steps: createContext makes the Context, Provider supplies the value from above, useContext reads it below. Intermediates never touch it.

const ThemeContext = createContext('light')

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  )
}

function Toolbar() {
  const theme = useContext(ThemeContext)
  return <div className={theme}>...</div>
}

The flaw. When the Provider's value changes, every component consuming that Context re-renders — all of them, even the ones that only use a small part of the value. That is why Context fits state that changes rarely (theme, language, the current user), and why frequently-changing state belongs elsewhere.

His stance on theme (his own words). Theme is a global value, used everywhere. He would absolutely use Context for it — never pass it down as a prop.

Redux, four pieces. A store holds the state; an action is a plain object describing what happened ({ type: 'counter/incremented' }); a reducer is a pure function, (state, action) => newState, that holds all the update rules in one place; useSelector reads a slice of the store, and the component re-renders only when that slice changes. Redux Toolkit is the current way to write it — createSlice generates the actions and the reducer together, and configureStore sets up the store with devtools.

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    incremented: (state) => { state.value += 1 },
    decremented: (state) => { state.value -= 1 },
  },
})

const store = configureStore({ reducer: { counter: counterSlice.reducer } })

DevTools and time travel. Redux DevTools is a browser extension that records every action and every resulting state. Time travel means clicking any past action and seeing the state as it was then — the page goes back to that moment. It works because every state change is a named action run through a pure reducer: to go back, the DevTools re-runs the reducer from the initial state, applying only the actions up to that point. That is the payoff for the reducer model: every change is logged and replayable.

Zustand. A tiny external store. The store is created once, outside any component, with create. Components subscribe to only the slice they need through a selector, and there is no Provider — the store is a module-level object any component can import.

import { create } from 'zustand'

const useStore = create((set) => ({
  count: 0,
  inc: () => set((s) => ({ count: s.count + 1 })),
}))

function Counter() {
  const count = useStore((s) => s.count)
  const inc = useStore((s) => s.inc)
  return <button onClick={inc}>{count}</button>
}

How it replaces memo. The selector returns a primitive (a number, a string, a boolean), compared by value — no reference trap. A component re-renders only when its own selected slice changes, so there is no extra render to block, and no need for memo. set merges rather than replaces: set({ name: 'b' }) changes only name.

How to choose. Changes rarely and few components need it: Context is enough (theme, language). Changes frequently, several components each need a slice, and you want minimal boilerplate: Zustand. A large project, needing time travel in devtools, a team convention already on Redux, or complex async flows: Redux Toolkit.

7.4 Data fetching and useEffect: dependencies, races, cleanup

useEffect runs side effects after commit; data fetching usually goes there. The dependencies array is the key: leave a dependency out, and the effect reads stale values (a stale closure); put too many in, and the effect runs over and over.

Races. The user switches twice quickly; the earlier request returns later and writes old data onto the new page. Fix it by checking whether this round is still alive when the request returns — cancel with AbortController, or keep a sequence number and only accept the latest round.

Cleanup. An effect returns a cleanup function, which runs before the effect re-runs when dependencies change, or when the component unmounts: cancel requests, clear timers, unsubscribe. Otherwise you get memory leaks, or state written onto an unmounted component.

What useEffect is for. Side effects are things that happen outside the render: fetching data, subscribing, timers, touching the DOM, logging. Render should be pure — the same props and state should give the same output. Effects cannot run during render, because render may run more than once and may be interrupted by Fiber. useEffect runs after commit, once React has updated the DOM, so it is safe there.

The dependency array. It decides when the effect re-runs. Empty [] runs once after mount. No array at all runs after every render. Listed dependencies re-run the effect when any of them changes.

Cleanup. An effect may return a cleanup function. React runs it before the effect re-runs when dependencies change, and when the component unmounts. Use it to clear timers, cancel requests, and unsubscribe.

The race condition. Type "a", a request goes out; type "ab", another request goes out. If the "a" request returns later, it writes old data onto the new page. Two fixes:

// Fix 1: AbortController — cancel the old request.
useEffect(() => {
  const controller = new AbortController()
  fetch(`/api/search?q=${query}`, { signal: controller.signal })
    .then((res) => res.json())
    .then(setResults)
  return () => controller.abort()
}, [query])

// Fix 2: a cancelled flag — drop the old result when it returns.
useEffect(() => {
  let cancelled = false
  fetchResults(query).then((data) => {
    if (!cancelled) setResults(data)
  })
  return () => { cancelled = true }
}, [query])

StrictMode. In development, StrictMode runs effects twice (mount, unmount, remount) to force you to write the cleanup correctly. If the cleanup is right, running twice is harmless.

Two pitfalls. A missing dependency means the effect reads a stale value (a stale closure) — the exhaustive-deps ESLint rule catches this. An infinite loop happens when the effect updates a state that is itself in the dependency array: the update triggers a re-run, which updates again, forever. Narrow the dependencies, or move the update out of the effect.

useEffectEvent (React 19.2). For the case where an effect needs the latest value of something, but should not re-run when that value changes. Wrap the non-reactive logic in an Event function: it always reads the latest values (no stale closure), but it is not a dependency, so changing it does not re-run the effect.

function ChatRoom({ roomId, onNewMessage }) {
  const onMessage = useEffectEvent((msg) => {
    onNewMessage(msg)
  })

  useEffect(() => {
    const connection = connect(roomId)
    connection.on('message', onMessage)
    return () => connection.disconnect()
  }, [roomId])
}

When it smells (his explicit judgment). He says reaching for useEffectEvent feels wrong — like something is written wrong somewhere, or not designed well. The test is whether the effect is doing two jobs. If it is, split it: the reactive job and the non-reactive job should not live in one effect. If it is one job that happens to need a latest value — the callback-prop case above, where the parent recreates the callback every render and the child should not resubscribe — then it is legitimate. And if you find yourself using it a lot, that is a sign the logic should move into a store.

7.5 Common pitfalls: stale closures, keys, setState batching

Stale closure. State captured in an effect or a callback is a snapshot from that render; when an asynchronous callback runs, it still reads the old value. Fix it by listing the dependencies completely, or by using a functional update, setState(prev => ...).

Keys. When rendering a list, React uses key to tell which item is which. A wrong key — using the array index, for example — misaligns items on insert or delete, and state gets crossed onto other items.

setState batching. Multiple setState calls in the same event merge into a single render. To update based on the old value, use the functional form; otherwise you read the old value.

Keys, in detail. React uses key to tell which list item is which across renders. The classic bug: a list where each item has an input, keyed by array index. Delete the first item, and the second item's input text shifts into the first position — because React matches by position and thinks the element at index 0 is the same element, only its content changed. With a stable id from the data as the key, React knows the first item was removed and the rest keep their state. A good key is stable, unique among siblings, and from the data itself. Index as key is only safe when the list never reorders, never filters, and items carry no state.

setState batching, in detail. Multiple setState calls in the same event handler merge into a single render. But setState does not update the state immediately — the value you read right after calling it is still the old one. So three calls of setCount(count + 1) all read the same stale count and the total only goes up by 1. The functional form reads the latest queued value each time, so three calls of setCount(c => c + 1) add up correctly to +3, still in one render.

function handleClick() {
  setCount(count + 1)
  setCount(count + 1)
  setCount(count + 1)
  // count only goes up by 1: all three read the same old count
}

function handleClick() {
  setCount((c) => c + 1)
  setCount((c) => c + 1)
  setCount((c) => c + 1)
  // count goes up by 3, still a single render
}

React 18 automatic batching. From React 18, batching is automatic everywhere: event handlers, setTimeout, promises — multiple setState calls always merge into one render. Before React 18, batching only happened inside React event handlers; in setTimeout or a promise, each setState triggered its own render.

What the two have in common. Key decides which element is which; batching decides when updates are applied together. Both are React deciding how an update is carried out.

Closures

What a closure is. A closure is a function that remembers the variables from the scope where it was born: even after those variables should have disappeared, the function can still use them.

Why it exists. In JavaScript, a function is a value — it can be returned and passed around. Without closures, a function returned from another function would lose the local variables it needs. A closure lets a function carry its birth environment with it.

How it works. JavaScript is lexically scoped: a function's scope is decided by where it is written, not where it is called. When created, a function captures a reference to its enclosing scope (the scope chain). As long as the function lives, the variables it captured are not garbage-collected.

function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}
const c = makeCounter();
c(); // 1
c(); // 2

Why React keeps bringing it up. Every render creates a fresh batch of functions (event handlers, effects) that capture that render's state snapshot. When an asynchronous callback runs, it reads the old value — that is the stale closure above. The two fixes, written out:

// Fix 1: list the dependency completely, so the effect is recreated with fresh values.
useEffect(() => {
  const id = setTimeout(() => setCount(count + 1), 1000);
  return () => clearTimeout(id);
}, [count]);

// Fix 2: functional update — read the latest value through prev, no dependency needed.
setCount(prev => prev + 1);

7.6 Hand-written problems: debounced search, implementing useState

Debounced search. Do not request on every keystroke; wait until input pauses for 300 milliseconds, then request. The shape is setTimeout plus cleanup: on each input, clear the previous timer first.

Implementing useState. The core is the memoizedState linked list on the Fiber node: useState takes a position in the list in call order, stores the value and the setter, and the setter triggers a re-render. Hand-written problems test whether you really understand this list and the render loop; you do not need to write the full Fiber, just the mechanism — "state hangs on the list in order, the setter triggers a render".

Implementing useState, written out. A minimal version: an array holds every Hook's value, and a cursor counts which Hook is being called. The index is captured in the closure, so each setter knows which slot to update. Before every render the cursor resets to 0, so the calls match by position again.

let hooks = []        // the memoizedState list, simplified to an array
let currentIndex = 0  // the cursor: which Hook is being called

function useState(initialValue) {
  const index = currentIndex
  if (hooks[index] === undefined) {
    hooks[index] = initialValue
  }
  function setState(newValue) {
    hooks[index] = newValue
    render()  // update the slot, then re-render
  }
  currentIndex++
  return [hooks[index], setState]
}

function render() {
  currentIndex = 0  // reset the cursor before every render
  // run the component function again
}

Why this explains the Rules of Hooks. If the calls ran in a different order, the indices would shift and a Hook would read another Hook's slot. That is why Hooks cannot go inside conditions or loops.

Debounced search, written out. The useDebounce custom Hook plus the search box that uses it:

import { useState, useEffect } from 'react'

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(timer)
    }
  }, [value, delay])

  return debouncedValue
}

function SearchBox() {
  const [query, setQuery] = useState('')
  const debouncedQuery = useDebounce(query, 300)

  useEffect(() => {
    if (debouncedQuery === '') return
    fetchResults(debouncedQuery)
  }, [debouncedQuery])

  return <input value={query} onChange={(e) => setQuery(e.target.value)} />
}

How it works. The input is controlled, so query updates on every keystroke. The effect sets a timer; the cleanup cancels the previous timer whenever value changes. Only when the value stops changing for the full delay does the timer run and update the debounced value — so the search request fires only after the user pauses for 300 milliseconds.

8. Beyond the core

8.1 Reconciliation, in detail

Two heuristics. Comparing two trees in general is O(n³) — too slow. React uses two rules to bring it to O(n). First: different element types mean different trees — tear the old subtree down and rebuild from scratch, losing all state in it. Second: same element type means update in place — keep the DOM node, change only the props that differ, then recurse into the children.

Lists and keys. Children are compared in order by default. With a key, React matches by identity: it can see a move, an insertion, or a deletion, and only touch what changed. Without a key, it matches by position, so inserting one item at the front looks like every item changed.

How it connects to Fiber. Reconciliation runs during the render phase. As React walks the Fiber tree, each Fiber is compared with the new element, and the result is marked with a flag — Placement, Update, Deletion. The commit phase applies those flags to the real DOM. Reconciliation computes what changes; commit performs how.

8.2 Virtual DOM and the RSC payload

Virtual DOM. The virtual DOM is the in-memory tree describing what the UI should be. State changes, React re-runs the components to produce a new tree, reconciles it with the old one, and writes only the difference into the real DOM. Real DOM operations are expensive; computing in memory is cheap.

The isomorphism with Server Components. The RSC payload is also a serialized tree that client React reconciles. Both are the same idea — describe the UI as a tree, compare trees, apply only the difference — one in browser memory, the other sent from the server.

8.3 Suspense and Transitions

Suspense. A Suspense boundary shows a fallback (a loading state) while the content inside is not ready. It works with Fiber's ability to pause: the render suspends, the fallback shows, and when the data arrives the boundary resolves to the real content.

Transitions. useTransition marks an update as non-urgent: urgent work renders first, the transition renders later, and the interface does not freeze. This is the concurrent feature that Fiber's interruptible render makes possible.

The isomorphism with Next.js. App Router's loading.js is a Suspense boundary, and streaming SSR — sending the page piece by piece as each part is ready — is built on Suspense. The loading states and streaming you use in Next.js are Suspense underneath.

8.4 React 19: Actions and the use Hook

Actions. A new way to handle forms and async work. useActionState manages a form submission's state (pending, error, result) without a pile of useState calls. useOptimistic shows an optimistic result first and rolls back if the server rejects it.

The use Hook. It reads a Promise or a Context during render, and unlike other Hooks it can be called conditionally: const data = use(fetchData()) waits for a Promise right inside the component.

Why Actions feel dangerous (his own judgment). He finds Actions dangerous, and the danger sits in Server Actions. A Server Action is a function marked "use server" that runs on the server but is called from the client — it looks like an ordinary function call, but it is a network request that executes on the server. Treat it as an API endpoint: validate and authorize on the server, never trust what the client sends, and do not pass sensitive objects or secrets as arguments. useOptimistic has its own trap: it shows a result before the server confirms it, so only use it when the rollback is simple, and always write the error branch.

8.5 Server Components

What they are. Server Components run only on the server and ship no JavaScript to the browser. They can reach the database, the filesystem, and backend APIs directly, without an API layer in between. They render to a serializable RSC payload, which client React reconciles.

The boundary. Client Components are the interactive ones (useState, useEffect, event handlers, browser APIs) and they do ship JavaScript. The boundary is the "use client" directive on a file. A Server Component can render Client Components as children; a Client Component cannot import a Server Component, because that would pull server code into the browser bundle.

The mental model. Server Components fetch data and render static content; Client Components handle interaction. Data flows down as props from server to client.

Where it came from. Server Components were proposed by the React team (2020) and co-developed with Vercel/Next.js — Next.js 13's App Router was the first framework to ship them. It feels like a Next.js feature because, for a long time, App Router was the only place you could use them. Other frameworks (Waku, Redwood, React Router) support them now, but Next.js remains the main implementation.

8.6 Compiler

What it does. React Compiler is a build-time tool that automatically memoizes your code: it analyzes a component's data flow and inserts the equivalent of useMemo, useCallback, and memo where they help. You write plain code; the Compiler adds the caching.

Why it matters. Hand-written memo is easy to get wrong (missed dependencies, reference traps) — the same failure modes behind the memo ban in §7.2. The Compiler does it correctly and automatically, so manual memo becomes less important in React 19 and beyond.

8.7 Where state lives: the state-layer principle

His architectural stance. Connection state, message lists, the current room — these are state, and they should be maintained as state. Stuffing complex logic into effects causes problems, and as the code grows it becomes unmaintainable. The destination, once the logic grows, is a state manager: the connection lifecycle lives in a store, components read state and call actions, and effects stop fighting callbacks. It is the same principle as the memo ban: solve the problem at the state layer, do not patch it at the component layer.

à propos de cette entrée

L'une des entrées de wiki de sijie. L'IA sur ce site est fondée sur le même corpus et répond à la voix de sijie, avec citations revenant à des entrées comme celle-ci — répondre coûte argent à sijie, donc cela attend derrière un code : entrer un code d'accès →

react — Sijie Wang