CS Fundamentals Trainer · Guides
Advanced React: re-renders, memoization, refs, data fetching and what React 19 changed
How React renders and re-renders, a triage ladder from measuring through structure, caching and the React Compiler to transitions and virtualization, identity and keys, Context against split contexts and stores, stale closures, refs, layout and portals, data fetching (waterfalls and out-of-order responses explained by arithmetic you can check, and how to measure your own) and error handling, with what React 19.3 changed.
65 min read
Most React trouble is not in the syntax. It is in when components run, what they remember between runs, and which version of your data a piece of code is looking at. This guide is organised around that. It starts with a triage ladder (the cheapest, safest fix first) and a symptom index, then explains the mechanism behind each rung: rendering, structure, memoization and the React Compiler, urgency and doing less, identity and keys, shared state, effects and stale values, refs, layout and portals, asynchronous data and error handling. It also marks what changed in React 19, because several older recipes are now different.
How to read it.
| You want | Read |
|---|---|
| The model and the fixes in 15 minutes | Start here, sections 1 and 2, the Quick recap |
| To fix a slow or wrong screen | Start here, then the symptom index, then the section it names |
| The whole picture | In order. Sections 3 (compiler checks), 7 (closures), 10 (data) and 11 (errors) are the deep dives; skip them on a first pass |
About the examples. The React snippets are illustrative and follow the documentation for React 19.3, the newest release at the time of writing (9 September 2026). The four scripts in the appendix are plain JavaScript on Node.js 22 that model mechanisms behind sections 7 and 10; they are not React.
What kind of evidence is in this guide.
| Kind | Where | How far to trust it |
|---|---|---|
| Documented behaviour | react.dev, MDN, TanStack and the other sources named in the text | as far as the source; check the version |
| Derived reasoning | the Context comparison (section 6) and the race probability (section 10) | it follows from the rules stated; confirm it in your own Profiler or Network panel |
| Mechanism demonstration | the scripts in the appendix | they show why a pattern behaves as it does; their numbers depend on parameters chosen by the author |
| Measured on a real app | none | no figure in this guide describes your app or production; section 4 shows how to record yours |
Start here: a triage ladder
In short. Measure first, then take the cheapest fix that removes the cause. Every rung costs more complexity than the one above it, so stop as soon as the problem is gone.
| Rung | Ask | Typical fix | What it costs you | Section |
|---|---|---|---|---|
| 1. Measure | Is it slow for a person, and in which interaction? | record one fixed interaction in the Profiler; look at the Performance panel | nothing | 4 |
| 2. Remove work by structure | Does something re-render that does not depend on what changed? | move state down; lift content up as children | a small refactor, easy to undo | 2 |
| 3. Cache | Does an expensive component re-render with unchanged inputs? | the React Compiler; otherwise memo and useMemo | prop stability becomes your job; stale-cache bugs | 3 |
| 4. Reorder | Is the work needed, but not urgent? | useTransition, useDeferredValue | the screen is briefly out of date; total work does not shrink | 4 |
| 5. Do less | Is there simply too much to render? | virtualization, pagination, content-visibility | find-in-page, focus, accessibility and scroll position need care | 4 |
| 6. Move it | Is it computation, not rendering? | a Web Worker, or the server | serialization and a more complex architecture | 4 |
The order is by risk, not by power. Structure changes cannot go stale and are easy to read; caching can silently serve old data; virtualization changes how the page behaves for keyboards, screen readers and search. A team that jumps to rung 5 for a problem rung 2 solves pays for it for years.
Symptom index.
| What you see | Usual cause | First fix | Section |
|---|---|---|---|
| Typing in a field lags | state lives too high, above a slow tree | move state down, or lift the slow content up | 2, 4 |
| A list is slow every time anything changes | rows re-render with unchanged data | compiler or memo with stable props; virtualize if there are very many rows | 3, 4 |
| A form loses its text or focus when something updates | a component defined inside another component, or an unstable key | declare it at the top level; use stable keys | 5 |
| After reordering, a row keeps another row's input | array index used as key | use the record's id | 5 |
| One context change re-renders half the page | every consumer follows every change | split the context, or use a store with selectors | 6 |
| A timer or handler logs an old value | stale closure | list the dependency, use an updater or useEffectEvent | 7 |
| The screen shows another item's data after quick clicks | a slower, older response arrived last | cleanup with an ignore flag, or a data library | 10 |
| The page fills in step by step | a request waterfall | hoist, prefetch or restructure the requests | 10 |
| The whole screen goes blank after one error | no error boundary | boundaries at page and widget level | 11 |
| A modal or tooltip is clipped | an ancestor with overflow or a stacking context | a portal, or the native <dialog> | 9 |
| A position flickers after measuring | measuring in useEffect | useLayoutEffect, or CSS | 9 |
1. How React renders
In short. A render is React calling your function, not a screen update. Parents re-render children by default; props are not the trigger.
Three words are used loosely and need to be exact.
- A component is a function that takes props and returns elements.
- An element is a plain object describing what to render: a type (
'div', or a component) and props. Writing<Child />creates an element; it does not runChild. - A render is React calling the component function. It is not a screen update.
React works in two phases. In the render phase it calls components to compute what the UI should look like and compares that with the previous result. In the commit phase it applies the differences to the DOM, updates refs and runs layout effects; ordinary effects (useEffect) run afterwards. So a component can render and cause no DOM change at all, and in concurrent rendering the render phase may be paused, repeated or thrown away, which is why render must be pure: no mutating existing objects, no network requests, no Math.random() or Date.now() in the result, no state updates during render (Erikson, React docs).
A render is triggered by a state update (in the component itself or in a hook it calls, even if the value is never displayed), by a change in a context it reads, or by its parent rendering. The last one is the surprise: by default, when a component renders, React renders all the children it returns, whether or not their props changed, and so on down the tree. Skipping one component skips its whole subtree (Erikson). Props changing is not what triggers a re-render; it only matters when you ask React to compare them (section 3).
Diagram: What happens after a state update
A default model, not a law. "A parent re-renders its children" describes what happens unless something stops it, and several things can: the child's element is the same object as last time because it was created higher up (section 2), the child is wrapped in React.memo and its props are shallow-equal (section 3), or the React Compiler has memoized the element (section 3). So the set of components that actually run after a state update is often smaller than the subtree below the component that changed, and it moves when you add memoization or switch the compiler on. Do not reason from the rule alone: open the React DevTools Profiler and look at which components rendered and why.
Two practical consequences. A re-render is not a bug: it is how React shows new data, and for most components it costs microseconds. It matters when a slow component re-renders very often, for instance a large tree below an input that updates on every keystroke. And in development, Strict Mode renders components twice to expose impure code, so a console.log in a component body printing twice is expected.
2. Keeping re-renders small by structure
In short. Move state down, or pass the slow part in as children. It removes work instead of caching it.
Before reaching for caching, change where things live. Dan Abramov's Before You memo() describes two techniques that need no memoization, and they are still the best first move:
Move state down. If a small piece of UI owns the state, give that piece its own component, so only it re-renders (any React version with hooks, 16.8+):
// Before: typing re-renders <SlowTree /> too
function App() {
const [text, setText] = useState('');
return (<><input value={text} onChange={(e) => setText(e.target.value)} /><SlowTree /></>);
}
// After: the state lives in a component that renders only the input
function SearchBox() {
const [text, setText] = useState('');
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}
function App() { return (<><SearchBox /><SlowTree /></>); }
Lift content up. When the state must stay in a wrapper that surrounds the slow part (a scroll container, a resizable panel), let the parent of the wrapper create the slow element and pass it in as children (any React version):
function ScrollArea({ children }: { children: React.ReactNode }) {
const [y, setY] = useState(0); // updates on every scroll event
return <div onScroll={(e) => setY(e.currentTarget.scrollTop)}>{children}</div>;
}
// <SlowTree /> is created here, by a component that does not render when y changes,
// so React receives the same element object and skips it.
<ScrollArea><SlowTree /></ScrollArea>
This works because of element identity: the element created by the outer component is the same object on the inner component's re-render, so there is nothing to compare or redo. children is only a prop, and the same holds for any prop that carries an element (icon={<Icon />}, footer={<Footer />}). Elements as props also keep a component simple: instead of iconColor, iconSize and other configuration props, the caller passes the finished element. When the wrapper must give the element some data (the hover state), a render prop (renderIcon={(hovered) => ...}) does it, although a custom hook is now often the cleaner way to share stateful logic.
Two things that undermine these techniques: a custom hook does not isolate renders, because a state update anywhere inside a hook re-renders the component that calls it, and a hook that calls another passes the update up the chain; and subscribing to something that changes often (scroll position, window size, a global store) in a big component re-renders all of it. Higher-order components (functions that take a component and return an enhanced one) are the pre-hooks way to share behaviour; they still fit for wrapping a group of components with the same logging or event interception, but a hook or a wrapper component is usually simpler.
3. Memoization, and what the React Compiler changes
In short. Memoization only helps when something compares the prop. The compiler now does most of it; know how to check what it did.
React compares objects, arrays and functions by reference (Object.is), not by content, in dependency arrays and in React.memo props. A function or object created in a component body is a new value on every render. The tools:
| Tool | What it keeps | When it matters |
|---|---|---|
useMemo(fn, deps) | the result of fn until deps change | an expensive calculation, or a value used as a dependency or as a memoized component's prop |
useCallback(fn, deps) | the function itself | the same, for functions |
React.memo(Component) | skips rendering when the props are shallow-equal and the render was caused by the parent | an expensive component whose parent renders often with unchanged data |
Why manual memoization is harder than it looks, a point made by Erikson and at length by TkDodo ("the uphill battle of memoization"):
- Memoizing a prop is useless unless something compares it: the receiving component must be wrapped in
React.memo, use the prop as a hook dependency, or pass it to something that does. - One unstable prop defeats
React.memofor the whole component. Inline objects, arrays, functions and JSXchildrenare new references on every render, and a new fallback such asvalue ?? []can break stability again. Someone adding a prop later can silently undo the benefit. React.memoonly stops re-renders caused by the parent. A state change or context change inside the component still renders it.- Comparing is not free. Measure first; memoization pays for slow work, not for cheap expressions.
Since 2025: the React Compiler. React Compiler 1.0 became stable on 7 October 2025. It is a build-time tool that analyses components and hooks and adds memoization automatically, including cases manual memoization cannot reach, such as code after an early return. It supports React 17 and up, is installed as a Babel plugin (babel-plugin-react-compiler) pinned to an exact version, is offered by the Vite, Next.js and Expo templates, and its lint rules come through eslint-plugin-react-hooks. The official guidance:
| Situation | Guidance from the React Compiler 1.0 announcement |
|---|---|
| New code | rely on the compiler; add useMemo and useCallback only where you need precise control, for example a value used as an effect dependency so that the effect does not run too often |
| Existing code | leave existing memoization in place (removing it can change what the compiler produces), or remove it only after careful testing |
| Code that breaks the Rules of React | the compiler can change behaviour, such as an effect running more or less often; with weak test coverage, pin the exact compiler version |
The announcement says nothing specific about React.memo, so I make no claim about it. What follows: understanding why memoization works and fails is still what you need to read compiler output and debug it; what ages is the advice to write most of it by hand. Structural fixes (section 2) still help because they remove work instead of caching it. And measure: React DevTools' profiler and, since 19.2, the Performance Tracks in Chrome DevTools show what rendered and why. Erikson's later talk on the compiler's rendering behaviour is a good next step.
Checking what the compiler did. "The compiler is on" is not the same as "my component was compiled", and a component the compiler skips simply runs without automatic memoization, with no error at run time. Four checks, from cheapest to most detailed (react.dev, Installation and Configuration):
- React DevTools. In development, components the compiler optimized show a "Memo ✨" badge next to their name. A hot component without it was not compiled.
- The build output. Compiled code imports
c as _cfromreact/compiler-runtimeand keeps results in a cache array (const $ = _c(1)), so a quick search of the built file forcompiler-runtimetells you whether a file was transformed at all. - Lint. The compiler's rules ship in
eslint-plugin-react-hooks(therecommended-latestpreset). The docs state what an error means: the compiler will skip optimizing that specific component or hook, which is safe and leaves the rest of the codebase optimized. So a lint error on a component is the usual reason for a missing badge. - Build-time events. The
loggeroption takes alogEvent(filename, event)function, so a build can print what was compiled (the docs' example checksevent.kind === 'CompileSuccess');panicThreshold: 'none'makes the build skip a problematic component instead of failing.
React 17 or later with babel-plugin-react-compiler (Compiler 1.0, stable). The most common reason for a skip is code that breaks the Rules of React, usually by changing something it does not own during render:
function Leaderboard({ scores }: { scores: number[] }) {
const top = scores.sort((a, b) => b - a).slice(0, 3); // sort() mutates the PROP array in place: a Rules of React violation
return <ol>{top.map((s) => <li key={s}>{s}</li>)}</ol>; // the lint rule reports it; the compiler skips this component
}
// Fix: copy first. `[...scores].sort(...)` or `scores.toSorted(...)` leaves the prop untouched.
To take a component out on purpose, put the directive "use no memo" as the first statement of its body (the docs' way to opt out a component that misbehaves). To go the other way, compilationMode: 'annotation' compiles only functions marked "use memo", which is the supported route for adopting the compiler one component at a time.
Before and after in the Profiler. I have not included a trace, because the numbers depend on your app, but the comparison is easy to make yourself: (1) in React DevTools open Profiler and, in its settings, enable Record why each component rendered while profiling; (2) record one fixed interaction, such as typing five characters in the search field; (3) repeat with the compiler off and on, or before and after a structural change from section 2. Compare three things: how many components lit up in each commit (a grey bar means it did not render), which ones and the reason shown for each (props changed, state changed, parent rendered), and the commit time of the slowest commits. If the compiler or your change worked, the components that do not depend on the typed text should be grey. Measure in a production build when you can, because development builds (Strict Mode double rendering included) are slower and differ.
4. When it is still slow: measuring, urgency and doing less
In short. After structure and caching, you can render the same work later (transitions), render less of it (virtualization), or not render it until it is needed. First, measure with the same fixed interaction every time.
Measure your own app. Two small helpers show what renders and why. They are illustrative and meant for development: <Profiler> does nothing in a normal production build unless you use the profiling build of React DOM.
import { Profiler, useEffect, useRef, type ProfilerOnRenderCallback, type ReactNode } from 'react';
const totals = new Map<string, { commits: number; ms: number }>();
const onRender: ProfilerOnRenderCallback = (id, _phase, actualDuration) => {
const t = totals.get(id) ?? { commits: 0, ms: 0 };
totals.set(id, { commits: t.commits + 1, ms: t.ms + actualDuration }); // actualDuration: time spent rendering this subtree
};
/** Wrap a subtree; after one interaction call `report()` in the console. */
export function Audit({ id, children }: { id: string; children: ReactNode }) {
return <Profiler id={id} onRender={onRender}>{children}</Profiler>;
}
export const report = () => console.table(Object.fromEntries(totals));
/** Logs which props changed since the last render; "none" means state, context or the parent caused it. */
export function useRenderCause(name: string, props: Record<string, unknown>) {
const previous = useRef(props);
useEffect(() => { // compared in an effect: refs must not be read during render
const changed = Object.keys(props).filter((k) => !Object.is(previous.current[k], props[k]));
console.log(`${name} rendered; props changed: ${changed.join(', ') || 'none'}`);
previous.current = props;
});
}
Use it the same way each time: wrap the screen in <Audit>, do one fixed interaction (type five characters), call report(), and write down the commits and milliseconds. Repeat after each change. The numbers are only meaningful relative to each other, on your machine, in the same build.
Urgent and not urgent: transitions. Typing must feel instant; refreshing a long list may wait a moment. useTransition marks a state update as non-urgent, so React can start rendering it, abandon that render if an urgent update (the next keystroke) arrives, and show the result when it finishes (React 18 or later):
function FilterableList({ items }: { items: Item[] }) {
const [query, setQuery] = useState(''); // urgent: what the field shows
const [shown, setShown] = useState(items); // not urgent: what the big list shows
const [isPending, startTransition] = useTransition();
return (
<>
<input
value={query}
onChange={(e) => {
setQuery(e.target.value); // painted at once
startTransition(() => setShown(filterItems(items, e.target.value))); // may be interrupted by the next keystroke
}}
/>
<Rows items={shown} stale={isPending} /> {/* dim the list while it catches up */}
</>
);
}
When the value comes from somewhere you cannot wrap in a transition (a prop, a custom hook), useDeferredValue gives you a lagging copy instead:
const deferredQuery = useDeferredValue(query); // old value during an urgent update, new value a moment later
return <><input value={query} onChange={...} /><SlowRows query={deferredQuery} /></>;
const SlowRows = memo(function SlowRows({ query }: { query: string }) { /* the slow part */ }); // memo is what lets it skip the urgent pass
What to know before using either:
- They reorder work; they do not remove it. The total rendering is the same, and so is the network traffic (a deferred value does not debounce requests).
- A single slow component cannot be interrupted. React can pause between components, not in the middle of one. If one component takes 300 ms, a transition will not make it faster.
useDeferredValueneeds the slow child to be memoized (withmemoor the compiler). Otherwise the child renders once with the old value and once with the new one.- A transition cannot drive a controlled text field; the field's own state must stay urgent, as in the example.
- Show that the screen is behind:
isPending, orquery !== deferredQuery, is the signal for dimming. - A transition that suspends keeps the old screen instead of replacing already-visible content with a fallback.
- React 19:
startTransitionaccepts an async function (an Action), but a state update after anawaitis not part of the transition; wrap it in its ownstartTransition.
Doing less. When the list itself is the problem, rendering it faster is the wrong lever; render fewer rows.
| Technique | What it removes | What it costs you |
|---|---|---|
Windowing (@tanstack/react-virtual, react-window) | React work and DOM nodes for rows outside the viewport | browser find-in-page cannot see unrendered rows; row heights must be known or measured; scroll restoration and keyboard focus on removed rows need handling; screen readers need aria-rowcount and aria-rowindex or equivalents |
| Pagination or "load more" | data fetched and rows rendered | the navigation model changes, but it is the simplest and the most accessible |
content-visibility: auto with contain-intrinsic-size | the browser's layout and paint of off-screen sections | React still runs the components, so the JavaScript cost stays; check browser support for your targets |
<Activity mode="hidden"> (19.2 or later) | work for parts of the UI the user cannot see; effects are unmounted and updates deferred while state is kept | memory stays in use; it fits tabs and likely next pages, not long lists |
A reasonable rule: below a few hundred cheap rows, memoized rows are simpler and safer; with thousands, or with expensive rows, windowing pays for its complexity. Decide from the audit, not from the row count alone.
When it is not rendering at all. If the audit shows little render time but the interaction is still slow, the cost is computation in a handler (sorting or parsing a large data set), and it appears in the browser's Performance panel instead of the Profiler. Move it to a Web Worker or to the server, or do it once and keep the result, rather than recomputing it on every keystroke.
A worked case: the filterable table. Typing in a filter box above a table of 5,000 rows lags. One way down the ladder, with what to look for in the audit at each step (the figures are yours to record):
| Step | Change | What the audit should show |
|---|---|---|
| 0 | Record: <Audit> around the page, type five characters, report() | one Row commit per row per keystroke, with the cause "none" (parent rendered) |
| 1 | Structure: keep query in the component that needs it and lift the table's other content up as children | the header and sidebar stop appearing |
| 2 | Cache: compiler, or memo on Row with stable props | rows that survive the filter stop rendering; rows that appear still cost |
| 3 | Reorder: useDeferredValue(query) into the table | the field stays responsive; the table catches up a moment later |
| 4 | Do less: window the rows | only the rows in view render, whatever the data size |
| 5 | Move: if filtering 5,000 records is itself slow, filter in a worker | the keystroke handler is short again in the Performance panel |
Most real screens stop at step 1 or 2. The point of the ladder is that you know the next move and what it will cost you before you make it.
5. State belongs to a position: identity, keys and resets
In short. State belongs to a position in the tree. Keys give identity, and changing a key resets state.
React keeps a component's state according to where it sits in the tree, not where it appears in the JSX (React docs, "Preserving and Resetting State"). Rules that follow:
- The same component type at the same position keeps its state, even if its props change;
{isFancy ? <Counter isFancy /> : <Counter />}keeps one counter. - A different type at that position (
<Counter />replaced by<p>, orsectionbydiv) destroys the old subtree and its state and mounts a new one. - A conditional like
isOpen ? <Panel /> : nullalways occupies one slot. - In dynamic lists, position is not a reliable identity, so each item gets a
key: a stable value, unique among its siblings, that identifies it across re-orders, insertions and removals.
Four consequences that cause real bugs:
- Never define a component inside another component. The inner function is a new function, so a new type, on every render; React unmounts and remounts it each time, losing its state, focus and running effects. Declare components at the top level.
- Do not use the array index as a key in lists that can be reordered, filtered or inserted into: state (an input's text, a checkbox) stays with the position, not the data. Use the record's id.
- Do not generate keys during render (
Math.random(),crypto.randomUUID()): every render produces new keys, so every item remounts. - A key is also a reset button. Changing it makes React treat the component as a different one:
<Profile userId={id} key={id} />discards the previous user's form state whenidchanges. The React docs prefer this to an effect that tries to reset state by hand, which renders once with stale state first. A key is not a prop; the component never receives it.
Keys matter more when items are expensive or wrapped in React.memo, because a wrong key makes a memoized item re-render or lose its state.
6. Sharing state: props, Context, reducers and stores
In short. Context re-renders every consumer on every change. Split it, or use a store with selectors, but first ask who should own the state.
Context passes a value deep into the tree without threading it through every level, which also avoids rendering the components in between. The cost, explained by Erikson: a provider compares its value by reference, and every component that reads the context re-renders when it changes, even if it only uses one field, and React.memo does not stop it. A provider that builds its value in render (value={{ user, setUser }}) creates a new object on every render, so all consumers re-render whenever the provider does. Context is a way to deliver a value, not a state-management tool: it has no selectors and no subscription to slices.
What helps:
- Memoize the value (
useMemo) and its functions (useCallback), so that the provider rendering for an unrelated reason does not change it. - Split contexts by how often things change: the React docs' pattern for combining a reducer with context uses two contexts, one for the state and one for
dispatch, becausedispatchnever changes, so a component that only dispatches does not re-render when the state does. - Pass children through the provider rather than creating them inside it, so they are not re-rendered by it (section 2).
- For larger or faster-changing state, use a store outside React with selectors (Zustand, Redux, Jotai and similar), where components subscribe to the slice they read. TkDodo makes this argument as the alternative to chasing prop stability; React's
useSyncExternalStoreis the primitive such stores use, and the docs recommend it over a hand-written subscription in an effect.
What changed in React 19:
| Then | Now |
|---|---|
<ThemeContext.Provider value={x}> | <ThemeContext value={x}>; the .Provider form still works, and the team plans a codemod and a future deprecation |
useContext(Ctx) at the top level only | use(Ctx) also reads context and, unlike hooks, can be called conditionally, after an early return for instance |
| a client wrapper to provide context from a Server Component | since 19.3, Server Components can render a context provider from a 'use client' module directly |
None of this changes the rule that consumers re-render when the value does; splitting remains design work.
Context is not a substitute for state ownership. Memoizing the provider's value stops re-renders caused by the provider's parent; it does not stop a consumer from re-rendering when the value it reads actually changes. Before reaching for any of the fixes above, ask who should own the state: if only two components need count, keep it in their nearest common parent and pass it as props. Context fits values that change rarely and are needed far away (theme, locale, the signed-in user). Four ways to share count and name between a CountView, a NameView and a ResetButton:
Works on React 16.8+ (hooks, createContext); the <Ctx value> form needs React 19. useSyncExternalStore needs React 18+. Illustrative.
// A. One context, memoized value: every consumer re-renders when EITHER field changes.
const AppCtx = createContext<{ count: number; name: string; reset(): void } | null>(null);
// B. Split contexts: state and actions apart, and one context per field that changes independently.
const CountCtx = createContext(0);
const NameCtx = createContext('');
const ActionsCtx = createContext<{ reset(): void }>({ reset() {} }); // stable: provide it with useMemo/useCallback
// C. An external store with selectors: a component subscribes to the slice it reads.
function useStore<T>(select: (s: State) => T): T {
return useSyncExternalStore(store.subscribe, () => select(store.getState())); // select must return a stable value
}
const count = useStore((s) => s.count);
// D. Ordinary props: the owner holds the state; pass only what each child needs.
function Owner() {
const [count, setCount] = useState(0);
const [name, setName] = useState('');
return <><CountView count={count} /><NameView name={name} /><ResetButton onReset={() => { setCount(0); setName(''); }} /></>;
}
Who re-renders when only count changes (assuming the provider component receives its children as props, section 2), by the rules documented in react.dev and in Erikson's guide (this is reasoning from those rules, not a measurement; confirm it in the Profiler for your tree):
| Approach | CountView | NameView | ResetButton | Cost and caveat |
|---|---|---|---|---|
| A. one context | yes | yes (it reads the same context) | yes | simplest; every consumer follows every change |
| B. split contexts | yes | no | no (it reads only the stable actions) | more providers to write and keep in the right order |
| C. store with selectors | yes | no | no | a new dependency or a small store to maintain; selectors must return stable values |
| D. props only | yes | yes, unless it is memoized or its element is created above the owner | yes, unless memoized (its onReset is a new function) | needs no extra machinery, but state ownership and prop passing become the design problem |
None of the four is always right. Props are the best default while the tree is shallow; split contexts or a store appear when many distant components read a value that changes often.
7. Effects, events and stale values
In short. A function keeps the values of the render that made it. Stale values come from that, and have four fixes in order of preference.
Choose the right tool first. The React docs' "You Might Not Need an Effect" is the best short list of mistakes: Effects are for synchronizing with external systems (the network, a non-React widget, the browser). Derive values during render instead of copying them into state; do user-caused work in the event handler, because by the time an effect runs you no longer know what the user did; avoid chains of effects that set state to trigger each other; reset state with key (section 5) rather than an effect; and subscribe to external stores with useSyncExternalStore.
Closures. A function created inside a component is a closure: it keeps references to the variables of that render, like a snapshot (MDN defines it as a function bundled with its lexical environment, created each time a function is created). When a long-lived function runs later, it sees the old snapshot unless it is created again. This is the stale-closure bug (hooks, React 16.8+):
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => console.log(count), 1000); // closes over THIS render's count
return () => clearInterval(id);
}, []); // never re-created, so it logs the first value forever
I reproduced the mechanics in plain JavaScript (closures.js): three timers created in different ways, after the value changed from 0 to 1 to 2.
| How the callback is created | Value it sees after the last change |
|---|---|
| once, closing over the first render (empty dependency list) | 0 (stale) |
| once, reading a ref that is updated after every render | 2 |
| re-created whenever the value changes (dependency list includes it) | 2 |
Fixes, in order of preference:
- List the dependency; the
react-hooks/exhaustive-depsrule finds it, and the docs advise against suppressing it, because suppression hides exactly these bugs. The effect cleans up and restarts with fresh values. - Use a functional update (
setCount((c) => c + 1)) so the value is not needed. - Use
useEffectEvent(documented with React 19.2): it separates "what to do" from "when to re-run". Its body always sees the latest props and state, but it is not reactive, so it does not restart the effect. The docs' example keeps a chat connection keyed onroomIdwhile a "connected" notification reads the currentthemewithout reconnecting when the theme changes. Limits from the docs: call it only from inside effects, never pass it to other components or hooks, and omit it from dependency arrays (the lint plugin enforces this). - Keep the latest function in a ref and read
ref.currentfrom the long-lived callback. This is the older pattern, still useful outside effects;useEffectEventnow covers the effect case.
Debouncing and throttling show the problem from the other side. A debounced function holds a timer, so it must be created once per component; created in the render body, each render gets its own timer and nothing is debounced. But created once, it closes over the first render. In closures.js I "typed" r, re, rea, reac, react ten milliseconds apart into a 50 ms debounce:
| Where the debounced function comes from | Searches performed |
|---|---|
| created in the render body (a new one each render) | 5: r, re, rea, reac, react; nothing was debounced |
| created once, closing over the first render | 1, with the wrong text: r |
| created once, calling the latest function through a ref | 1, correct: react |
Keep the debounced function stable and give it a way to reach fresh data. Often it is simpler to debounce a value (a useDebouncedValue hook that updates after a delay and cancels its timer on cleanup). useDeferredValue and transitions reduce rendering cost; they do not reduce network requests.
8. Refs
In short. A ref is a box that survives renders and does not re-render. In React 19 it is an ordinary prop.
A ref is a mutable object, { current: value }, that stays the same across renders. It differs from state in two ways that decide when to use it: changing it does not re-render, and the change is synchronous and visible at once, while state updates are scheduled and applied on the next render. So refs hold values that do not appear on screen: a timer id, the previous value, a DOM node, the latest callback (section 7). The React docs add a rule: do not read or write ref.current during render, only in event handlers and effects, or the component becomes impure; the compiler's lint rules (refs) flag it.
Reaching the DOM. const inputRef = useRef<HTMLInputElement>(null), then <input ref={inputRef} />; after the commit, inputRef.current is the element and inputRef.current?.focus() works from a handler.
Passing a ref to your own component is where React 19 changed things:
| Before (React 18) | Now (React 19) |
|---|---|
a function component could not receive ref; you wrapped it in forwardRef((props, ref) => ...) | ref is an ordinary prop: function MyInput({ placeholder, ref }) { return <input placeholder={placeholder} ref={ref} />; } |
forwardRef required | forwardRef still works but is no longer necessary; the docs mark it deprecated and a codemod is planned |
Other changes: ref callbacks may return a cleanup function (it runs on unmount, and React then no longer calls the ref with null), so write ref={(el) => { instance = el; }} with a block body, since TypeScript now rejects an implicit return; useRef needs an argument in TypeScript (useRef(undefined)); string refs are removed and element.ref is deprecated. Since 19.3, a ref on a <Fragment> gives a handle to a group of DOM children (addEventListener, focus, scrollIntoView) without a wrapper element.
An imperative API. When a parent really must command a child (focus(), shake(), scrollTo), expose a few methods with useImperativeHandle(ref, () => ({ shake, focus }), []) rather than handing out the whole DOM node. Use it sparingly: most communication should go through props and state.
9. Layout, painting and portals
In short. Measure before paint with useLayoutEffect; escape clipping with a portal, and remember that events follow the React tree.
useEffect or useLayoutEffect. useEffect runs after the browser has had the chance to paint; useLayoutEffect runs after React updates the DOM but before the browser paints (React docs). If an effect measures an element and then sets state to position or resize something, doing it in useEffect can show one frame in the wrong place, a visible flicker, and useLayoutEffect removes it. The docs' warning: its code and the state updates it triggers block painting, so use it only for measuring and positioning.
On the server, effects do not run, and useLayoutEffect triggers "useLayoutEffect does nothing on the server", since there is no layout to measure; the flicker can come back in server-rendered apps. The docs list the options:
| Option | Use when |
|---|---|
replace it with useEffect | the server HTML is acceptable until the effect runs |
render the component only on the client with use(browser()) (new in 19.3) | it cannot be server-rendered; a Suspense fallback goes into the HTML |
render it after mount (an isMounted state set in an effect) | the older, universal pattern |
useSyncExternalStore | the effect only read an external value, not layout |
Portals. A modal, tooltip or dropdown inside a container with overflow: hidden, or inside a parent that creates a stacking context (position with z-index, transform, opacity below 1, and others), can be clipped or trapped under other content, whatever its z-index. createPortal(children, document.body) renders the elements into another DOM node while keeping them in the same place in the React tree. So context and events follow the React tree (a click inside the portal fires onClick on its React ancestors), while CSS, native DOM events and form submission follow the DOM tree: a <button> in a portal does not natively submit the <form> it is rendered under. The docs add an accessibility duty: manage keyboard focus into and out of the portal and follow the WAI-ARIA modal practices. The browser's top layer (a native <dialog> opened with showModal(), and the Popover API) solves part of the same problem without a portal; check support for your targets.
10. Asynchronous data
In short. A chain of requests costs the sum, a group costs the slowest. Late responses from older requests are the usual bug, and they have simple cures.
The simple version and its limits. Fetching in an effect is valid, and the React docs say so. You then own loading and error states, caching, cancellation, retries, deduplication and refetching, and the docs point to a framework's built-in data fetching as the more efficient route. For anything beyond "fetch once and forget", use a data library (TanStack Query, SWR, RTK Query, Apollo) or your framework's data layer. Libraries cannot fix an app's structure, which is where waterfalls come from.
Evidence in this section. There are no measurements here. The two problems below are explained by arithmetic and by a deterministic trace, and the appendix scripts check the arithmetic. What you will see in your app depends on your latencies, your users' clicking and your caching, so section 4's habit applies: throttle the network in the browser's developer tools and record your own.
Waterfalls. A waterfall is a chain of requests in which each starts only after the previous one finished. The TanStack Query documentation lists the usual causes: dependent queries, nested components (a parent waits for its data before rendering a child, so the child's request starts late), code splitting (a lazy component's JavaScript loads only after its parent renders, and its request starts after that) and, with Suspense, several suspending queries in one component running one after the other.
sequential |-- user --|-- posts --|-- comments --| 3 x latency
together |-- user --|
|-- posts --|
|-- comments --| 1 x latency (the slowest)
| Shape | Time | With 100 ms per request (arithmetic, not a measurement) |
|---|---|---|
| n requests, one after another | n × L | 3 requests: 300 ms |
| n requests started together | L, the slowest | 3 requests: 100 ms |
| n requests, c connections at a time | ⌈n / c⌉ × L | 12 requests, 6 connections: 200 ms |
The last row is the old HTTP/1.1 limit of about six connections per host; HTTP/2 and HTTP/3 multiplex requests over one connection and lift it (DNS and HTTP). A browser adds DNS, TLS, caching and rendering on top of all of this, which is why the real figure is yours to record.
The fixes named by TanStack: restructure the API so dependent data arrives in one request, hoist independent requests to a parent so they run in parallel, prefetch early (at the router, on navigation), fetch data for a code-split component alongside its JavaScript, and do dependent fetching on the server, where latency is lower.
Promise.all only helps requests that do not need each other. If the posts request needs the user.id the first request returns, the second cannot start until the first has finished, whatever the syntax (await, .then, a hook, a loader). Only restructuring removes that wait: an endpoint that accepts what you already know (a username from the URL), a combined endpoint, a server-side join, or prefetching something you can derive earlier (route parameters). Not every waterfall needs fixing: look at the Network tab and fix the high-impact ones.
Race conditions. A response can arrive after a newer request's response. In an effect that fetches by id and then calls setData, clicking page 2 and then page 3 quickly can leave the screen showing page 2 while the address says page 3. The whole bug in four lines:
t = 0 ms click page 2 request A sent
t = 10 ms click page 3 request B sent
t = 40 ms B answered screen shows page 3 (correct)
t = 130 ms A answered naive code writes page 2 over page 3 (wrong, and it stays)
It needs two things at once: requests that overlap in time, and response times that vary by more than the gap between them. For two requests started g ms apart, with independent response times spread evenly between 0 and w ms, the older response arrives last with probability ½(1 − g/w)² when g < w, and never otherwise. formula.js in the appendix checks this against random draws.
| Response times spread over w | Requests g apart | Chance that the older response arrives last |
|---|---|---|
| 40 ms | 10 ms | 28% |
| 200 ms | 10 ms | 45% |
| 200 ms | 50 ms | 28% |
| 200 ms | 150 ms | 3% |
| 40 ms | 50 ms or more | 0% |
These are values of the formula, not observations of any app. Read them for the shape: fast, even responses and slow clicking hide the bug; slow, uneven responses and quick clicking show it often, and a third and fourth click add more pairs that can swap. The three fixes below need no such table, because each works by construction: the ignore flag makes the late write impossible, the id check makes it detectable, and abort stops the old request from finishing in the first place. They are correct whatever the timing, and that is the reason to prefer them to hoping the timing is kind.
The ignore flag is the React docs' own recipe: let ignore = false; in the effect, if (!ignore) setData(json) in the callback, and return () => { ignore = true; } as cleanup. It protects correctness: the stale result is simply not used. AbortController also prevents the stale write and may save resources, but be careful about how much it does (any React version with hooks; AbortController is a browser and Node API; illustrative):
useEffect(() => {
const controller = new AbortController();
fetch(`/api/pages/${id}`, { signal: controller.signal })
.then((r) => r.json())
.then(setData)
.catch((e) => { if (e.name !== 'AbortError') setError(e); });
return () => controller.abort(); // runs before the next effect and on unmount
}, [id]);
What aborting does and does not do. Aborting is client-side cancellation. Specifically:
- The browser stops waiting, and the
fetchpromise rejects with anAbortError(MDN, AbortController). - The unread part of the response is discarded, and the browser typically closes the connection or resets the HTTP/2 stream.
- It does not guarantee that the server stops. A server that already received the request may run the query or job to the end, unless it notices the closed connection and is written to stop (many server frameworks expose a request-closed or abort signal, and your handler has to use it).
- For a mutation (a POST that pays, sends or deletes), aborting undoes nothing: the server may have completed it. Use an idempotency key and read the real state afterwards instead of assuming the request did not happen.
So count on abort for the client's side (no stale write, no wasted download) and treat server savings as a bonus that needs cooperation. Use the ignore flag or the id check for correctness, and add abort when cancelling the download or the server work is worth it.
Remounting with a key (section 5) also removes the old results' target. async/await changes the syntax, not the behaviour. A data library handles all of this, which is one of the best reasons to use one. (The old warning "Can't perform a React state update on an unmounted component" has been removed from React.)
use(), Suspense and Actions (React 19).
- React 19 and later. React 19 documents
use(promise): a component reads a promise during render, React suspends it, and the nearest<Suspense fallback={...}>shows until it resolves. A rejected promise becomes an error for the nearest error boundary. Older material that calls Suspense for data "unsupported" predates this. - The promise must not be created during the render that reads it: a new promise on every render would never settle, and React warns. It must come from a Suspense-compatible cache, library or framework (a loader, a parent Server Component, or a promise held in a cache). That is why the library-or-framework advice above stands.
- React 19.0 also added pre-warming: when a component suspends, React commits the nearest fallback at once and keeps rendering the siblings to start their requests early, which reduces some waterfalls.
- For changes, React 19 adds Actions: async functions used in transitions that track a pending state, errors and form reset, with
<form action={fn}>,useActionState([state, formAction, isPending]),useFormStatusanduseOptimistic. They replace much hand-written "isLoading, error, setData" code for forms and mutations. - Suspense replaces fiddling with loading flags; it does not remove waterfalls caused by fetching in nested components, nor the need for caching.
// Illustrative; commentsPromise comes from a loader, a cache or a Server Component, not created here.
function Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {
const comments = use(commentsPromise); // suspends until resolved
return <ul>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul>;
}
<ErrorBoundary fallback={<p>Could not load comments.</p>}>
<Suspense fallback={<p>Loading...</p>}><Comments commentsPromise={commentsPromise} /></Suspense>
</ErrorBoundary>
11. Errors
In short. Boundaries catch render errors only. A complete setup also logs the error and lets the user retry.
By default an error thrown while React renders removes the whole UI, so a few error boundaries at sensible places (a page, a widget, a route) are close to mandatory. The React docs (the Component reference) state what a boundary catches and what it does not:
| Tool | Catches | Does not catch |
|---|---|---|
| error boundary | errors thrown while rendering the components below it, however deep | errors in event handlers, in asynchronous code such as setTimeout, in server-side rendering, and in the boundary itself (an exception: errors thrown inside a function passed to startTransition are caught) |
try/catch | errors in event handlers, callbacks and awaited code | errors thrown while rendering child components; you cannot usefully wrap a component's return |
The whole lifecycle once. Catching an error is the middle of the story; a useful screen also logs it and lets the user recover. The example below follows one failing request from start to retry (illustrative; the boundary comes from the community react-error-boundary package, which hides the class component, and use() needs React 19; reportError stands for your logging call):
const cache = new Map<string, Promise<Comment[]>>(); // a Suspense-compatible cache: the same key gives the same promise
function loadComments(postId: string, attempt: number) {
const key = `${postId}:${attempt}`; // a new attempt is a new key, so a retry makes a new request
if (!cache.has(key)) {
cache.set(key, fetch(`/api/posts/${postId}/comments`).then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`); // fetch does NOT reject on 404 or 500: turn them into errors yourself
return r.json();
}));
}
return cache.get(key)!; // (a real cache would also expire entries)
}
function Comments({ postId, attempt }: { postId: string; attempt: number }) {
const comments = use(loadComments(postId, attempt)); // a rejected promise is thrown here, during render
return <ul>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul>;
}
export function CommentsPanel({ postId }: { postId: string }) {
const [attempt, setAttempt] = useState(0);
return (
<ErrorBoundary
resetKeys={[postId, attempt]} // recover when the post or the attempt changes
onError={(error, info) => reportError(error, info.componentStack)} // 3. logging
fallbackRender={() => ( // 4. what the user sees
<div role="alert">
<p>Could not load comments.</p>
<button onClick={() => setAttempt((a) => a + 1)}>Try again</button> {/* 5. retry */}
</div>
)}
>
<Suspense fallback={<p>Loading...</p>}><Comments postId={postId} attempt={attempt} /></Suspense>
</ErrorBoundary>
);
}
| Step | What happens | Who handles it |
|---|---|---|
| 1. The request fails | the promise rejects (a network error, or the Error thrown for a bad status) | your loader |
2. use() reads it | the rejection is thrown during render, so the nearest boundary catches it | the error boundary |
| 3. Logging | onError receives the error and the component stack; in React 19 the root's onCaughtError also sees it | your reporting service |
| 4. Fallback | the boundary renders the message and the button; the rest of the page keeps working | the boundary |
| 5. Retry and recovery | the click bumps attempt; the new key makes a new request; resetKeys changed, so the boundary resets and Suspense shows the loading state again; success replaces the fallback | the cache key and resetKeys |
Add a limit in real code (a few retries, with a delay that grows) so a dead server is not hit in a tight loop, and report the final failure. A data library gives you most of this without writing the cache: TanStack Query has throwOnError and a reset boundary for exactly this pairing, and most frameworks have a route-level error component.
When re-throwing during render is justified. Throwing the error into render (the useAsyncError pattern below, or showBoundary from react-error-boundary's useErrorBoundary hook, which does the same thing and is the better choice than hand-writing it) is justified when the failure came from somewhere a boundary cannot see (an event handler, a timer, a .then outside render) and the component cannot usefully continue, so you want the whole fallback. It is the wrong tool for errors the user can fix in place, such as a form validation message or a failed save with a "retry" button next to the form: handle those with ordinary state and keep the screen. And when the supported route exists, take it: a framework's loader and route error component, or the library's error option, give you logging, retry and recovery already wired together.
A boundary is still a class component (getDerivedStateFromError to show the fallback, which must be pure, and componentDidCatch for side effects such as logging); there is no hook for it. Write one reusable class, or use the community react-error-boundary package, as the docs suggest. To get async errors into a boundary, catch them and re-throw during a render, where the boundary can see them:
function useAsyncError() {
const [, setState] = useState();
return useCallback((e: unknown) => setState(() => { throw e; }), []); // thrown inside a state updater, i.e. during render
}
React 19 and later. What changed in React 19: render errors are no longer re-thrown; uncaught errors go to window.reportError and caught errors to console.error, and new root options let you hook in: onCaughtError (a boundary caught it), onUncaughtError (nothing did) and the existing onRecoverableError. Pass them to createRoot or hydrateRoot and send the errors to your logging service. Errors are also logged once, with full information. With use() and Suspense, pair a Suspense boundary with an error boundary, as in the example above.
12. What is new since React 18
| Release | Date | What matters for this guide |
|---|---|---|
| React 19.0 | 5 Dec 2024 | ref as a prop; ref cleanup; use(); Actions, useActionState, useOptimistic, useFormStatus; <Context value>; onCaughtError and onUncaughtError; Suspense pre-warming |
| React 19.2 | 1 Oct 2025 | useEffectEvent; <Activity> (hide part of the UI with mode="hidden": effects unmount and updates are deferred, state is kept, and likely next pages can be pre-rendered); cacheSignal for Server Components; Performance Tracks in Chrome DevTools |
| React Compiler 1.0 | 7 Oct 2025 | automatic memoization (section 3) |
| React 19.3 | 9 Sep 2026 | <ViewTransition> and addTransitionType stable; Fragment refs; use(browser()); Trusted Types support; Server Components can render context providers |
Which version does an example need? The release table mixes three kinds of change, and a reader on an older React can copy something that does not run for them. Use this list before pasting code:
| Feature | Needs | Kind |
|---|---|---|
Hooks, createContext, React.memo, useLayoutEffect, portals, error boundaries (class), AbortController in effects | React 16.8 or later (portals 16.0; error boundaries 16.0) | stable core |
useSyncExternalStore, useDeferredValue, transitions | React 18 or later | stable core |
ref as a prop, <Ctx value>, use(), Actions, useActionState, useOptimistic, onCaughtError | React 19.0 or later | stable core; not in React 18 |
useEffectEvent, <Activity> | React 19.2 or later | stable core; not in React 19.0 or 19.1 |
use(browser()), <ViewTransition>, Fragment refs | React 19.3 | stable core, newest release |
| React Compiler | its own package, babel-plugin-react-compiler, installed in the build | a build tool, not part of the react package; supports React 17 and up |
| Server Components, Server Functions | a framework or bundler that implements them (Next.js, React Router and others) | needs the framework; not available in a plain client-only setup |
react-error-boundary, TanStack Query, Zustand | the library's own releases | third-party libraries, not React |
If you are on React 18, the guide's patterns still apply, but swap in the older forms: forwardRef, <Ctx.Provider>, useEffect with a ref for useEffectEvent, and an ignore flag or a data library instead of use().
Security: Server Components. In December 2025 the React team disclosed CVE-2025-55182, an unauthenticated remote code execution flaw (CVSS 10.0) in React Server Components, in how the server decodes requests to Server Function endpoints. It affected react-server-dom-webpack, -parcel and -turbopack in versions 19.0, 19.1.0, 19.1.1 and 19.2.0 and the frameworks that bundle them (Next.js, React Router, Waku and others), and was fixed in 19.0.1, 19.1.2 and 19.2.1; later advisories covered denial of service and source-code exposure and are fixed in the same upgrade path. Apps with no server, or without a framework or bundler that supports Server Components, were not affected. The lesson is operational: if you use Server Components or Server Functions, keep React, its server packages and your framework on the latest patch release, and do not treat host-level mitigations as a substitute. See web application security for the general habits.
Server Components are a large topic this guide leaves out. They run only on the server, can read data directly and ship no client JavaScript of their own; Client Components (marked 'use client') hold the interactivity. Everything above about re-renders, refs and effects applies to Client Components.
13. Where to learn more
No single source covers all of this, and the sources disagree in emphasis, so read more than one:
| Source | Good for |
|---|---|
react.dev (Learn and Reference): "Preserving and Resetting State", "You Might Not Need an Effect", "Separating Events from Effects", the createPortal, useLayoutEffect and Component references | the authoritative, current rules, and the release posts for what changed |
| Mark Erikson, A (Mostly) Complete Guide to React Rendering Behavior (2020) and his talks on rendering and on the compiler | a precise model of rendering, context and memo |
| Dan Abramov, Before You memo() (overreacted.io) | the two structural techniques and the element-identity idea behind them |
| TkDodo, The uphill battle of memoization | why manual memoization is fragile, and the external-store alternative |
| TanStack Query docs, "Performance & Request Waterfalls" | how waterfalls form and how to remove them |
| MDN, Closures | the JavaScript semantics underneath stale state |
| Nadia Makarevich, Advanced React (2023, advanced-react.com) | a book-length, example-driven investigation of re-renders, memoization, reconciliation, Context, refs, closures, portals, data fetching, race conditions and error handling; written for React 18, so read the changes in this guide beside it |
14. Common mistakes
- Memoizing props of a component that nothing compares, or wrapping everything in
React.memowhile passing a new object, function orchildreneach render. - Defining a component inside another component, losing its state on every render.
- Using the index or a random value as a
key. - Putting a value that changes often into one big Context, with everything reading it.
- Calling
fetchin an effect with no cleanup, so a slower older response wins. - Assuming
AbortControllerstops the server or undoes a request that already reached it. - Quoting a figure from a demonstration, or from someone else's app, as if it described yours; record your own.
- Reaching for virtualization or a transition before measuring and restructuring.
- Expecting
useDeferredValueto help a child that is not memoized, oruseTransitionto speed up one slow component. - Assuming the compiler optimized a component without checking the badge or the lint output.
- Using Context for fast-changing state, or memoizing the provider value as a replacement for deciding who owns the state.
- Starting dependent requests from nested components, so they run one after the other.
- Leaving a dependency out of an effect to "make it run once", then reading stale values.
- Creating a debounced function in the render body.
- Reading or writing
ref.currentwhile rendering. - Using
useLayoutEffectfor something that does not need to block painting, or on the server without a plan. - Expecting an error boundary to catch an error thrown in an event handler or a promise.
- Writing new
forwardRefwrappers, or hand-memoizing everything in a codebase that already uses the compiler. - Copying a tutorial without checking which React version it targets.
15. Things to mention in an interview
- "A render is calling the component function. It re-runs when its state or a context it reads changes, or its parent renders, and then its children run again by default, unless something prevents it: their elements are the same objects, they are memoized, or the compiler memoized them. I check the Profiler instead of assuming."
- Structure before caching: move state down, pass content as
children;memo,useMemoanduseCallbackcache and need stable props; the compiler now does most of that. - State follows position in the tree;
keygives identity in lists and can reset state; a component defined inside a component remounts every render. - Context re-renders all consumers on any value change; split it, memoize the value, or use a store with selectors.
- Refs are mutable boxes that do not re-render; in React 19
refis a prop andforwardRefis on its way out. - Stale closures: the dependency list, functional updates,
useEffectEventand the latest-ref pattern. - Out-of-order responses are fixed by cleanup with an ignore flag or a request-id check for correctness;
AbortControlleralso cancels on the client but does not make the server stop, and does not undo a mutation. A library hides all of it. - Waterfalls come from nested or dependent fetching; start independent requests together and early, or move them to the server.
- When it is still slow: measure, then structure, cache, reorder (
useTransition,useDeferredValue: same work, later, interruptible between components), do less (windowing, pagination), and move computation off the main thread. Name the cost of each step. - Error boundaries catch render errors only; async errors need
try/catch, and a re-throw into render only when the whole fallback is wanted; a complete setup also logs the error and offers a retry; React 19 addsonCaughtErrorandonUncaughtError. - What changed: the Compiler,
use(), Actions,useEffectEvent,<Activity>, and the Server Components security patches.
Quick recap
- A render is a function call, not a screen update; by default parents re-render children unless something stops it, and props are not what triggers it.
- Restructure first, memoize second, and let the React Compiler do routine memoization in new code. If it is still slow, reorder (transitions), do less (windowing) or move work off the main thread, in that order, and measure each step.
- State follows position; keys give identity and can reset state; never define components inside components.
- Context re-renders every consumer; split it, or use a store with selectors.
- Closures are snapshots: fix stale data with dependencies, updaters,
useEffectEventor a latest-ref. - Refs are mutable and silent;
refis a prop in React 19. - Fetch with cleanup, in parallel where requests are independent (dependent ones need restructuring, not
Promise.all), through a library or a framework;use()needs a promise from a cache, not one made in render. - Error boundaries for render errors, with logging and a retry;
try/catchfor async ones; root-level reporting. - Keep React and its server packages patched, and read more than one source.
Appendix: the experiment code
All four scripts use only Node.js 22 (no packages) and model the JavaScript mechanics behind the topics; none of them runs React or a browser. formula.js checks the closed-form race probability quoted in section 10, and waterfall.js checks its arithmetic. race.js and closures.js demonstrate mechanisms; their numbers depend on the parameters at the top of each script, so change them, and the guide does not quote them as results. race.js uses fixed seeds, so its counts repeat from run to run; the timings in waterfall.js vary by a few milliseconds.
formula.js: the race probability, checked
Run with node formula.js; it takes a second or two. It compares the closed form in section 10 with random draws.
// Two requests started `gap` ms apart; each response time is uniform between 0 and `width` ms, independent of the other.
// The bug: the OLDER request's response arrives after the NEWER one's, so a naive effect shows the older data last.
function simulate(width, gap, rounds = 1_000_000) {
let wrong = 0;
for (let i = 0; i < rounds; i++) {
const older = Math.random() * width; // response time of the first request
const newer = Math.random() * width; // response time of the second request, which started `gap` ms later
if (gap + newer < older) wrong++; // the newer response arrived first
}
return wrong / rounds;
}
const formula = (width, gap) => (gap < width ? 0.5 * (1 - gap / width) ** 2 : 0);
for (const [width, gap] of [[40, 10], [200, 10], [200, 50], [200, 150], [40, 50]]) {
console.log(`w=${width} g=${gap}: formula ${(100 * formula(width, gap)).toFixed(1)}% simulated ${(100 * simulate(width, gap)).toFixed(1)}%`);
}
race.js: out-of-order responses and four strategies
Run with node race.js; it takes about twenty seconds because it repeats the experiment across seeds, timings and failure rates.
// Out-of-order responses: the mechanics behind a data-fetching race in an effect. Plain Node.js 22, no React.
// This demonstrates a mechanism. It is NOT an estimate of how often the bug happens in production: every number below depends
// on the delay range, the spacing between requests and the failure rate chosen here. Change them and watch the numbers move.
// Each "render" starts a request for its own id (page 1, 2, 3). The outcome of the LAST request started (data, or an error if
// that request failed) is the correct final state of the screen.
function makeRng(seed) { let s = seed >>> 0; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296); }
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// One round: three requests started gapMs apart, with delays and failures fixed by `plan` so every strategy sees the same rounds.
async function round(strategy, plan, gapMs) {
let screen = null, latest = 0, staleWrites = 0;
const cleanups = [], pending = [];
const fakeFetch = (id, signal) => new Promise((resolve, reject) => {
const { ms, fail } = plan[id - 1];
const t = setTimeout(() => (fail ? reject(new Error('network error')) : resolve('data ' + id)), ms);
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new DOMException('aborted', 'AbortError')); });
});
for (let id = 1; id <= 3; id++) {
latest = id;
cleanups.splice(0).forEach((f) => f()); // React runs the previous effect's cleanup first
let ignore = false; const ac = new AbortController();
if (strategy === 'ignore-flag') cleanups.push(() => { ignore = true; });
if (strategy === 'abort') cleanups.push(() => ac.abort());
const apply = (value) => {
if (strategy === 'ignore-flag' && ignore) return;
if (strategy === 'compare-id' && id !== latest) return;
screen = value;
if (id !== latest) staleWrites++; // an out-of-date result was written to the screen
};
pending.push(fakeFetch(id, strategy === 'abort' ? ac.signal : undefined)
.then(apply, (e) => { if (e.name !== 'AbortError') apply('error ' + id); }));
await sleep(gapMs);
}
await Promise.all(pending);
const expected = plan[2].fail ? 'error 3' : 'data 3';
return { wrong: screen !== expected, staleWrites };
}
async function run(strategy, cfg, seed, rounds) {
const rnd = makeRng(seed);
const plans = Array.from({ length: rounds }, () => [1, 2, 3].map(() => ({
ms: cfg.minMs + Math.floor(rnd() * (cfg.maxMs - cfg.minMs + 1)), fail: rnd() < cfg.failRate })));
const out = await Promise.all(plans.map((p) => round(strategy, p, cfg.gapMs))); // rounds are independent, so run them side by side
return { wrong: out.filter((x) => x.wrong).length, stale: out.reduce((a, x) => a + x.staleWrites, 0) };
}
const strategies = ['naive', 'ignore-flag', 'compare-id', 'abort'];
const base = { minMs: 5, maxMs: 45, gapMs: 10, failRate: 0 };
const SEEDS = [1, 2, 3, 4, 5];
(async () => {
console.log('A. Five seeds, 400 rounds each (delays 5-45 ms, requests 10 ms apart, no failures): rounds ending with the wrong screen');
for (const s of strategies) {
const w = []; for (const seed of SEEDS) w.push((await run(s, base, seed, 400)).wrong);
console.log(' ' + s.padEnd(12), 'min ' + String(Math.min(...w)).padStart(3), ' max ' + String(Math.max(...w)).padStart(3), ' [' + w.join(', ') + ']');
}
console.log('B. Naive strategy, varying the delay range and the spacing between requests (no failures): % of rounds ending wrong (5 seeds x 200 rounds)');
for (const [lo, hi] of [[5, 15], [5, 45], [5, 205]]) {
const row = [];
for (const gap of [10, 50, 150]) {
let w = 0; for (const seed of SEEDS) w += (await run('naive', { ...base, minMs: lo, maxMs: hi, gapMs: gap }, seed, 200)).wrong;
row.push((w / 10).toFixed(1).padStart(5) + '%');
}
console.log(' delays ' + (lo + '-' + hi + ' ms').padEnd(9), 'spacing 10 / 50 / 150 ms:', row.join(' '));
}
console.log('C. Failure rate (delays 5-45 ms, 10 ms apart): % of rounds ending wrong (5 seeds x 200 rounds)');
for (const f of [0, 0.05, 0.2]) {
const row = [];
for (const s of strategies) { let w = 0; for (const seed of SEEDS) w += (await run(s, { ...base, failRate: f }, seed, 200)).wrong; row.push(s + ' ' + (w / 10).toFixed(1) + '%'); }
console.log(' failures ' + String(Math.round(f * 100)).padStart(2) + '%:', row.join(' | '));
}
})();
waterfall.js: sequential and parallel requests against a local server
Run with node waterfall.js; each cell is the median of seven runs.
// Request waterfalls and a per-host connection limit, modelled with a local HTTP/1.1 server (Node 22, no React, no browser).
// This demonstrates a mechanism. It is NOT a prediction for production: a real page adds DNS, TLS, caching, HTTP/2 multiplexing,
// server-side variation and rendering time. What carries over is the shape: a chain of N dependent requests costs about N x latency,
// independent requests started together cost about 1 x latency, and a connection limit adds one extra "round" per batch of requests.
// Every endpoint answers after a fixed delay. Each measurement is repeated and we report the median and the range.
const http = require('http');
const server = http.createServer((req, res) => {
const ms = Number(new URL(req.url, 'http://x').searchParams.get('ms') || 100);
setTimeout(() => { res.end(JSON.stringify({ path: req.url })); }, ms);
});
const get = (agent, path, ms) => new Promise((resolve, reject) => {
http.get({ port: server.address().port, path: `${path}?ms=${ms}`, agent }, (r) => { r.resume(); r.on('end', resolve); }).on('error', reject);
});
const time = async (f) => { const t = performance.now(); await f(); return Math.round(performance.now() - t); };
const stat = (xs) => { const s = [...xs].sort((a, b) => a - b); return `${s[Math.floor(s.length / 2)]} ms (${s[0]}-${s[s.length - 1]})`; };
const REPEATS = 7;
server.listen(0, async () => {
const keep = (n) => new http.Agent({ keepAlive: true, maxSockets: n });
const warm = async (a, n) => { await Promise.all(Array.from({ length: n }, (_, i) => get(a, '/warm' + i, 1))); }; // open the connections first
const measure = async (f) => { const xs = []; for (let i = 0; i < REPEATS; i++) xs.push(await time(f)); return stat(xs); };
console.log(`Median and range of ${REPEATS} runs.`);
console.log('A. Three requests, by latency per request');
for (const L of [20, 100, 300]) {
const a = keep(6); await warm(a, 6);
const dep = await measure(async () => { await get(a, '/user', L); await get(a, '/posts', L); await get(a, '/comments', L); });
const par = await measure(() => Promise.all([get(a, '/user', L), get(a, '/posts', L), get(a, '/comments', L)]));
const one = await measure(() => get(a, '/user-with-posts-and-comments', L));
console.log(` latency ${String(L).padStart(3)} ms | dependent chain ${dep.padEnd(18)} | started together ${par.padEnd(18)} | one combined endpoint ${one}`);
a.destroy();
}
console.log('B. Twelve independent requests at 100 ms each, by the number of connections allowed');
for (const n of [1, 2, 6, 12]) {
const a = keep(n); await warm(a, n);
console.log(` ${String(n).padStart(2)} connection${n === 1 ? ' ' : 's'} | ${await measure(() => Promise.all(Array.from({ length: 12 }, (_, i) => get(a, '/r' + i, 100))))}`);
a.destroy();
}
server.close();
});
closures.js: stale closures and three ways to debounce
Run with node closures.js.
// The JavaScript mechanics behind stale closures and debouncing in components. Plain Node.js 22; NOT React.
// A "render" is a function call that receives the current state; anything created inside it closes over THAT render's state.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }
(async () => {
// ---- 1. Stale closure: a callback created in render 1 and kept ("effect with empty dependencies") ----
const slots = { latest: { current: 0 } }; // a ref: one mutable object that survives across renders
const seen = { stale: [], viaRef: [], recreated: [] };
let recreatedTimer;
const render = (count, first) => {
slots.latest.current = count; // "update the ref after each render"
if (first) {
setInterval(() => seen.stale.push(count), 20); // closure over render 1's count, never replaced
setInterval(() => seen.viaRef.push(slots.latest.current), 20); // reads the mutable ref: always the newest
}
clearInterval(recreatedTimer); // "dependencies changed: clean up and create again"
recreatedTimer = setInterval(() => seen.recreated.push(count), 20);
};
render(0, true); await sleep(100);
render(1, false); await sleep(100);
for (const k in seen) seen[k].length = 0; // look only at what happens after the last render
render(2, false); await sleep(100);
process.stdout.write('1. values seen by a 20 ms timer after the last render (count went 0 -> 1 -> 2)\n');
for (const [k, v] of Object.entries(seen)) console.log(' ' + k.padEnd(10), [...new Set(v)].join(','));
// ---- 2. Debounce created in three ways; the user types "r", "re", "rea", "reac", "react" 10 ms apart ----
const typed = ['r', 're', 'rea', 'reac', 'react'];
async function scenario(kind) {
const calls = [];
const search = (q) => calls.push(q);
let kept; // what a hook would keep between renders
const latestSearch = { current: search };
const renderInput = (text) => {
latestSearch.current = () => search(text); // new function each render, sees this render's text
if (kind === 'recreated-in-render') return debounce(() => search(text), 50); // new timer every render
if (kind === 'kept-but-stale') { kept ??= debounce(() => search(text), 50); return kept; } // first render's closure
if (kind === 'kept-with-ref') { kept ??= debounce(() => latestSearch.current(), 50); return kept; }
};
for (const text of typed) { renderInput(text)(); await sleep(10); }
await sleep(120);
return calls;
}
console.log('2. searches performed while typing "react" (5 renders, 10 ms apart, 50 ms debounce):');
for (const k of ['recreated-in-render', 'kept-but-stale', 'kept-with-ref']) console.log(' ' + k.padEnd(20), JSON.stringify(await scenario(k)));
process.exit(0);
})();
Sources
- React team, Preserving and Resetting State, You Might Not Need an Effect, Separating Events from Effects, Scaling Up with Reducer and Context, and the references for
createPortal,useLayoutEffect,forwardRefandComponent(error boundaries). - React team, React v19, the React 19 Upgrade Guide, React 19.2, React 19.3, React Compiler v1.0 and React Versions.
- React team, Critical Security Vulnerability in React Server Components (CVE-2025-55182, affected and fixed versions).
- Mark Erikson, A (Mostly) Complete Guide to React Rendering Behavior, and A Guide to React Compiler Rendering.
- Dan Abramov, Before You memo().
- TkDodo, The uphill battle of memoization.
- TanStack Query, Performance & Request Waterfalls.
- MDN, Closures, and AbortController.
- React team, React Compiler: installation, configuration and the reference for
use. - Brian Vaughn, react-error-boundary (
ErrorBoundary,resetKeys,useErrorBoundary). - Nadia Makarevich, Advanced React (2023), a book-length treatment of several topics in sections 2 to 11; see section 13.
Practise this topic: React