Questions 141–150 of 150 · 0 of 10 on this page marked learned
141.react-0141Hardsenior
When is it valid to call setState during render, and how does it replace getDerivedStateFromProps?
React allows a component to call its own setState during render, as long as it is guarded by a condition so it stops. React then discards the current render output and re-renders the component immediately with the new state, before running children or effects. It is the recommended way to adjust state when a prop changes (store the previous prop in state and compare), and it avoids the extra commit and flash of an effect. Prefer a key or computing during render when possible.
Full answer
Normally setting state while rendering is a mistake, and calling another component's setter during render raises an error. There is one supported exception: updating the same component's own state during its render.
How it works. If the component calls its own setter during render, React finishes that render call, throws the result away, and re-runs the component immediately with the updated state, without committing or rendering children in between. The user never sees the intermediate result. Without a guard it loops until React stops with a "Too many re-renders" error, so the call must be conditional.
Use case: reacting to a prop change. The class component API getDerivedStateFromProps did this. In function components you keep the previous prop in state, compare it during render, and update both the stored prop and the dependent state when it differs. The example below does exactly that.
Compare with an effect that resets state: the effect version commits the stale state first, runs the effect, and then renders again, so users can see one frame with outdated selection. The render-phase version is committed once with consistent values.
Better alternatives, in order:
Compute the value during render if it can be derived (no state needed): store the selected id and derive the object.
Reset the whole component with a key when an identity changes: <List key={listId} />.
Use the render-time update pattern only when you need to keep some state and adjust part of it.
Rules: only update the same component's state, always guard with a condition comparing values, and keep logic simple. Do not use this pattern for side effects (network, subscriptions).
The example resets a selection when the list changes, and logs how many times the function runs.
The check pressed every button in order: Change list first, which changed the items. The log shows one "props changed" line followed by two body lines: the first body run belongs to the discarded pass, and the second to the immediate re-run. Then the other buttons were pressed. Output of the run:
Picker body ran, selected=null
props changed during render: resetting the selection
Picker body ran, selected=null
Picker body ran, selected=null
Picker body ran, selected=Art
Picker body ran, selected=Music
Key points
A component may update its own state during render if the update is guarded by a condition.
React discards the render and re-runs the component immediately, before committing or rendering children.
It replaces getDerivedStateFromProps and avoids the stale frame that an effect causes.
Prefer deriving values or using a key. Use the pattern only for partial adjustments.
Never use it for side effects or for other components' state.
Common mistakes
Calling setState during render without a guard, causing an infinite loop.
Using this pattern for side effects such as requests.
Updating a different component's state during render.
Using an effect to reset state and showing a stale frame.
Reaching for it when a key would be simpler.
Follow-ups
Why does an effect-based reset show a stale frame?
When is a key a better solution?
What error does React raise for an unguarded update?
Tips
Mention that it is supported only for the same component.
Compare with the effect version and its extra frame.
Offer the key and derived alternatives first.
142.react-0142Hardsenior
How would you architect a React design system (tokens, headless primitives, variants, versioning, accessibility) for several products?
Layer it. Design tokens (colors, spacing, type) are the single source of truth. Headless primitives (behaviour and accessibility with no styling, such as Radix or React Aria) sit on top, then styled components with typed variants, then composed patterns. Keep a small stable API (composition over many props), document with Storybook, test accessibility and visual regressions, version with semantic versioning and changesets, and support theming through CSS variables.
Full answer
A design system is a product with users (other developers), so it needs a clear structure and a release process.
Layers:
Tokens. Named values for color, spacing, radius, typography and motion, stored in a neutral format (JSON, with a tool such as Style Dictionary) and output as CSS variables. Themes (light, dark, brand) swap token values, not component code.
Primitives (headless). Components that provide behaviour and accessibility without styling: dialog, menu, tabs, combobox, tooltip. Writing keyboard handling and ARIA correctly is hard, so build on tested libraries (Radix UI, React Aria, Headless UI, Ark UI) or write hooks that return props to spread.
Styled components. Buttons, inputs and cards that apply tokens, with variants as typed props (variant, size, tone) mapped to class names or CSS variables (class-variance-authority or similar). Limit the variant matrix.
Patterns. Compositions such as form fields, data tables and page headers.
API design. Prefer composition (<Card><Card.Header/></Card>, children, slots) to long lists of boolean props. Forward refs and rest props (ref is a prop in React 19) so consumers can attach behaviour. Support the as or asChild pattern for links. Be strict with accessibility defaults (labels required in types where possible).
Delivery. A package in a monorepo, published with semantic versioning. Use changesets, codemods for breaking changes, tree-shakeable ESM output, a CSS strategy that avoids runtime cost (CSS variables, CSS modules, or zero-runtime CSS-in-JS), and a deprecation policy.
Quality. Storybook as catalogue and playground, interaction tests with play functions, axe checks, visual regression (Chromatic or similar), unit tests for logic, and visual and accessibility review in pull requests.
Governance. Contribution guidelines, an owner team, a roadmap driven by product needs, usage analytics (which components are used) and design tooling parity (Figma components match code).
Pitfalls: building too many variants early, leaking implementation details in props, no migration path, and styling overrides that break consistency.
The example shows a token-driven button with typed variants on top of a headless toggle hook.
jsx
import { useState } from 'react';
// Tokens: the single source of truth, usually generated and output as CSS variables.
const tokens = { color: { primary: '#0b5fff', neutral: '#444' }, space: { sm: '4px', md: '8px' } };
// Headless behaviour: state and accessibility props with no styling.
function useToggle(initial = false) {
const [pressed, setPressed] = useState(initial);
return { pressed, buttonProps: { 'aria-pressed': pressed, onClick: () => setPressed((p) => !p) } };
}
// Styled layer: variants are typed props mapped to tokens.
const variants = {
primary: { background: tokens.color.primary },
neutral: { background: tokens.color.neutral },
};
function ToggleButton({ variant = 'neutral', children }) {
const { buttonProps } = useToggle();
return (
<button {...buttonProps} style={{ ...variants[variant], padding: tokens.space.md, color: 'white' }}>
{children}
</button>
);
}
export default function App() {
return (
<div>
<ToggleButton variant="primary">Bold</ToggleButton>
<ToggleButton>Italic</ToggleButton>
</div>
);
}
This sketch shows the layers in one file: tokens, a headless hook and a styled component. A real system splits them into packages. The check pressed both buttons. Rendered result: <div><button aria-pressed="true" style="background: rgb(11, 95, 255); padding: 8px; color: white;">Bold</button><button aria-pressed="true" style="background: rgb(68, 68, 68); padding: 8px; color: white;">Italic</button></div>
Key points
Layer the system: tokens, headless primitives, styled components and patterns.
Reuse tested headless libraries for accessible behaviour, and theme with CSS variables.
Design small composable APIs with typed variants, forwarded refs and asChild or as.
Ship as a versioned package with changesets, codemods and a deprecation policy.
Test accessibility and visuals, document in Storybook, and govern with owners and usage data.
Common mistakes
Building every component from scratch instead of using tested headless primitives.
Exposing dozens of boolean props instead of composition.
Shipping breaking changes with no codemod or deprecation period.
Letting products override styles freely and losing consistency.
Treating the design system as a one-time project without owners.
Follow-ups
How would you theme the system with CSS variables and support dark mode?
How do you version and communicate a breaking change?
How do you measure adoption of the design system?
Tips
Present the layers in order and name a tool for each.
Mention governance and versioning. They are what makes it work at scale.
Emphasize accessibility as a default.
143.react-0143Hardsenior
Why use a state machine (useReducer or XState) for complex UI flows, and how does it prevent impossible states?
A state machine lists the states a flow can be in and the events allowed in each state. Booleans such as isLoading, isError and isSuccess can combine into impossible states (loading and error at once). A single status field with a reducer that checks the current state before applying an event makes invalid transitions impossible and logic easy to test. useReducer is enough for small flows. XState adds visualisation, guards, delayed transitions and actors for larger ones.
Full answer
Complex flows (checkout, wizards, upload, authentication, form submission with retry) often start with several booleans. With isLoading, isError and data, there are eight combinations, and many of them make no sense. Bugs appear when one flag is updated and another is forgotten.
A state machine fixes this with a model:
A finite set of states (idle, loading, success, error).
A set of events (SUBMIT, RESOLVE, REJECT, RETRY).
Transitions: for each state, which events are allowed and which state they lead to. Events that are not defined in a state are ignored.
Optional context data (the result or the error message) stored with the state.
Benefits. Impossible states cannot be represented. The behaviour is explicit and reviewable, and even a non-programmer can read the diagram. Testing becomes a matter of feeding events and checking states. Side effects (requests, timers) are triggered by transitions or by effects that react to the state, not by scattered handlers.
In React. useReducer with a status discriminated union and a switch on state.status is a lightweight machine. TypeScript helps by making each state carry only its relevant data. For larger flows, XState (createMachine, useMachine) adds guards (conditions), delayed transitions, parallel and nested states, actors for invoked work, and visual tools. Redux Toolkit's createSlice can be used in a similar way.
When not to use it. A simple toggle or a one-field form does not need it. The model pays off when there are more than two or three states, retries, cancellation or time-based transitions.
The example is a small submit flow where a duplicate SUBMIT during loading is ignored by design.
The check pressed the buttons in order: Submit, Fail, Retry, Succeed. Retry is only valid in the error state, and Fail only in loading, so the flow ended in success after going through loading twice. Rendered result: <div><p>Status: success</p><button>Submit</button><button>Fail</button><button>Retry</button><button>Succeed</button><p>Saved</p></div>
Key points
Multiple booleans allow impossible states. A single status makes them unrepresentable.
A machine defines states, events and which transitions are allowed in each state.
Events that are not valid in the current state are ignored, so double submits are harmless.
useReducer covers small flows, and XState adds guards, delays, nesting and tooling.
Do not use it for trivial state.
Common mistakes
Modelling a flow with independent booleans.
Allowing every event in every state and handling conflicts with ad hoc checks.
Storing derived flags such as isLoading next to status.
Starting requests inside the reducer.
Using a full machine library for a two-state toggle.
Follow-ups
How does a discriminated union help TypeScript users here?
How would you add a cancel event and a timeout in XState?
Where do side effects live in a machine-based design?
Tips
Start with the impossible-states example.
Draw the states and events, even for a simple case.
Say when it is overkill.
144.react-0144Hardsenior
How do you implement feature flags and A/B tests in a React application, and what pitfalls do you watch for?
Fetch flag values from a flag service (LaunchDarkly, Unleash, GrowthBook or your own) and expose them through a provider and a hook. Evaluate flags on the server where possible, so the first render has the right value and users do not see a flicker. Use stable user bucketing for experiments, log exposure when a user actually sees a variant, remove old flags quickly, and make sure each variant is tested and accessible.
Full answer
A feature flag is a runtime switch that decides which code path a user gets. An A/B test is a flag that assigns users to variants and measures a metric.
Architecture:
A flag source. A hosted service (LaunchDarkly, Statsig, GrowthBook, Unleash) or a simple JSON from your backend. It evaluates rules (percentage rollouts, user attributes, environments).
Delivery. For client-only apps, fetch flags at start and keep them in a context provider, with a useFlag('new-checkout') hook. For server rendering or Server Components, evaluate on the server and pass values to the client (as props or in a serialized payload), so the first HTML is already correct.
Usage. Keep conditionals small: choose between two components at one place rather than scattering checks. Provide safe defaults when the flag service is unreachable.
Experiment correctness:
Stable bucketing. Assign a user to a variant by hashing a stable id (user id or an anonymous cookie id) with the experiment key, so a user always sees the same variant across sessions and devices where possible.
Exposure events. Log an exposure when the variant is actually rendered to the user, not when the flag is evaluated, otherwise metrics are diluted.
Avoid flicker and layout shift. Do not render the control and swap to the variant after a request. Use server evaluation, edge middleware or a loading state.
Sample size and duration, and not stopping early, are statistical concerns that the team must respect.
Operational hygiene:
Short-lived flags have an owner and an expiry. Remove the flag and dead code once the rollout is complete.
Kill switches for risky features.
Test both branches in unit and end-to-end tests, and keep accessibility and performance equal across variants.
Do not use flags for security or authorization. The client can read and change anything it receives, so protect data on the server.
Be careful with bundle size: variants loaded with lazy avoid shipping unused code.
The example shows a flag provider, a hook and deterministic bucketing.
The bucket function is deterministic, so the same user always gets the same variant. In a real system the flag service owns this rule, and the exposure line would be sent to analytics once per user and not on every render. Output of the run:
same user, same variant again: true
exposure logged: checkout-experiment=control
Key points
Flags come from a service and are exposed with a provider and a hook, with safe defaults.
Evaluate on the server where possible to avoid flicker and layout shift.
Bucket users with a stable hash, and log exposure when the variant is actually shown.
Remove flags and dead code after rollout, and test every variant.
Never use client flags as access control.
Common mistakes
Showing the control and swapping after the flags load, causing flicker.
Logging exposure when the flag is evaluated and not when it is seen.
Leaving finished flags and old branches in the code.
Using client-side flags to protect paid or private features.
Randomizing the variant on every visit.
Follow-ups
How would you serve flags with server rendering without flicker?
How do you test a component that depends on a flag?
What is a kill switch and how is it different from an experiment?
Tips
Separate flags from experiments, and name the extra rules of experiments.
Mention exposure logging and stable bucketing.
Close with flag cleanup.
145.react-0145Hardsenior
How does React protect against XSS by default, where are the escape hatches that break this protection, and how does a Content Security Policy add defence in depth?
React escapes values placed in JSX, so a string is rendered as text and not as HTML. The risky places are dangerouslySetInnerHTML, URLs such as javascript: in href, rendering untrusted HTML from libraries, and direct DOM writes through refs. Sanitize any HTML you must render with a maintained library such as DOMPurify and validate URL schemes. A Content Security Policy (script-src with nonces or hashes, no unsafe-inline) limits the damage if something gets through.
Full answer
Default protection. In JSX, {userInput} is converted to a text node, so <img onerror=...> typed by a user shows as text and does not execute. This covers most cases.
Escape hatches and risks:
dangerouslySetInnerHTML. It inserts raw HTML, so untrusted input leads to XSS. If you must render user or CMS HTML, sanitize it first with DOMPurify (configure the allowed tags), ideally on the server, and keep the call site small and reviewed.
URLs. href={userUrl} with a javascript: URL executes when clicked. Validate that the scheme is http, https or mailto. React warns about javascript: URLs in development and plans to block them in future versions, but you should validate anyway.
Direct DOM writes (ref.current.innerHTML = ...), eval, new Function, and libraries that inject HTML (markdown renderers without sanitization).
Spreading untrusted objects as props (<div {...userProps} />) can set dangerouslySetInnerHTML or event handlers on elements.
Server rendering. Embedding serialized state in a script tag must escape < characters, otherwise </script> in data ends the script. Frameworks do this for you, hand-written SSR often does not.
Third-party scripts and dependencies (supply chain). Pin versions, audit and limit the scripts you load.
Defence in depth with CSP. A Content-Security-Policy header tells the browser which sources of scripts it may run. A strict policy uses nonces or hashes (script-src 'nonce-...' 'strict-dynamic') and avoids 'unsafe-inline' and 'unsafe-eval', so injected inline scripts do not run. Also consider object-src 'none', base-uri 'none', frame-ancestors to prevent clickjacking, and Trusted Types to control DOM sinks. Roll out in report-only mode first. Vite dev tools and some libraries use inline scripts or eval, so test the production build.
Other points: do not store tokens in localStorage if XSS is a concern (prefer httpOnly cookies), use SameSite cookies and CSRF protection, and treat all client-side checks as advisory.
The example demonstrates safe text rendering, a URL validator and sanitizing HTML with an allow-list.
jsx
import { renderToStaticMarkup } from 'react-dom/server';
const attack = '<img src=x onerror="alert(1)">';
function safeHref(url) {
try {
const parsed = new URL(url, 'https://example.com');
return ['http:', 'https:', 'mailto:'].includes(parsed.protocol) ? url : '#';
} catch {
return '#';
}
}
// A deliberately tiny allow-list sanitizer for the demo. Use DOMPurify in real code.
function sanitize(html) {
return html.replace(/<(?!\/?(b|i|em|strong)\b)[^>]*>/gi, '');
}
console.log('1. text child: ' + renderToStaticMarkup(<p>{attack}</p>));
console.log('2. javascript url is rejected: ' + safeHref('javascript:alert(1)'));
console.log('3. https url is kept: ' + safeHref('https://schoolabe.com'));
console.log('4. sanitized html: ' + renderToStaticMarkup(<p dangerouslySetInnerHTML={{ __html: sanitize('<b>Hello</b><img src=x onerror=alert(1)>') }} />));
This ran as a script with server rendering to a string. The regular text child was escaped. The hand-written sanitizer here is only an allow-list demo and is not safe for production. A real Content Security Policy is an HTTP header enforced by browsers, and this run does not exercise it. Output of the run:
1. text child: <p><img src=x onerror="alert(1)"></p>
2. javascript url is rejected: #
3. https url is kept: https://schoolabe.com
4. sanitized html: <p><b>Hello</b></p>
Key points
JSX escapes text by default, so ordinary interpolation is safe.
Escape hatches: dangerouslySetInnerHTML, javascript: URLs, direct DOM writes, spread props and unsafe SSR serialization.
Sanitize HTML with a maintained library and validate URL schemes.
CSP with nonces or hashes and no unsafe-inline limits the damage of an injection.
Prefer httpOnly cookies for tokens and keep dependencies audited.
Common mistakes
Using dangerouslySetInnerHTML with unsanitized CMS or user content.
Allowing javascript: URLs in links from user input.
Writing your own sanitizer instead of using a maintained library.
Using unsafe-inline in a CSP and believing it still protects scripts.
Storing long-lived tokens in localStorage on pages that render untrusted content.
Follow-ups
How does a nonce-based CSP work with server rendering?
What are Trusted Types, and how do they help?
Why is spreading untrusted props risky?
Tips
Begin with what React protects and then list the hatches.
Say CSP is a second layer and not a replacement for escaping.
Name DOMPurify and URL scheme validation.
146.react-0146Hardsenior
How do you persist state in localStorage correctly, including cross-tab sync and server rendering?
Treat localStorage as an external store and read it with useSyncExternalStore. Subscribe to the window storage event so other tabs update this one, provide a server snapshot so server and first client renders match, and wrap storage access in try/catch for private mode and quota errors. Do not read localStorage during the first render in an SSR app with useState, because it causes hydration mismatches. The storage event does not fire in the tab that made the change, so notify local listeners yourself.
Full answer
Naive persistence reads localStorage in a useState initializer and writes in an effect. It works in a single tab on the client, but breaks in common cases.
Problems:
Other tabs. A change in tab A leaves tab B showing old data until reload. The storage event fires in other tabs of the same origin (not the tab that wrote), so you can subscribe to it.
Server rendering. There is no localStorage on the server. If the client's first render uses the stored value, its HTML differs from the server HTML, which causes a hydration mismatch.
Failures. Access can throw in private modes, when storage is blocked or full, and stored values can be corrupted JSON.
Solution: useSyncExternalStore. Pass subscribe (adds a storage listener and a listener for local changes), getSnapshot (reads the current string from storage) and getServerSnapshot (returns a default). During hydration React uses the server snapshot, then re-renders with the real value if different, without a mismatch error. Writes go through a function that sets storage and notifies local subscribers, because the browser does not send the event to the writing tab.
Details:
Snapshots must be stable: return primitives (strings) from getSnapshot and parse outside, or cache the parsed value, otherwise React loops.
Validate and version stored data, and fall back to a default for bad JSON.
Store small, non-sensitive values only. Never store secrets or tokens that need protection.
For richer needs use libraries (Zustand persist, redux-persist), IndexedDB for large data, and BroadcastChannel for messages between tabs.
The example is a theme hook that follows other tabs.
jsx
import { useSyncExternalStore } from 'react';
const listeners = new Set();
function subscribe(listener) {
listeners.add(listener);
window.addEventListener('storage', listener);
return () => {
listeners.delete(listener);
window.removeEventListener('storage', listener);
};
}
function readTheme() {
try {
return window.localStorage.getItem('theme') ?? 'light';
} catch {
return 'light';
}
}
function writeTheme(value) {
try {
window.localStorage.setItem('theme', value);
} catch {
// Storage may be blocked or full. Keep the app working.
}
listeners.forEach((listener) => listener());
}
export default function ThemeSwitcher() {
const theme = useSyncExternalStore(subscribe, readTheme, () => 'light');
return (
<div>
<p>Theme: {theme}</p>
<button onClick={() => writeTheme('dark')}>Set dark</button>
</div>
);
}
The check set the theme in this tab and then simulated a write from another tab, by changing storage and dispatching a storage event. The component followed both changes. Output of the run:
start: Theme: light | stored: null
after Set dark in this tab: Theme: dark | stored: dark
after another tab changed it: Theme: light | stored: light
Key points
Read localStorage through useSyncExternalStore and not through a useState initializer.
The storage event reaches other tabs only, so notify local subscribers on writes.
Supply getServerSnapshot to avoid hydration mismatches.
Wrap access in try/catch and return stable snapshot values.
Keep stored data small, validated and non-sensitive.
Common mistakes
Reading localStorage in a useState initializer in a server-rendered app.
Expecting the storage event to fire in the same tab.
Parsing JSON inside getSnapshot and returning a new object each time.
Not handling blocked storage or invalid data.
Storing tokens or private data in localStorage.
Follow-ups
Why does useSyncExternalStore need getServerSnapshot?
When would you choose BroadcastChannel or IndexedDB?
How do you migrate the format of persisted data between versions?
Tips
Mention three failure modes: other tabs, SSR and storage errors.
Say that the writing tab does not receive the storage event.
Mention stable snapshots.
147.react-0147Hardsenior
What is stale-while-revalidate, and how do client data libraries (SWR, TanStack Query) and HTTP caching layers fit together?
Stale-while-revalidate shows cached data immediately and refetches in the background, then updates the UI when fresh data arrives. Libraries such as SWR and TanStack Query keep a client cache keyed by request, deduplicate concurrent requests, and revalidate on mount, focus or reconnect. HTTP caching (Cache-Control, ETag, CDN) works below this layer, so you tune staleTime, cache-control headers and invalidation together.
Full answer
The idea. A fast screen matters more than perfect freshness in most cases. Stale-while-revalidate (SWR) returns cached data right away (stale), starts a request in the background (revalidate), and replaces the data when the response arrives.
Client layer (SWR, TanStack Query, RTK Query):
A cache keyed by the request (['course', id]).
Deduplication. Ten components asking for the same key share one request.
Status flags separate the first load (isLoading) from background refreshes (isFetching).
Revalidation triggers: on mount, on window focus, on reconnect, on an interval, and after mutations through invalidation.
Staleness settings: TanStack Query's staleTime (how long data counts as fresh, default 0) and gcTime (how long unused data stays in memory). SWR revalidates on mount and focus by default and has options to adjust that.
Optimistic updates and rollback for mutations.
HTTP layer. Browsers and CDNs cache by headers. Cache-Control: max-age defines freshness, ETag and If-None-Match allow conditional requests (304 with no body), and the stale-while-revalidate directive lets a cache serve stale responses while it refreshes in the background. The client library cache sits above this: when it revalidates, the request may be answered from the browser or CDN cache.
Server layer. Server Components, Next.js caching and framework data functions add a server-side cache and revalidation (time-based or on demand). Different layers can hold the same data, so define who owns freshness: choose short client staleness with CDN caching for public data, and no-store for private and user-specific data.
Pitfalls: showing stale data for critical values (balances, stock) without indicating freshness, caching private responses on shared caches, unstable query keys that defeat the cache, and forgetting invalidation after a mutation.
The example is a minimal cache with deduplication and background revalidation, to show the mechanics. In real projects use a library.
This is a plain script with a toy cache and not a real library. The second call returned instantly with stale data while one background request refreshed it. Output of the run:
no cache yet, waiting
first call returned: course-7 v1
served stale: course-7 v1
second call returned: course-7 v1
background update arrived: course-7 v2
cache now holds: course-7 v2, requests made: 2
Key points
Stale-while-revalidate returns cached data first, then refreshes in the background.
HTTP caching (Cache-Control, ETag, CDN) works under the client cache, and the layers must be tuned together.
Distinguish isLoading (no data yet) from isFetching (refreshing).
Never cache private data on shared layers, and always plan invalidation.
Common mistakes
Treating stale data as correct for balances, inventory or permissions.
Using unstable query keys such as inline objects that change identity.
Caching private responses on shared CDN caches.
Forgetting to invalidate related queries after a mutation.
Confusing isLoading with isFetching in the UI.
Follow-ups
What do staleTime and gcTime control in TanStack Query?
How does the stale-while-revalidate Cache-Control directive differ from the client pattern?
How would you implement an optimistic update with rollback?
Tips
Define the pattern in one sentence and then place it in each layer.
Mention deduplication and invalidation.
Name one data type where staleness is unacceptable.
148.react-0148Hardsenior
What is islands architecture and partial hydration, and how does it differ from hydrating a whole React page?
With full hydration, the client downloads and runs the JavaScript for every component on the page, even static ones, to attach event handlers. Islands architecture renders the page to static HTML and hydrates only the interactive components (the islands), often lazily when they become visible or idle. The static parts ship no JavaScript. Astro popularised it, and React Server Components reach a similar goal by keeping server components out of the client bundle.
Full answer
Hydration attaches event handlers and state to server-rendered HTML. In a classic React SSR app (hydrateRoot(document, <App />)), the whole component tree must be loaded and executed in the browser, including components that never change, such as headers, articles and footers. The cost is JavaScript download, parse and execution, which delays interactivity (INP) on slower devices.
Islands architecture treats a page as mostly static HTML with a few interactive islands. The server renders everything. The browser receives HTML, plus a small script for each island, with its props serialized in the markup. Each island is hydrated independently with hydrateRoot on its own container, and the page can decide when: immediately (client:load in Astro), when the browser is idle, when the island scrolls into view (client:visible), or on a media query.
Benefits: much less JavaScript for content sites, faster interactivity, and independent failure and loading of islands. Costs: no shared React tree across islands, so shared state needs a store outside React or events, no context across islands, props must be serializable, and the mental model differs from a single app. It suits content-heavy pages such as blogs, documentation and marketing sites, and not highly interactive dashboards.
Related approaches:
Selective hydration in React 18+ (Suspense boundaries hydrate independently and prioritise what the user interacts with, but all code is still shipped).
React Server Components, where server components never ship to the browser and only use client components are hydrated.
Resumability (Qwik), which avoids hydration by serializing the state and loading handlers on demand.
The example simulates islands: it renders static HTML on the server with two island placeholders that carry serialized props, then hydrates one island and leaves the other untouched. It uses jsdom and hydrateRoot for real.
This ran as a script in jsdom. Only the island that was hydrated responded to the click, while the other kept its static HTML. Output of the run:
before hydration, island buttons have React props: false, false
after hydrating island 1 only: true, false
island 1 text: Count 2
island 2 text (never hydrated, click ignored): Count 50
Key points
Full hydration runs every component in the browser. Islands hydrate only the interactive parts.
Static parts ship no JavaScript, and islands can hydrate on load, idle or visibility.
Costs: no shared React tree or context across islands, and serializable props.
Selective hydration and Server Components are related but different tools.
It fits content sites better than highly interactive applications.
Common mistakes
Assuming SSR means the page is interactive immediately.
Sharing React context between separate islands.
Passing functions or class instances as island props.
Using islands for a highly interactive application.
Confusing selective hydration with shipping less JavaScript.
Follow-ups
How does React's selective hydration with Suspense differ from islands?
How would islands share state without a common React tree?
How do Server Components relate to islands?
Tips
Start with the cost of hydrating static markup.
Name the hydration strategies (load, idle, visible).
State the limits, especially shared state.
149.react-0149Hardsenior
Why does a single-page app need focus management on route changes, and how do you implement it accessibly?
On a normal page load, a browser resets focus and a screen reader announces the new page. In a single-page app, the URL and content change but focus stays on the clicked link, which may even be removed, so keyboard and screen reader users get no signal. After navigation, move focus to the new page heading (with tabIndex of -1), or to the main container, update document.title, and consider a polite live region announcement. Do not steal focus on the initial load.
Full answer
Full page loads give assistive technology several signals: the document title is read, focus returns to the top, and the reading position resets. A client-side router replaces content without those signals. Typical failures: focus stays on a link that no longer exists, so it jumps to the body, a screen reader says nothing, and a keyboard user must tab from the top through the header again.
Implementation options:
Move focus to the main heading. On route change, focus the <h1> of the new page. Headings are not focusable by default, so give them tabIndex={-1}, which allows focus() without adding them to the tab order. The screen reader then reads the heading.
Focus a container such as <main tabIndex={-1}> when headings differ in structure.
Announce through a live region: a visually hidden element with aria-live="polite" whose text is updated with the page title.
Update document.title (React 19 supports rendering <title> in components) so the title is accurate for each route.
Restore scroll position appropriately (routers provide this) and keep skip links working.
Details:
Do not move focus on the initial page load, only on later navigations, so it does not interrupt the browser's normal behaviour.
Use an effect keyed by the location (useEffect with the pathname) or the router's navigation hooks, and focus after the new content has rendered.
Frameworks help: Next.js and Remix provide route announcers and some handling, React Router offers primitives such as ScrollRestoration, but you still need to check the result with a screen reader.
For modals and menus, move focus in and return it to the trigger on close.
Test with keyboard only and with a screen reader (NVDA, VoiceOver), plus automated checks with axe, which cannot find this issue by itself.
The example uses a tiny state-based router and focuses the heading after each navigation except the first.
The check clicked Courses and About. After each navigation the heading received focus. On the first load, focus stayed on the document body. Output of the run:
first load: heading "Home", focus on "HomeCoursesAboutHome"
after clicking Courses: heading "Courses", focus on "Courses"
after clicking About: heading "About", focus on "About"
Key points
SPA navigation does not reset focus or announce the new page, which hurts keyboard and screen reader users.
Focus the new h1 (tabIndex -1) or main container after the route changes, and update document.title.
Use a polite live region as an alternative or addition for announcements.
Skip focus on the initial load, and focus after the new content has rendered.
Verify manually with keyboard and a screen reader, because automated checks miss it.
Common mistakes
Leaving focus on a link that disappeared after navigation.
Calling focus() on a heading without tabIndex -1.
Moving focus on the very first page load.
Relying only on automated accessibility tools.
Updating content without changing document.title.
Follow-ups
How would a live region announcement differ from moving focus?
How do modals return focus to their trigger?
What do Next.js and React Router do about this by default?
Tips
Describe what browsers do on a full load and what a SPA lacks.
Give the heading focus recipe with tabIndex -1.
Mention manual testing with a screen reader.
150.react-0150Hardsenior
How would you migrate a large legacy front end (class components, Redux, CRA, or jQuery pages) to modern React without a rewrite freeze?
Migrate incrementally. First stabilize: add tests around critical flows, set up CI and measure. Then upgrade the foundation (React version, build tool, TypeScript in allow-JS mode) and move new work to the new pattern, with a strangler approach: new routes or widgets in the new stack, old ones replaced gradually behind a shared shell. Use codemods, lint rules to stop new legacy code, and metrics to track progress. Avoid a big-bang rewrite.
Full answer
A big-bang rewrite freezes product work, loses hidden behaviour and often fails. Incremental migration keeps shipping.
Steps:
Understand and protect. Inventory the codebase (class components, deprecated lifecycles, legacy context, string refs, defaultProps on functions, CRA config). Add characterization tests and end-to-end tests for the most critical flows, so you can detect regressions. Set up error monitoring and performance baselines.
Upgrade the platform. Move to a supported React version step by step, reading the upgrade guides and running official codemods. Fix warnings in Strict Mode. Replace CRA (deprecated) with Vite or a framework, which can be done separately from React changes. Add TypeScript with allowJs and migrate file by file.
Establish the target and stop the bleeding. Document the new patterns (function components, hooks, a data-fetching library instead of hand-written Redux thunks, the router choice). Add ESLint rules and code review checks so new code does not add legacy patterns.
Strangle gradually. Migrate leaf components first, since they have few dependents, and then routes. Classes and function components interoperate, so there is no need to convert everything. For pages built with another framework (jQuery, Angular, old React versions), mount the new React pieces as widgets inside the old shell with their own createRoot, or put routing at a proxy or micro-frontend boundary, and move pages one at a time. Share design tokens, authentication and analytics between the old and new parts.
Replace state management where it hurts. Redux can stay for global client state while server state moves to TanStack Query or RTK Query. Remove boilerplate when files are touched.
Measure and finish. Track the percentage of migrated routes, bundle size, errors, and web vitals. Delete the old code and dependencies once nothing uses them.
Risks: running two stacks increases bundle size and inconsistency, so set a time box and an owner. Feature parity checks and gradual rollout (feature flags, percentage traffic) reduce risk. Communicate with the team and product so the migration has support.
The example shows the widget-mounting technique: a React 19 island created inside an existing page container managed by legacy code.
This ran as a script in jsdom. The widget has its own root, so the legacy page can mount and unmount it without a shared React tree. Output of the run:
widget mounted: Save: React basics
after click: Saved: React basics
legacy markup untouched: Legacy page (legacy)
after unmount, widget container is empty: true
Key points
Avoid big-bang rewrites. Protect critical flows with tests, then migrate in steps.
Upgrade the platform (React, build tool, TypeScript) separately from the architecture changes.
Use the strangler approach: new routes or widgets in the new stack, mounted in the old shell.
Add lint rules to stop new legacy code, and use codemods for mechanical changes.
Track progress with metrics, time-box the coexistence, and delete old code.
Common mistakes
Starting a full rewrite and freezing feature work.
Changing React version, build tool and architecture in one release.
Migrating pages without tests around critical flows.
Running two stacks forever without a time box.
Not preventing new legacy code with lint rules.
Follow-ups
How would you route between the legacy and new apps during the migration?
How do you decide the order of components to migrate?
Which codemods would you run first?
Tips
Lead with why not a rewrite, then give the sequence.
Separate platform upgrades from architecture changes.