← Interview prep

React interview questions

Hooks, rendering, state, and React interview favorites.

150 questions · Page 5 of 8

Want the full pack? Interview packs · Mock interview · Mentora

Page 5 of 8

Questions 81–100 of 150 · 0 of 20 on this page marked learned

81.react-0081Mediummid

What are the core ideas of the Next.js App Router (file conventions, Server and Client Components, loading and error files, Server Actions)? This question is specific to the Next.js framework.

This is framework-specific, not core React. In the App Router, folders define routes and special files define behaviour: page, layout, loading, error and not-found. Components are Server Components by default, can be async and fetch data directly, and ship no JavaScript. Add "use client" to a file for state, effects and browser APIs. Server Actions ("use server" functions) handle mutations from forms. In current versions params is a Promise to await.

Full answer

Next.js is a framework built on React, and the App Router (the app directory) is its routing model based on React Server Components. Interviewers ask about it because many React jobs are Next.js jobs, but remember to separate framework features from React itself.

Routing by files. Each folder is a URL segment, and a page file makes it public: app/courses/[id]/page.tsx serves /courses/123. layout wraps a segment and its children and persists between navigations. loading is shown through Suspense while the segment loads. error is an error boundary for the segment (it must be a Client Component). not-found renders for missing content. route files define API handlers. Dynamic segments use brackets, and groups in parentheses organize files without changing the URL.

Server and Client Components. Files are Server Components by default: they run on the server, can be async, can read a database or call an API directly, and their code does not reach the browser. A file starting with "use client" marks a boundary: that module and what it imports run in the browser too, which is needed for useState, useEffect, event handlers and browser APIs. Keep the boundary low in the tree, so most of the page stays on the server. Server Components can render Client Components and pass them serializable props, but a Client Component cannot import a Server Component (it can receive one as children).

Data. Fetch in Server Components with await. In Next.js 15 and later, params and searchParams are Promises that you await. Caching has changed between versions: older versions cached fetch by default, and Next.js 16 with Cache Components makes dynamic rendering the default and caching opt-in with the use cache directive. Check the docs of your version rather than relying on memory.

Mutations. A Server Action is an async function marked with "use server". Pass it to a form's action prop and it runs on the server with the FormData. After changing data, call revalidatePath or revalidateTag, or redirect. Treat actions as public endpoints: validate input and check authorization inside every action.

Navigation uses Link (with prefetching) and the useRouter hook in Client Components.

The example shows a Server Component page. It runs here as a plain async function, so it demonstrates the data flow, not Next.js itself.

jsx
// app/courses/[id]/page.jsx in a Next.js project: a Server Component (no "use client").
async function getCourse(id) {
  await new Promise((resolve) => setTimeout(resolve, 10));
  return { id, title: 'React Basics', lessons: ['JSX', 'Props', 'State'] };
}

export async function CoursePage({ params }) {
  const { id } = await params;
  const course = await getCourse(id);

  return (
    <article>
      <h1>{course.title}</h1>
      <ul>
        {course.lessons.map((lesson) => (
          <li key={lesson}>{lesson}</li>
        ))}
      </ul>
    </article>
  );
}

// Stand-in for the framework, which passes route params as a Promise.
export default async function Demo() {
  return CoursePage({ params: Promise.resolve({ id: 'react-basics' }) });
}

This is only a plain async function rendered to static HTML. It was not run inside Next.js, so routing, caching and streaming are not tested here. Rendered result: <article><h1>React Basics</h1><ul><li>JSX</li><li>Props</li><li>State</li></ul></article>

Key points

  • Folders are routes. page, layout, loading, error and not-found files define behaviour.
  • Components are Server Components by default. Add "use client" at a boundary for state, effects and browser APIs.
  • Server Components can be async and fetch directly. params is a Promise in current versions.
  • Server Actions handle mutations and must validate input and check authorization.
  • Caching differs between Next.js versions. Check the documentation for yours.

Common mistakes

  • Adding "use client" at the top of every file and losing the benefits of Server Components.
  • Importing a server-only module (database client) into a Client Component.
  • Forgetting to await params in current Next.js versions.
  • Trusting Server Action inputs without validation and authorization.
  • Assuming the caching rules of one Next.js version apply to another.

Follow-ups

  • What can you pass from a Server Component to a Client Component?
  • What does a layout do that a template does not?
  • How would you revalidate a list after a Server Action?

Tips

  • Say it is framework-specific. It shows you know where React ends.
  • Explain the client boundary rule with one example.
  • Mention that caching changed across versions and that you check the docs.
82.react-0082Mediummid

What is a request waterfall in React, why is it a problem, and how do you fetch data in parallel and avoid fetch-on-render?

A waterfall happens when requests run one after another because each starts only after the previous finished or after a component mounted. Total time is the sum of all waits. Fix it by starting independent requests together (Promise.all or hoisting), fetching before render (route loaders, Server Components, prefetching) and using Suspense with use() so rendering does not decide when fetching starts. Fetch-on-render in nested components is the usual cause.

Full answer

Fetch-on-render is the common beginner pattern: a component mounts, an effect starts a fetch, and the data arrives later. If a child component also fetches, it only mounts after its parent has rendered real data, so its fetch starts after the parent's finished. With three levels of nesting, three round trips happen in sequence. This is a waterfall, and it makes pages slow on high latency networks.

Ways to avoid it:

  1. Parallelize independent requests. Start them together and wait for both: const [user, courses] = await Promise.all([getUser(), getCourses()]). Use Promise.allSettled when one failure should not hide the other result. Only true dependencies should be sequential.
  2. Fetch earlier. Route loaders (React Router, Next.js Server Components, TanStack Router) start fetching when navigation begins, before the component renders. This is called render-as-you-fetch.
  3. Hoist and pass promises. Start the promise in a parent or loader and pass it to children, which read it with use(promise) inside a Suspense boundary. Create the promise outside the component or cache it, or each render creates a new request.
  4. Prefetch. TanStack Query's prefetchQuery, link hover prefetching and <link rel="preload"> start requests before the user needs the data.
  5. Move the join to the server. One endpoint (or GraphQL query) returning what the page needs replaces several round trips.

Related correctness issues: handle races (see the abort pattern), show skeleton fallbacks that match the layout, and avoid fetching on the client what could be rendered on the server.

Measure with the browser network panel: a staircase of bars is a waterfall.

The example measures sequential and parallel loading with two 50 ms requests.

jsx
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const getUser = () => delay(50, { name: 'Asha' });
const getCourses = () => delay(50, ['Maths', 'Science']);

async function timed(label, load) {
  const start = performance.now();
  const [user, courses] = await load();
  const elapsed = performance.now() - start;
  console.log(label + ': ' + user.name + ' has ' + courses.length + ' courses, took at least 90 ms: ' + (elapsed >= 90));
}

await timed('sequential', async () => {
  const user = await getUser();
  const courses = await getCourses();
  return [user, courses];
});

await timed('parallel', () => Promise.all([getUser(), getCourses()]));

This ran as a script with two simulated requests of 50 ms. The sequential version needs about 100 ms and the parallel one about 50 ms. Output of the run: sequential: Asha has 2 courses, took at least 90 ms: true parallel: Asha has 2 courses, took at least 90 ms: false

Key points

  • Waterfalls make total time the sum of requests, usually from fetch-on-render in nested components.
  • Start independent requests together with Promise.all, and keep sequence only for real dependencies.
  • Fetch before render with loaders, Server Components and prefetching.
  • Pass promises to Suspense with use(), created outside render.
  • Reduce round trips with server-side joins or a combined endpoint.

Common mistakes

  • Nesting components that each fetch in an effect after the parent has data.
  • Awaiting independent requests one after another.
  • Creating the promise inside a component that uses use(), restarting it every render.
  • Using Promise.all when a single failure should not block the page.
  • Measuring only on a fast local network and missing the waterfall.

Follow-ups

  • How does Suspense with use() change fetch-on-render?
  • How do route loaders in React Router or Next.js help?
  • When is a waterfall unavoidable?

Tips

  • Define the term with the nested component example.
  • List several fixes, from simple to structural.
  • Mention measuring with the network panel.
83.react-0083Hardsenior

How do you write generic React components in TypeScript (a typed List, a table with keyof columns), and what do constraints buy you?

Declare a type parameter on the component function: function List<T>(props: ListProps<T>). TypeScript infers T from the props, so renderItem and getKey receive the right item type. Add constraints with extends (T extends { id: number }) when the component needs certain fields, and keyof T to tie a prop such as a column name to the data type. This gives compile-time checks without casts or any.

Full answer

A generic component works with many data shapes while keeping each use fully typed. A list that renders any array is the classic example.

tsx
function List<T>({ items, renderItem }: { items: T[]; renderItem: (item: T) => ReactNode }) {
  return <ul>{items.map((item, index) => <li key={index}>{renderItem(item)}</li>)}</ul>;
}

At the call site TypeScript infers T from items, so in renderItem the parameter is the actual item type. No annotation is needed, and passing the wrong callback is an error.

Constraints. T extends { id: number } tells TypeScript that the component may read id, and rejects data without it. keyof T gives the union of property names of T. A prop sortBy: keyof T accepts only real columns, and row[sortBy] is typed correctly. For columns of a specific kind, use a mapped type to filter keys by value type.

Other patterns. Default type parameters (<T = string>) help optional generics. Inference problems appear when T can be inferred from two places, so make one the source and use NoInfer<T> for the other when needed (TypeScript 5.4 and later). Generic hooks work the same way: function useToggleList<T>(initial: T[]).

Arrow function components in .tsx files need a trailing comma or an extends in the generic, <T,>(props: Props<T>) => ..., because <T> is parsed as JSX. Function declarations avoid that.

React.memo and forwardRef erase generics: the wrapped result has the type parameter replaced by unknown. Cast the result to the generic function type if needed, or avoid wrapping. With React 19, passing ref as a prop removes the forwardRef issue.

Avoid over-engineering: do not make a component generic if one concrete type is enough, and do not use generics only to avoid writing a type.

The example has a generic List and a SortedTable.

tsx
import { useState, type ReactNode } from 'react';

type ListProps<T> = {
  items: readonly T[];
  getKey: (item: T) => string | number;
  renderItem: (item: T) => ReactNode;
};

function List<T>({ items, getKey, renderItem }: ListProps<T>) {
  return (
    <ul>
      {items.map((item) => (
        <li key={getKey(item)}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

type TableProps<T extends { id: number }> = {
  rows: T[];
  columns: (keyof T)[];
  initialSort: keyof T;
};

function SortedTable<T extends { id: number }>({ rows, columns, initialSort }: TableProps<T>) {
  const [sortBy, setSortBy] = useState<keyof T>(initialSort);
  const sorted = [...rows].sort((a, b) => String(a[sortBy]).localeCompare(String(b[sortBy]), undefined, { numeric: true }));

  return (
    <table>
      <thead>
        <tr>
          {columns.map((column) => (
            <th key={String(column)}>
              <button onClick={() => setSortBy(column)}>{String(column)}</button>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sorted.map((row) => (
          <tr key={row.id}>
            {columns.map((column) => (
              <td key={String(column)}>{String(row[column])}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

type Course = { id: number; title: string; hours: number };
const courses: Course[] = [
  { id: 1, title: 'Science', hours: 12 },
  { id: 2, title: 'Maths', hours: 9 },
];

export default function App() {
  return (
    <div>
      <List items={courses} getKey={(course) => course.id} renderItem={(course) => course.title.toUpperCase()} />
      <SortedTable rows={courses} columns={['title', 'hours']} initialSort="title" />
    </div>
  );
}

The file passed the TypeScript compiler in strict mode. Passing a column such as "price" to SortedTable, or rows without an id, is a compile error. The check pressed each header button in turn, so the table ends sorted by hours. Rendered result: <div><ul><li>SCIENCE</li><li>MATHS</li></ul><table><thead><tr><th><button>title</button></th><th><button>hours</button></th></tr></thead><tbody><tr><td>Maths</td><td>9</td></tr><tr><td>Science</td><td>12</td></tr></tbody></table></div>

Key points

  • Put a type parameter on the component function and let TypeScript infer it from props.
  • Use extends constraints for required fields and keyof T for column-like props.
  • Arrow functions in tsx need <T,> or an extends. Function declarations avoid the issue.
  • memo and forwardRef lose generics, so cast or avoid them. React 19 ref props help.
  • Do not add generics when one concrete type is enough.

Common mistakes

  • Using any or type assertions instead of a type parameter.
  • Forgetting the extends constraint and then reading a field that may not exist.
  • Writing generic arrow functions in tsx without the comma and getting a JSX parse error.
  • Wrapping a generic component in memo and losing its type parameter.
  • Making components generic when a single concrete type would do.

Follow-ups

  • How does NoInfer help when inference picks the wrong source?
  • How would you restrict columns to keys whose values are numbers?
  • Why do memo and forwardRef break generic components?

Tips

  • Explain inference at the call site. It is the value of generics.
  • Show one constraint with extends and one with keyof.
  • Mention the arrow function gotcha in tsx. It is practical.
84.react-0084Hardsenior

How do you build a type-safe polymorphic component with an "as" prop in TypeScript, and what are its limits?

Make the component generic over the element type: T extends ElementType = 'span', accept as?: T, and combine the component's own props with Omit<ComponentPropsWithoutRef<T>, keyof OwnProps>. Then as="a" accepts href, as="button" accepts onClick and type, and a mismatch such as href on a span is a compile error. Limits are heavy types, slower editor feedback and awkward ref typing, so some design systems prefer asChild composition.

Full answer

Design system components such as Text, Box or Button often need to render different elements: a button that is really a link, or a heading with the style of a paragraph. A polymorphic as prop does this. Plain JavaScript is easy. Type safety is the hard part.

The type has three pieces. T extends ElementType = 'span' is a type parameter naming the element or component to render (ElementType covers tag names and components). The component's own props, such as tone and children, are declared in OwnProps<T> along with as?: T. The rest of the props come from the target element: Omit<ComponentPropsWithoutRef<T>, keyof OwnProps<T>>. Omitting the own keys prevents conflicts, where for example your tone collides with a native attribute.

When TypeScript sees <Text as="a" href="/courses">, it infers T as "a" and allows anchor attributes. With as="span", href is rejected, and a misspelled attribute is rejected too. This was checked with the compiler for the example below.

Implementation detail: inside the component, assign const Component: ElementType = as ?? 'span'. Widening to ElementType avoids a type explosion in the JSX expression, at the cost of one internal loose type that the public signature protects.

Refs: in React 19, ref is a prop, so use ComponentPropsWithRef<T> if you need it. With forwardRef, generics need a cast, which is why older polymorphic types were awkward.

Limits. The types are long and can slow the editor. Error messages are hard to read. Component targets with required props need care. Many teams prefer composition with an asChild prop (Radix UI Slot): the component clones its single child and merges props, which is easier to type and covers links in routers. Choose by team preference and keep the surface small.

Accessibility also matters: changing the element changes semantics. A div with an onClick is not a button, so document which elements are allowed.

tsx
import type { ComponentPropsWithoutRef, ElementType, ReactNode } from 'react';

type TextOwnProps<T extends ElementType> = {
  as?: T;
  tone?: 'plain' | 'muted';
  children: ReactNode;
};

type TextProps<T extends ElementType> = TextOwnProps<T> & Omit<ComponentPropsWithoutRef<T>, keyof TextOwnProps<T>>;

function Text<T extends ElementType = 'span'>({ as, tone = 'plain', children, ...rest }: TextProps<T>) {
  const Component: ElementType = as ?? 'span';
  return (
    <Component data-tone={tone} {...rest}>
      {children}
    </Component>
  );
}

export default function App() {
  return (
    <div>
      <Text>Plain span</Text>
      <Text as="a" href="/courses" tone="muted">
        Courses
      </Text>
      <Text as="button" type="button" onClick={() => console.log('pressed')}>
        Press
      </Text>
    </div>
  );
}

The file passed the strict TypeScript check. In a separate check, <Text as="span" href="/x"> and a misspelled attribute on an anchor were both rejected by the compiler, as the answer says. Rendered result: <div><span data-tone="plain">Plain span</span><a data-tone="muted" href="/courses">Courses</a><button data-tone="plain" type="button">Press</button></div>

Key points

  • Make the component generic over T extends ElementType with a default element.
  • Combine own props with Omit<ComponentPropsWithoutRef<T>, keyof OwnProps>.
  • TypeScript then checks element-specific props from the as value.
  • Widen to ElementType inside the implementation, and keep the public type strict.
  • Consider asChild composition when polymorphic types become too heavy, and keep semantics accessible.

Common mistakes

  • Typing the rest props as any, which removes all checking.
  • Forgetting to omit the own prop keys, so the types conflict.
  • Allowing as="div" for a clickable control and losing keyboard and screen reader behaviour.
  • Making the type so complex that the editor becomes slow.
  • Ignoring ref typing and breaking forwarded refs.

Follow-ups

  • How does the asChild pattern in Radix UI differ from an as prop?
  • How do you type the ref for a polymorphic component in React 19?
  • How would you restrict as to a small set of elements?

Tips

  • Show the three-part type. It is the whole answer.
  • Mention accessibility. Elements carry semantics.
  • Offer asChild as the alternative and compare them briefly.
85.react-0085Hardsenior

Explain React's Fiber architecture and scheduler. How can React pause, resume and discard renders, and what do lanes and priorities do?

Fiber is React's data structure and work loop: each element becomes a fiber node, and rendering is done as small units of work that can be paused between units. Updates get a lane (priority). Urgent lanes, such as typing and clicks, are rendered first. Non-urgent ones, such as transitions and deferred values, render in the background through the scheduler and are restarted or dropped when newer urgent work arrives. Only the commit phase must be synchronous.

Full answer

Before Fiber (React 15), rendering was a recursive stack walk that could not be interrupted. A large update blocked the main thread until it finished. Fiber, introduced in React 16, replaced the recursion with a linked data structure and a loop, so work can stop and continue.

A fiber is a plain object for one unit of work: it holds the component type, props, state, a pointer to its parent, child and sibling, and the pending work. React keeps two trees. The current tree is what is on screen. The work-in-progress tree is built during render. When rendering finishes, the commit phase swaps them by changing one pointer.

The work loop processes one fiber at a time: beginWork calls your component and decides on children, completeWork builds DOM nodes and collects effects on the way back up. In concurrent mode the loop checks shouldYield between fibers. If the time slice (about 5 ms) is used up, it hands control back to the browser through the scheduler (a message channel based task queue), so input and painting can happen, and resumes later.

Priorities are expressed as lanes, bits in a bitmask. Discrete events (click, key press) get the highest lane (SyncLane), continuous events (scroll, pointer move) get a lower one, transitions and deferred values get transition lanes, and offscreen work gets the lowest. When a higher lane is scheduled during a lower lane render, React abandons the work-in-progress tree and starts again with the urgent lane. Starved lower lanes eventually expire and are rendered anyway.

Consequences for code. Render functions must be pure, because they may run more than once or be thrown away, and StrictMode double calls them to expose impurities. Side effects belong in effects, which run only after commit. The render phase can be interrupted, the commit phase cannot.

useDeferredValue(value) shows the idea in practice: the urgent render updates the input with the new value at once, while a background render tries to update the deferred value. If the user types again before it finishes, the older background render is discarded and only the latest value is rendered. The example proves this with logging.

Fiber does not make code faster. It makes work interruptible and prioritized, so the interface stays responsive.

jsx
import { memo, useDeferredValue, useState } from 'react';

const COURSES = Array.from({ length: 300 }, (_, i) => 'React lesson ' + (i + 1));

const Results = memo(function Results({ query }) {
  console.log('rendering results for "' + query + '"');
  const matches = COURSES.filter((c) => c.toLowerCase().includes(query.toLowerCase()));
  return <p>{matches.length} matches</p>;
});

export default function Search() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);

  return (
    <div>
      <input aria-label="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
      <Results query={deferredQuery} />
    </div>
  );
}

The check changed the input to "r", "re" and "rea" in quick succession inside one batch of work. The input updated each time, but the background render of Results ran only for the latest value. Output of the run: rendering results for "" rendering results for "rea" input value at the end: rea

Key points

  • A fiber is a unit of work. React keeps a current tree and a work-in-progress tree, swapped at commit.
  • Concurrent rendering yields between fibers (about 5 ms slices) so the browser can handle input.
  • Lanes give updates priorities. Urgent updates interrupt and restart lower-priority renders.
  • Render must be pure because it can be paused, repeated or discarded. Commit is synchronous.
  • useDeferredValue and transitions use low-priority lanes, so intermediate values may never render.

Common mistakes

  • Saying Fiber makes React faster instead of interruptible.
  • Writing impure render functions and then being surprised by double renders.
  • Putting side effects in the render phase.
  • Believing the commit phase can be paused.
  • Expecting useDeferredValue to delay or debounce by a fixed time.

Follow-ups

  • Why does StrictMode render components twice in development?
  • What is the difference between a transition and a debounce?
  • What happens to a Suspense fallback when a transition is in progress?

Tips

  • Draw the two trees and the pointer swap. It shows you understand the model.
  • Separate render phase (pausable) and commit phase (not).
  • Give useDeferredValue as the practical example.
86.react-0086Hardsenior

How does streaming server rendering with Suspense work in React 19, and how does it improve time to first byte and perceived speed?

With renderToPipeableStream (Node) or renderToReadableStream (web streams), React sends the HTML for the shell immediately, with Suspense fallbacks in place of slow parts. When the data for a boundary resolves, React streams the finished HTML plus a tiny inline script that swaps it into place. Users see content sooner, slow data does not block fast parts, and each boundary can hydrate independently.

Full answer

Classic server rendering (renderToString) is all or nothing. The server waits for all data, sends one big HTML document, and the client must download all JavaScript and hydrate everything before anything is interactive.

Streaming SSR changes this with Suspense. Wrap slow parts in <Suspense fallback={...}>. The server renders the shell, which is everything outside suspended boundaries, and the stream starts. onShellReady fires when the shell is complete, and you pipe the stream to the response then. Each suspended boundary renders its fallback in the shell. When the awaited data resolves, React sends another chunk: a hidden element with the real HTML and an inline script ($RC) that replaces the fallback. No client JavaScript framework code is needed for the swap, so content appears even before hydration.

On the client, hydrateRoot hydrates in pieces. Boundaries hydrate independently, so a slow component does not block the rest. If the user interacts with a boundary that has not hydrated yet, React raises its priority and hydrates it first (selective hydration). Code can be split per boundary with lazy.

Details. onShellError is for failures before the shell is ready (send a 500 or a static fallback), and onError logs errors in boundaries. Errors inside a boundary make React render the client fallback so the client can retry. abort() with a timeout stops waiting for slow data and sends the fallbacks for the rest. Crawlers can be served the fully resolved document with onAllReady instead of onShellReady.

Where data comes from: in a framework such as Next.js, Server Components await data on the server and the framework wires streaming. In a custom setup, use(promise) inside a boundary suspends the render until the promise resolves, and the promise should be created outside the component or cached.

Trade-offs: layout shift if fallbacks differ in size from content, headers and status codes must be decided before streaming starts, and more moving parts than static output.

The example streams a page with one slow boundary and prints what each chunk contained.

jsx
import { Suspense, use } from 'react';
import { renderToPipeableStream } from 'react-dom/server';
import { Writable } from 'node:stream';

const reviewsPromise = new Promise((resolve) => setTimeout(() => resolve(['Clear and practical']), 30));

function Reviews() {
  const reviews = use(reviewsPromise);
  return <ul>{reviews.map((r) => <li key={r}>{r}</li>)}</ul>;
}

function Page() {
  return (
    <main>
      <h1>React Basics</h1>
      <Suspense fallback={<p>Loading reviews...</p>}>
        <Reviews />
      </Suspense>
    </main>
  );
}

const chunks = [];
const sink = new Writable({
  write(chunk, _encoding, done) {
    chunks.push(chunk.toString());
    done();
  },
});

sink.on('finish', () => {
  console.log('chunks received: ' + chunks.length);
  console.log('first chunk has the fallback: ' + chunks[0].includes('Loading reviews...'));
  console.log('first chunk has the review: ' + chunks[0].includes('Clear and practical'));
  const rest = chunks.slice(1).join('');
  console.log('later chunks have the review: ' + rest.includes('Clear and practical'));
  console.log('later chunks have the swap script: ' + rest.includes('$RC'));
});

const { pipe } = renderToPipeableStream(<Page />, {
  onShellReady() {
    pipe(sink);
  },
  onShellError(error) {
    console.log('shell failed: ' + error.message);
  },
});

This ran with renderToPipeableStream on the box, outside any framework. Output of the run: chunks received: 2 first chunk has the fallback: true first chunk has the review: false later chunks have the review: true later chunks have the swap script: true

Key points

  • The shell is sent first with fallbacks. Resolved boundaries stream later with inline swap scripts.
  • onShellReady starts the response. onAllReady waits for everything, for example for crawlers.
  • Boundaries hydrate independently and interaction raises the priority of a boundary (selective hydration).
  • Handle onShellError, onError and abort timeouts.
  • Fallback sizes should match content to limit layout shift.

Common mistakes

  • Using renderToString for pages with slow data and blocking the whole response.
  • Creating the promise inside the component, so it restarts on every render.
  • Forgetting onShellError and returning a broken response.
  • Fallbacks with a different size from the content, causing layout shift.
  • Setting headers or status codes after the stream has started.

Follow-ups

  • What is selective hydration and when does it matter?
  • When would you use onAllReady instead of onShellReady?
  • How does streaming relate to Next.js loading.js files?

Tips

  • Describe the shell and boundary chunks, not only "streaming".
  • Mention selective hydration. It is the client-side half of the story.
  • Mention the headers and status code limit.
87.react-0087Hardsenior

How do createEntityAdapter and createSelector help structure large Redux state, and why normalize data?

createEntityAdapter stores collections in a normalized shape ({ ids, entities }) and generates reducers (addOne, setAll, updateOne, removeOne) and selectors (selectAll, selectById, selectIds). Normalization gives O(1) lookups and one source of truth per item, so updates do not need to search arrays. createSelector builds memoized derived data, so components receive the same reference until the inputs change.

Full answer

Storing a list as an array makes updates and lookups require a scan, and the same item can appear in several arrays that drift apart. A normalized shape keeps each item once: entities is an object keyed by id and ids is the order. Other places reference items by id.

createEntityAdapter() encodes this shape. You may pass selectId (if the id field is not id) and sortComparer (to keep ids sorted). The adapter gives reducer helpers that work directly with Immer drafts: addOne, addMany, setAll, updateOne, upsertOne, removeOne. Use them as case reducers, or call them inside your own reducer with the state. adapter.getInitialState() creates the empty structure and can carry extra fields such as status.

adapter.getSelectors((state) => state.students) returns selectAll, selectById, selectIds, selectEntities and selectTotal, bound to the slice location.

Derived data uses createSelector (from Reselect, re-exported by RTK). It takes input selectors and a result function, and recomputes only when an input result changes by reference. Returning a new filtered array from a plain selector would make useSelector see a new value every time and re-render the component for any store change. A memoized selector returns the same array until relevant data changes. Reselect 5 memoizes with an unbounded cache per argument set by default, so parameterized selectors work, but consider the memory for many distinct arguments.

Rules. Keep selectors next to the slice. Select the smallest slice of data in components. Do not write selectors that create new objects unless they are memoized. In development RTK warns when a selector returns a different result for the same input.

Normalization has a cost: reading nested data requires joins through selectors. Normalize when entities are shared, updated individually or numerous. RTK Query is another option, and it caches per endpoint without normalization.

The example runs the store without a UI to show the state shape and memoization.

jsx
import { configureStore, createEntityAdapter, createSelector, createSlice } from '@reduxjs/toolkit';

const studentsAdapter = createEntityAdapter({
  sortComparer: (a, b) => a.name.localeCompare(b.name),
});

const studentsSlice = createSlice({
  name: 'students',
  initialState: studentsAdapter.getInitialState(),
  reducers: {
    received: studentsAdapter.setAll,
    scoreChanged(state, action) {
      studentsAdapter.updateOne(state, { id: action.payload.id, changes: { score: action.payload.score } });
    },
  },
});

const { received, scoreChanged } = studentsSlice.actions;
const store = configureStore({
  reducer: { students: studentsSlice.reducer, theme: (state = 'light') => state },
});

const { selectAll, selectById } = studentsAdapter.getSelectors((state) => state.students);
const selectPassing = createSelector([selectAll], (students) => students.filter((s) => s.score >= 50));

store.dispatch(
  received([
    { id: 2, name: 'Ravi', score: 45 },
    { id: 1, name: 'Asha', score: 82 },
    { id: 3, name: 'Meera', score: 61 },
  ])
);

console.log('ids in order: ' + JSON.stringify(store.getState().students.ids));
console.log('lookup by id 3: ' + selectById(store.getState(), 3).name);

const first = selectPassing(store.getState());
console.log('passing: ' + first.map((s) => s.name).join(', '));

store.dispatch({ type: 'theme/changed' });
console.log('same array after an unrelated change: ' + (selectPassing(store.getState()) === first));

store.dispatch(scoreChanged({ id: 2, score: 70 }));
const second = selectPassing(store.getState());
console.log('passing after update: ' + second.map((s) => s.name).join(', '));
console.log('new array after a relevant change: ' + (second !== first));

This ran as a script against a store with no UI. Output of the run: ids in order: [1,3,2] lookup by id 3: Meera passing: Asha, Meera same array after an unrelated change: true passing after update: Asha, Meera, Ravi new array after a relevant change: true

Key points

  • Normalized state stores items once in entities and keeps order in ids.
  • The adapter provides reducer helpers and selectors, and an optional sortComparer.
  • createSelector memoizes derived data, returning the same reference when inputs are unchanged.
  • Plain selectors that build new arrays or objects cause extra re-renders.
  • Normalize shared or frequently updated data. Use RTK Query when server caching is enough.

Common mistakes

  • Keeping arrays of objects and searching them on every update.
  • Writing selectors that return new arrays and not memoizing them.
  • Normalizing everything, including data that is never shared or updated.
  • Duplicating the same entity under several slices.
  • Reading nested relations in components instead of in selectors.

Follow-ups

  • When is normalization not worth it?
  • How would you build a parameterized selector like selectByCourse(courseId)?
  • How does RTK Query compare with an entity adapter for server data?

Tips

  • Explain the extra re-render problem of unmemoized selectors. It is the practical reason.
  • Say normalization has costs.
  • Mention RTK Query as the alternative for server state.
88.react-0088Hardsenior

What are micro-frontends, how would you integrate several React apps into one product, and what are the trade-offs?

Micro-frontends split a large UI into independently built and deployed pieces owned by separate teams. Integration options are build-time packages, run-time loading of remote bundles (Module Federation or native ES modules with import maps), iframes, or server-side composition. A stable contract (mount and unmount functions, props, events) keeps teams decoupled. The costs are duplicated dependencies, inconsistent UX and harder shared state, so use them only when team and deploy independence justifies it.

Full answer

Micro-frontends apply the microservice idea to the interface: a checkout team, a catalog team and an account team each own a vertical slice with its own repository, pipeline and release schedule. A shell (host) application composes them.

Integration styles:

  • Build-time: each slice is an npm package. Simple, but any change needs a rebuild and release of the host, so deployment is not independent.
  • Run-time with Module Federation or native ES modules: the host loads remote bundles by URL when needed, and can share libraries such as React as singletons so only one copy runs. Teams deploy independently.
  • iframes: strong isolation of styles, scripts and failures, at the cost of routing, sizing, accessibility and performance difficulty.
  • Server-side composition: edge or origin stitches HTML fragments, often with web components or streaming.

Contract design is the important part. A framework-agnostic contract means each remote exports mount(element, props) and returns an unmount function. The host does not care how the remote renders, and can mix React versions in the extreme case. Communication goes through props, custom DOM events or a small event bus, not shared global state. Shared concerns such as authentication, routing base paths, design tokens and analytics are provided by the shell and a shared design system.

Pitfalls: loading two React copies breaks hooks and context across the boundary (share React as a singleton, or keep remotes isolated), CSS leaks (use CSS modules, scoped naming or Shadow DOM), bundle bloat from duplicated libraries, version skew between the shell and remotes, and a worse developer experience on a shared page. Error isolation matters: wrap each remote in an error boundary and a loading fallback.

When not to use them: small teams, one product with a shared release cycle. A well-structured monorepo with feature folders gives most benefits at lower cost.

The example uses two remotes with the mount contract and an error-isolated host. The remotes are in-file stand-ins for bundles that would be loaded by URL.

jsx
import { createRoot } from 'react-dom/client';

// Each remote exposes a framework-agnostic contract: mount(element, props) returns unmount().
const remotes = {
  catalog: async () => ({
    mount(element, props) {
      const root = createRoot(element);
      root.render(<h2>Catalog for {props.user}</h2>);
      return () => root.unmount();
    },
  }),
  checkout: async () => ({
    mount(element) {
      const root = createRoot(element);
      root.render(<button onClick={() => element.dispatchEvent(new window.CustomEvent('checkout:done', { bubbles: true }))}>Pay</button>);
      return () => root.unmount();
    },
  }),
  broken: async () => {
    throw new Error('remote failed to load');
  },
};

async function mountRemote(name, element, props) {
  try {
    const remote = await remotes[name]();
    return remote.mount(element, props);
  } catch (error) {
    element.textContent = 'This section is unavailable: ' + error.message;
    return () => {};
  }
}

const host = document.getElementById('root');
const slots = ['catalog', 'checkout', 'broken'].map((name) => {
  const slot = document.createElement('section');
  slot.dataset.remote = name;
  host.appendChild(slot);
  return { name, slot };
});

host.addEventListener('checkout:done', () => console.log('host received checkout:done'));

const unmounts = await Promise.all(slots.map(({ name, slot }) => mountRemote(name, slot, { user: 'Asha' })));
await new Promise((resolve) => setTimeout(resolve, 30));
console.log(host.innerHTML);
host.querySelector('button').click();
unmounts.forEach((unmount) => unmount());

This ran as a script. The remotes are local stand-ins for bundles that a real host would import by URL. The third one fails on purpose to show that a broken remote does not break the host. Output of the run: <section data-remote="catalog"><h2>Catalog for Asha</h2></section><section data-remote="checkout"><button>Pay</button></section><section data-remote="broken">This section is unavailable: remote failed to load</section> host received checkout:done

Key points

  • Micro-frontends give team and deployment independence at the cost of complexity.
  • Integration options are packages, run-time federation or ES modules, iframes and server composition.
  • A mount and unmount contract plus events keeps remotes decoupled.
  • Share React as a singleton or isolate remotes. Control CSS leakage and version skew.
  • A monorepo with feature folders is often enough.

Common mistakes

  • Loading two copies of React and breaking hooks across the boundary.
  • Sharing mutable global state between remotes instead of an event contract.
  • No error boundary or fallback around remotes.
  • Choosing micro-frontends for a small team that could use one codebase.
  • Letting remotes leak CSS into each other.

Follow-ups

  • How does Module Federation share React as a singleton?
  • How would you share authentication and routing between remotes?
  • How would you test the integration between the shell and a remote?

Tips

  • Lead with the team and deployment reasons. Technology is second.
  • Describe a concrete contract. It shows real design thinking.
  • Offer the monorepo alternative to show judgment.
89.react-0089Hardsenior

How would you design error handling for a large React application, covering error boundaries, root error callbacks in React 19, async errors and monitoring?

Layer it. Put error boundaries at several levels (app, route, widget) so a failure removes only a small part of the screen and offers a retry. Use the React 19 root options onCaughtError, onUncaughtError and onRecoverableError to report to monitoring in one place. Boundaries do not catch event handler or async errors, so handle those with try/catch and state, or rethrow into render. Send errors with release, route and user context, and test the fallback paths.

Full answer

Error boundaries (class components with getDerivedStateFromError, or the react-error-boundary library) catch errors thrown while rendering, in lifecycle methods and in constructors of their children. They do not catch errors in event handlers, in async code such as promises and timers, in server rendering, or in the boundary itself.

Layering. A root boundary guards against a white screen and shows a generic page. Route-level boundaries keep the navigation working when one page fails. Widget-level boundaries isolate risky or third-party parts such as charts or embeds. Each fallback explains what happened and offers a retry, which resets the boundary (a resetKey prop, or a key change) and re-renders the children.

Reporting in React 19. createRoot and hydrateRoot accept onCaughtError (errors caught by a boundary), onUncaughtError (errors that no boundary caught) and onRecoverableError (for example hydration mismatches that React repaired). React 19 no longer logs the same error three times. These callbacks are the single place to send errors and the component stack to Sentry or a similar service. The boundary's own componentDidCatch remains useful for local actions.

Async and event errors. In handlers use try/catch, set an error state and show an inline message. To let a boundary handle an async failure, store the error in state and throw it during render, if (error) throw error, or use a data library whose throwOnError option does that. Suspense plus use surfaces rejected promises to the nearest boundary.

Operational practice: attach release version, route, user id (as policy allows) and feature flags to reports, deduplicate noisy errors, set alerts on error rate per release, and upload source maps. Test failure paths: a component test that makes a child throw, and an end-to-end test that simulates API failure. Avoid swallowing errors silently.

The example shows a boundary with a reset, and the root callbacks capturing the error.

jsx
import { Component, useState } from 'react';
import { createRoot } from 'react-dom/client';

class Boundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  render() {
    if (this.state.error) {
      return (
        <div role="alert">
          <p>Something went wrong: {this.state.error.message}</p>
          <button onClick={() => this.setState({ error: null })}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

function Chart({ data }) {
  if (!data) throw new Error('No chart data');
  return <p>Chart with {data.length} points</p>;
}

function Page() {
  const [data, setData] = useState(null);
  return (
    <main>
      <h1>Dashboard</h1>
      <Boundary>
        <Chart data={data} />
      </Boundary>
      <button onClick={() => setData([1, 2, 3])}>Load data</button>
    </main>
  );
}

const reports = [];
const container = document.getElementById('root');
const root = createRoot(container, {
  onCaughtError(error, info) {
    reports.push('caught by a boundary: ' + error.message + ' (component stack present: ' + Boolean(info.componentStack) + ')');
  },
  onUncaughtError(error) {
    reports.push('uncaught: ' + error.message);
  },
});

root.render(<Page />);
await new Promise((resolve) => setTimeout(resolve, 30));
console.log('after first render: ' + container.querySelector('[role=alert] p').textContent);

[...container.querySelectorAll('button')].find((b) => b.textContent === 'Load data').click();
await new Promise((resolve) => setTimeout(resolve, 30));
[...container.querySelectorAll('button')].find((b) => b.textContent === 'Try again').click();
await new Promise((resolve) => setTimeout(resolve, 30));
console.log('after loading data and retrying: ' + container.querySelector('p').textContent);
console.log('reports: ' + JSON.stringify(reports));
root.unmount();

This ran as a script. The Chart throws until data exists, the boundary shows the fallback, and Load data followed by Try again recovers. The root callback recorded the error once. Output of the run: after first render: Something went wrong: No chart data after loading data and retrying: Chart with 3 points reports: ["caught by a boundary: No chart data (component stack present: true)"]

Key points

  • Layer boundaries at app, route and widget level, each with a retry.
  • Boundaries miss event handlers, async code and server rendering errors.
  • React 19 root options onCaughtError, onUncaughtError and onRecoverableError centralize reporting.
  • Rethrow async errors in render or use a library option so a boundary can handle them.
  • Include release, route and context in reports and test failure paths.

Common mistakes

  • Expecting error boundaries to catch errors in event handlers or promises.
  • One boundary at the root only, so any widget failure blanks the app.
  • A retry button that re-renders without fixing the cause and loops.
  • Logging errors without release or route context.
  • Swallowing errors in catch blocks without reporting.

Follow-ups

  • How do you reset a boundary when the route changes?
  • How would you let a boundary catch a failed fetch?
  • Which errors would you report and which would you ignore?

Tips

  • Mention what boundaries do not catch. It is the usual follow-up.
  • Know the React 19 root callbacks. They are a recent change.
  • Describe operational practice, not only the component.
90.react-0090Hardsenior

How would you diagnose and fix a React page with poor Interaction to Next Paint (INP)?

Measure first: use field data (web-vitals, CrUX) and the Performance panel to find which interactions are slow and whether the delay is input delay, processing time or presentation. Use the React Profiler to find expensive renders and the flame chart to find long tasks. Then fix the cause: avoid unnecessary renders, move heavy work out of the handler, mark non-urgent updates as transitions, split long tasks by yielding to the main thread, and reduce DOM size or list length.

Full answer

INP measures the delay between a user interaction (click, tap, key) and the next frame painting, and is reported at roughly the worst interaction on a page visit. A good value is 200 ms or less. It is a field metric, so start with real-user data to find the pages and interactions that are bad.

Reproduce in the browser Performance panel with CPU throttling, because developer machines hide the problem. Find the interaction, and look at three parts: input delay (the main thread was busy before the event), processing time (your handlers and React's render and commit), and presentation delay (style, layout and paint). A long yellow bar of scripting under the interaction points to JavaScript. Layout and paint cost points to DOM size or expensive CSS.

React-specific tools: the React DevTools Profiler shows which components rendered, why (props, state, context, parent) and how long each took. Look for components that render on every keystroke without needing to, very large lists, expensive calculations in render and context values that change too often.

Fixes, in order of impact:

  1. Do less. Colocate state so a keystroke re-renders a small subtree. Memoize expensive children with memo when props are stable (or rely on React Compiler). Derive values instead of storing them. Virtualize long lists.
  2. Defer. Wrap non-urgent updates in startTransition or use useDeferredValue so typing stays responsive while heavy results render in the background.
  3. Split long tasks. Break large synchronous work into chunks and yield to the main thread between them with scheduler.yield() (with a setTimeout fallback), so the browser can handle input and paint. Move CPU-heavy work to a Web Worker.
  4. Reduce what ships: lazy-load rarely used code so parsing and hydration cost less.
  5. Make the first feedback immediate, for example a pressed state, and then do the work.

Verify with the same trace and track the metric after release. The example proves the yielding idea with an event that is waiting while heavy work runs.

jsx
const yieldToMain = () =>
  globalThis.scheduler && typeof globalThis.scheduler.yield === 'function'
    ? globalThis.scheduler.yield()
    : new Promise((resolve) => setTimeout(resolve, 0));

function heavyStep(n) {
  let total = 0;
  for (let i = 0; i < 200000; i++) total += Math.sqrt(i + n);
  return total;
}

async function blockingRun(steps) {
  for (let i = 0; i < steps; i++) heavyStep(i);
  console.log('blocking run finished');
}

async function chunkedRun(steps) {
  for (let i = 0; i < steps; i++) {
    heavyStep(i);
    if (i % 5 === 4) await yieldToMain();
  }
  console.log('chunked run finished');
}

// A queued user event stands in for a click that arrives while work is running.
setTimeout(() => console.log('click handled during the blocking run'), 0);
await blockingRun(40);
await yieldToMain();

setTimeout(() => console.log('click handled during the chunked run'), 0);
await chunkedRun(40);

This ran as a script. A timer represents the user's click. In the blocking run it waits until all work ends, and in the chunked run it is handled after the first chunk, before the rest of the work. Output of the run: blocking run finished click handled during the blocking run click handled during the chunked run chunked run finished

Key points

  • INP is a field metric. Find slow interactions with real-user data, then reproduce with throttling.
  • Break the delay into input delay, processing time and presentation delay.
  • Use the React Profiler to find unnecessary or expensive renders.
  • Fix by doing less, deferring with transitions, splitting long tasks, and using workers.
  • Verify with a trace and monitor after release.

Common mistakes

  • Optimizing from guesses instead of a trace.
  • Testing only on a fast development machine without throttling.
  • Memoizing everything without measuring.
  • Doing heavy work inside the event handler before any visual feedback.
  • Ignoring DOM size and long lists as causes.

Follow-ups

  • What is the difference between INP and First Input Delay?
  • How would you move a heavy calculation into a Web Worker?
  • How does the React Compiler change your approach to memoization?

Tips

  • Start with measurement. It is what separates seniors from guessers.
  • Name the three parts of an interaction delay.
  • List fixes in order of cost and impact.
91.react-0091Hardsenior

How would you test components that fetch data (loading, success, error and retry), and how do you organize a test suite for a large React codebase?

Mock at the network boundary (Mock Service Worker, or a stubbed fetch in small tests), render the component, and assert on what the user sees: a loading indicator, then the data found with findBy queries, and a role="alert" message on failure with a working retry. Avoid mocking your own hooks. For the suite, keep many fast component and unit tests, fewer integration tests of whole pages, and a small number of end-to-end tests, and make failures deterministic by controlling time and network.

Full answer

Data components have four states worth testing: loading, success, error and empty. Tests should reproduce them with a controlled network, not by mocking the component's internals. If the test replaces your own useCourses hook, it proves nothing about the hook.

Network mocking. Mock Service Worker (MSW) intercepts requests at the network layer, so the real fetch code, query library and error handling run. In small tests, stubbing fetch with vi.stubGlobal or vi.fn also works, as in the example. For each test, set the response (a list, an empty list, a 500 status, a rejected promise), render, and assert.

Query rules. After render, the first state is loading: assert with getByText or a role. Data appears later: use await screen.findByRole(...) or findByText, which retry until the timeout. Failure: check for role="alert". Retry: click the button with user-event and assert the next fetch result appears. Use queryBy to assert absence.

Wrapper and isolation. Create a renderWithProviders helper that adds router, store or QueryClient providers. Create a fresh QueryClient or store for each test, with retries turned off, so tests do not share a cache and do not wait for default retry delays. Reset mocks in afterEach.

Determinism. Avoid real timers and real network. Use fake timers for debounce or polling. Do not assert on implementation details such as how many renders happened. Flaky tests usually come from shared state, missing awaits or real time.

Suite strategy. The testing pyramid, adapted: many small unit tests (pure functions, reducers, hooks with renderHook), a good number of component tests with RTL, selected integration tests at page level with mocked network, and a handful of Playwright tests for critical flows (login, checkout) against a real browser. Add accessibility checks (see the axe item), type checks and linting in CI. Keep tests close to the code, name them as behaviours, and treat a flaky test as a bug to fix or delete.

Coverage numbers are a signal, not a goal. Review which behaviours are untested.

The example stubs fetch and covers success, a failing request and retry.

jsx
import { useEffect, useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/vitest';

function CourseList() {
  const [attempt, setAttempt] = useState(0);
  const [state, setState] = useState({ status: 'loading', courses: [], message: '' });

  useEffect(() => {
    let ignore = false;
    setState({ status: 'loading', courses: [], message: '' });
    fetch('/api/courses')
      .then((response) => {
        if (!response.ok) throw new Error('Request failed with status ' + response.status);
        return response.json();
      })
      .then((courses) => {
        if (!ignore) setState({ status: 'ready', courses, message: '' });
      })
      .catch((error) => {
        if (!ignore) setState({ status: 'error', courses: [], message: error.message });
      });
    return () => {
      ignore = true;
    };
  }, [attempt]);

  if (state.status === 'loading') return <p>Loading courses...</p>;
  if (state.status === 'error') {
    return (
      <div role="alert">
        <p>{state.message}</p>
        <button onClick={() => setAttempt((n) => n + 1)}>Retry</button>
      </div>
    );
  }
  if (state.courses.length === 0) return <p>No courses yet</p>;
  return (
    <ul>
      {state.courses.map((course) => (
        <li key={course}>{course}</li>
      ))}
    </ul>
  );
}

const jsonResponse = (body, status = 200) => Promise.resolve({ ok: status < 400, status, json: async () => body });

afterEach(() => {
  cleanup();
  vi.unstubAllGlobals();
});

describe('CourseList', () => {
  it('shows a loading message and then the courses', async () => {
    vi.stubGlobal('fetch', vi.fn(() => jsonResponse(['Maths', 'Science'])));
    render(<CourseList />);
    expect(screen.getByText('Loading courses...')).toBeInTheDocument();
    expect(await screen.findByText('Maths')).toBeInTheDocument();
    expect(screen.queryByText('Loading courses...')).not.toBeInTheDocument();
  });

  it('shows an empty state', async () => {
    vi.stubGlobal('fetch', vi.fn(() => jsonResponse([])));
    render(<CourseList />);
    expect(await screen.findByText('No courses yet')).toBeInTheDocument();
  });

  it('shows an error and recovers after retry', async () => {
    const user = userEvent.setup();
    const fetchMock = vi
      .fn()
      .mockImplementationOnce(() => jsonResponse({}, 500))
      .mockImplementationOnce(() => jsonResponse(['Maths']));
    vi.stubGlobal('fetch', fetchMock);
    render(<CourseList />);
    expect(await screen.findByRole('alert')).toHaveTextContent('Request failed with status 500');
    await user.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText('Maths')).toBeInTheDocument();
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });
});

The component and tests are in one file only to keep the example complete. A real project would use Mock Service Worker and separate files. The file ran under Vitest with jsdom, and these tests passed on two consecutive runs: CourseList > shows a loading message and then the courses CourseList > shows an empty state CourseList > shows an error and recovers after retry

Key points

  • Test loading, success, error, retry and empty states from the user's point of view.
  • Mock at the network boundary (MSW or a fetch stub), not your own hooks.
  • Use findBy queries for async content and role="alert" for errors. Use queryBy for absence.
  • Fresh providers, store or QueryClient per test, with retries off, and reset mocks after each test.
  • Balance unit, component, integration and end-to-end tests. Fix flaky tests.

Common mistakes

  • Mocking the component's own hook, which tests nothing real.
  • Using getBy for content that appears later, instead of findBy.
  • Sharing a QueryClient or store between tests, so state leaks.
  • Leaving default retries on and making failure tests slow.
  • Asserting on implementation details such as render counts.

Follow-ups

  • How does Mock Service Worker differ from stubbing fetch?
  • How would you test a debounced search with fake timers?
  • Which flows belong in end-to-end tests and why?

Tips

  • List the four states first. It shows a systematic approach.
  • Explain why mocking your own hooks is a smell.
  • Mention flaky tests and how you remove their causes.
92.react-0092Hardsenior

How do you build accessibility checks into a React workflow with axe-core, linting and manual testing, and what can automation not catch?

Combine layers: eslint-plugin-jsx-a11y while coding, axe-core in component tests (for example through jest-axe or vitest-axe) and in end-to-end runs, and manual checks with keyboard and a screen reader. Automation finds mechanical issues such as missing labels, missing alt text, duplicate ids and bad ARIA, but only part of all problems. It cannot judge whether alt text is meaningful, focus order makes sense, or a flow is usable, so manual testing remains required.

Full answer

Accessibility problems are cheapest to fix while code is written, so checks run at several points.

  1. Linting. eslint-plugin-jsx-a11y flags problems in JSX as you type: images without alt, clickable divs, invalid ARIA attributes and missing labels.
  2. Component tests. axe-core analyses a DOM and returns violations with rule ids, impact and the failing nodes. Wrappers such as jest-axe and vitest-axe provide toHaveNoViolations. Render the component in each important state (error messages shown, dialog open, menu expanded), because many problems appear only in states.
  3. End-to-end tests. Run axe on real pages in Playwright or Cypress, with real CSS, so rules that need layout and colors work. In jsdom, color contrast cannot be evaluated, so that rule is turned off in component tests.
  4. Manual testing. Use only the keyboard: can you reach and operate everything, is the focus visible, is the order logical, can you leave modals? Then test with a screen reader (VoiceOver, NVDA) on key flows. Check zoom to 200 percent and reduced motion.
  5. Process. Add a design system with accessible primitives, a checklist in pull request templates, CI that fails on new violations (with a reviewed baseline for old ones), and ownership for fixing.

What automation misses: whether labels and alt text are accurate, whether the heading structure tells the story, focus management after route changes, correct announcements, cognitive load, and custom widgets that behave wrongly despite valid markup. Automated tools find a minority of the possible issues, so passing axe is not proof of conformance to WCAG.

Interview framing: say you treat axe as a regression net, not a certificate.

The example audits a bad form and a fixed one with axe-core directly.

jsx
import axe from 'axe-core';
import { createRoot } from 'react-dom/client';

function BadForm() {
  return (
    <form>
      <input />
      <img src="/logo.png" />
      <button></button>
    </form>
  );
}

function GoodForm() {
  return (
    <form>
      <label>
        Email <input type="email" />
      </label>
      <img src="/logo.png" alt="Schoolabe logo" />
      <button type="submit">Subscribe</button>
    </form>
  );
}

async function audit(name, element) {
  const container = document.createElement('div');
  document.body.appendChild(container);
  const root = createRoot(container);
  root.render(element);
  await new Promise((resolve) => setTimeout(resolve, 30));
  const results = await axe.run(container, { rules: { 'color-contrast': { enabled: false } } });
  const ids = results.violations.map((v) => v.id).sort();
  console.log(name + ': ' + (ids.length ? ids.join(', ') : 'no violations'));
  root.unmount();
}

await audit('bad form', <BadForm />);
await audit('good form', <GoodForm />);

This ran axe-core 4 in a script on the box, with color contrast turned off because jsdom cannot compute it. Output of the run: bad form: button-name, image-alt, label good form: no violations

Key points

  • Layer checks: lint rules, axe in component and end-to-end tests, and manual keyboard and screen reader testing.
  • Test components in their important states, not only the default one.
  • Color contrast needs a real browser. jsdom cannot evaluate it.
  • Automation finds only part of the issues and cannot judge meaning or flow.
  • Use CI gates with a baseline, and accessible design system primitives.

Common mistakes

  • Treating a clean axe report as proof of accessibility.
  • Testing only the default state of components.
  • Relying on color contrast checks in jsdom.
  • Silencing rules globally to make the build pass.
  • Never testing with a keyboard or a screen reader.

Follow-ups

  • How would you add axe to a Playwright test suite?
  • How do you handle existing violations in a large codebase without blocking all work?
  • What would you check manually in a dialog component?

Tips

  • Call axe a regression net, not a certificate.
  • Name two things automation cannot check.
  • Mention testing states such as open menus and error messages.
93.react-0093Hardsenior

How do you implement authentication and protected routes in a React application, and where should tokens live?

Treat the client check as a user experience feature only, because the server enforces access. Use route loaders (or a guard component) to redirect unauthenticated users to a login page, and keep session state in a provider that is filled from the server on load. Prefer httpOnly, Secure, SameSite cookies for sessions so JavaScript cannot read the token, protect against CSRF, and never store long-lived tokens in localStorage, where any XSS can steal them.

Full answer

Two questions are separate: who is the user (authentication) and what may they do (authorization). The browser can only decide what to show. Every API call must be checked again on the server, because anyone can edit client code.

Route protection. With React Router data routers, a loader on a parent route can check the session and throw redirect('/login'). This runs before the page renders, so there is no flash of protected content. A layout route can apply it to a whole group of routes. Without a data router, a RequireAuth component renders <Navigate to="/login" replace /> when there is no user. Remember the intended destination (a from parameter or state) to return after login. For role-based access, check roles in the same place and render a "forbidden" page for a missing permission, not the login page.

Session state. On load, ask the server who the user is (GET /me). Store the result in a provider or a query cache, and show a loading state until it resolves, so a refresh does not log the user out visually. Clear the cache on logout so another user does not see old data.

Token storage. Options: httpOnly cookies set by the server are not readable by scripts, so XSS cannot steal them, but they need CSRF defenses (SameSite=Lax or Strict, CSRF tokens for risky requests). Tokens in localStorage or sessionStorage are readable by any injected script. If an access token must be in memory (for an API on another domain), keep it short-lived in a variable, refresh through an httpOnly refresh cookie, and rotate refresh tokens. Never put secrets in the bundle.

Other points: use an established identity provider (OIDC with PKCE) rather than rolling your own, handle 401 responses globally by clearing the session and redirecting, protect against open redirects when using a from parameter, and apply rate limiting and multi-factor authentication on the server. In Next.js, check sessions in Server Components, route handlers and middleware or the proxy layer, and again inside each Server Action.

The example uses a memory router with a loader guard.

jsx
import { RouterProvider, createMemoryRouter, redirect, useNavigate } from 'react-router';

const session = { user: null };

function requireUser() {
  if (!session.user) throw redirect('/login');
  return session.user;
}

function Login() {
  const navigate = useNavigate();
  return (
    <main>
      <h1>Login page</h1>
      <button
        onClick={() => {
          session.user = 'Asha';
          navigate('/dashboard');
        }}
      >
        Log in
      </button>
    </main>
  );
}

function Dashboard() {
  const navigate = useNavigate();
  return (
    <main>
      <h1>Dashboard for {session.user}</h1>
      <button
        onClick={() => {
          session.user = null;
          navigate('/login');
        }}
      >
        Log out
      </button>
    </main>
  );
}

const router = createMemoryRouter(
  [
    { path: '/login', Component: Login },
    { path: '/dashboard', loader: requireUser, Component: Dashboard, HydrateFallback: () => <p>Checking session...</p> },
  ],
  { initialEntries: ['/dashboard'] }
);

export default function App() {
  return <RouterProvider router={router} />;
}

The session here is a plain object only to keep the example short. A real app asks the server and also checks on every request. The check opened /dashboard while logged out, logged in, and logged out again. Output of the run: opened /dashboard while logged out: Login page after logging in: Dashboard for Asha after logging out: Login page

Key points

  • The client guard is UX. The server must enforce authorization on every request.
  • Use route loaders or a guard component, and remember the destination for a return after login.
  • Load the session from the server and show a loading state to avoid flicker.
  • Prefer httpOnly, Secure, SameSite cookies with CSRF protection over localStorage tokens.
  • Use a proven identity provider and handle 401 responses centrally.

Common mistakes

  • Believing a client-side guard secures data.
  • Storing long-lived tokens in localStorage.
  • Redirecting from an effect after the protected page has rendered, causing a flash of content.
  • Using an unvalidated from parameter and creating an open redirect.
  • Not clearing cached data on logout.

Follow-ups

  • How do you protect state-changing requests with cookies from CSRF?
  • How would you implement role-based access in routes?
  • How would you refresh an expired access token without logging the user out?

Tips

  • Start with "the server enforces". It is the central security point.
  • Compare cookie and localStorage storage, with the XSS and CSRF trade-off.
  • Mention using an established identity provider.
94.react-0094Hardsenior

How would you design internationalization for a large React app: message catalogs, plurals, formatting, right-to-left layouts and lazy loading of languages?

Keep all text in per-locale catalogs addressed by keys, use ICU-style messages for plurals and variables, and format numbers, dates and lists with the Intl APIs instead of string concatenation. Load catalogs on demand per locale (and per route for big apps), set lang and dir on the document, and use logical CSS properties for RTL. Use a library (react-intl, i18next, Lingui or FormatJS) and a translation workflow, because plural rules and word order differ per language.

Full answer

Internationalization (i18n) prepares code for many languages, and localization (l10n) provides the translations. A global product needs both from the start, because retrofitting is expensive.

Text. Extract every user-visible string into catalogs keyed by message id, one file per locale. Never build sentences by concatenation, because word order differs. Use placeholders (Welcome, {name}) so translators can move them. Give translators context with descriptions.

Plurals. English has two forms, but other languages have more. Polish has one, few, many and other, and Arabic has six categories. Messages should carry all forms and let Intl.PluralRules pick: ICU syntax {count, plural, one {# course} few {# courses} many {# courses} other {# courses}}, with the right words per language. Never write count === 1 ? ... : ... in components.

Formatting. Use Intl.NumberFormat (numbers, currency, units), Intl.DateTimeFormat and Intl.RelativeTimeFormat (dates and "3 days ago"), Intl.ListFormat and Intl.Collator for sorting. Time zones must be explicit for dates in shared data.

Direction. For right-to-left languages such as Arabic and Hebrew, set dir="rtl" on the root together with lang. Write CSS with logical properties (margin-inline-start, padding-inline, text-align: start) so layout flips without separate styles. Mirror directional icons, but not logos or media controls that have fixed meaning.

Delivery. Do not ship all languages to everyone. Load the catalog for the active locale with dynamic import(), and for large apps split catalogs by route or feature. Show a Suspense fallback while loading, and fall back to a default locale for missing keys. Choose the locale from a URL prefix, a cookie or the Accept-Language header, and keep it in a context provider. Server rendering needs the same catalog on the server to avoid hydration mismatches.

Process. Use a translation management system, run a check in CI for missing keys and unused keys, and test with pseudo-localization (long, accented text) to find layout breakage. Avoid text in images and fixed-width buttons.

The example has a small provider with lazy catalogs and plural selection for English and Polish.

jsx
import { createContext, useContext, useEffect, useState } from 'react';

const loaders = {
  en: () => Promise.resolve({ courses: { one: '{n} course', other: '{n} courses' } }),
  pl: () => Promise.resolve({ courses: { one: '{n} kurs', few: '{n} kursy', many: '{n} kursów', other: '{n} kursu' } }),
};

const I18nContext = createContext(null);

function I18nProvider({ children }) {
  const [requested, setLocale] = useState('en');
  const [loaded, setLoaded] = useState(null);

  useEffect(() => {
    let ignore = false;
    loaders[requested]().then((messages) => {
      if (!ignore) setLoaded({ locale: requested, messages });
    });
    return () => {
      ignore = true;
    };
  }, [requested]);

  if (!loaded) return <p>Loading...</p>;

  // The locale and its catalog are stored together, so they can never get out of sync.
  const { locale, messages } = loaded;

  function plural(key, n) {
    const category = new Intl.PluralRules(locale).select(n);
    return messages[key][category].replace('{n}', new Intl.NumberFormat(locale).format(n));
  }

  return (
    <I18nContext value={{ locale, setLocale, plural }}>
      <div lang={locale}>{children}</div>
    </I18nContext>
  );
}

function CourseCounts() {
  const { locale, setLocale, plural } = useContext(I18nContext);
  return (
    <div>
      <button onClick={() => setLocale('en')}>English</button>
      <button onClick={() => setLocale('pl')}>Polski</button>
      <ul>
        {[1, 2, 5, 22].map((n) => (
          <li key={n}>{plural('courses', n)}</li>
        ))}
      </ul>
      <p>{new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(1234.5)}</p>
    </div>
  );
}

export default function App() {
  return (
    <I18nProvider>
      <CourseCounts />
    </I18nProvider>
  );
}

The check switched to English and then to Polish. The catalogs are loaded lazily through promises that stand in for dynamic imports. The Polish forms use the CLDR plural rules from Intl.PluralRules: 1 is one, 2 and 22 are few, 5 is many. The "other" form (used for fractions) is shown here only to complete the category set. Rendered result: <div lang="pl"><div><button>English</button><button>Polski</button><ul><li>1 kurs</li><li>2 kursy</li><li>5 kursów</li><li>22 kursy</li></ul><p>1234,50&nbsp;€</p></div></div>

Key points

  • Put text in per-locale catalogs with placeholders. Do not concatenate sentences.
  • Let Intl.PluralRules choose among the plural forms a language needs.
  • Format numbers, dates and lists with Intl APIs.
  • Set lang and dir, and use CSS logical properties for right-to-left languages.
  • Load catalogs lazily per locale or route, keep the server and client in sync, and automate missing-key checks.

Common mistakes

  • Concatenating translated fragments into sentences.
  • Using count === 1 for plurals and breaking languages with more forms.
  • Hard-coding date and number formats.
  • Using left and right CSS properties and breaking right-to-left layouts.
  • Shipping all locales in the main bundle.

Follow-ups

  • How do you keep server-rendered and client-rendered text identical?
  • How would you detect missing translation keys in CI?
  • How do you handle gendered or context-dependent translations?

Tips

  • Mention plural categories with a concrete language. It shows depth.
  • Use the Intl APIs. Interviewers like platform knowledge.
  • Cover delivery (lazy loading) and process (translation workflow), not only code.
95.react-0095Hardsenior

What causes hydration mismatches in server-rendered React, how do you fix them, and what is selective hydration?

Hydration attaches React to server-rendered HTML and expects the first client render to produce the same output. A mismatch happens when the client renders something different from the server HTML, typically because of time, randomness, window checks, locale or browser-only data. React reports a recoverable error and falls back to client rendering of the affected part. Fix it by making the first render deterministic, reading browser-only values after hydration (an effect or useSyncExternalStore with getServerSnapshot), or using suppressHydrationWarning for unavoidable single text differences.

Full answer

Server rendering produces HTML so users see content before JavaScript loads. hydrateRoot(container, <App />) then walks the existing DOM and attaches event handlers and state instead of creating the DOM again. For that to be safe, React expects the first client render to match the server output.

Common causes: Date.now() or new Date() in render, Math.random() or unstable ids, checks such as typeof window !== 'undefined' that change output, reading localStorage or matchMedia during render, locale or time zone differences between server and browser, browser extensions that modify the DOM, and invalid HTML nesting (a div inside a p), which the browser repairs before React sees it.

Result. In development React 19 reports the mismatch with a diff, and in all builds the error goes to onRecoverableError. React cannot trust the server HTML for that part, so it discards it and client-renders the nearest Suspense boundary or the whole root. The page still works, but you lose the benefit of server rendering and may see a flash.

Fixes:

  1. Keep render pure and deterministic. Pass time, locale and ids from the server as props or use useId for ids.
  2. For browser-only values, render a neutral value first and update after hydration: useEffect with state, or better useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot). During hydration React uses getServerSnapshot, so the output matches, and then it re-renders with the client value.
  3. Use suppressHydrationWarning on one element when a text difference is expected, such as a timestamp. It works one level deep and is an escape hatch.
  4. Render client-only widgets in a boundary that does not render on the server (a mounted flag, or lazy with a client-only wrapper).
  5. Validate HTML nesting.

Selective hydration is the related React 18 feature. With Suspense boundaries and streaming, React hydrates boundaries independently and in priority order. If a user clicks inside a boundary that is not hydrated yet, React records the event, raises that boundary's priority, hydrates it, and replays the event. Slow components no longer block interactivity of the rest. Combined with lazy, code for a boundary may load later.

The example simulates a server and a client with different environments, hydrates a naive component and a safe one, and counts the recoverable errors.

jsx
import { useSyncExternalStore } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';

// Stands in for "where this code is running", which differs between server and browser.
let environment = 'server';

function Naive() {
  return <p>Rendered on the {environment}</p>;
}

const subscribe = () => () => {};

function Safe() {
  const where = useSyncExternalStore(subscribe, () => environment, () => 'server');
  return <p>Rendered on the {where}</p>;
}

async function hydrateWith(label, Component) {
  const container = document.createElement('div');
  document.body.appendChild(container);

  environment = 'server';
  container.innerHTML = renderToString(<Component />);
  const serverText = container.textContent;

  environment = 'client';
  const problems = [];
  hydrateRoot(container, <Component />, {
    onRecoverableError: (error) => problems.push(error.message.split('\n')[0]),
  });
  await new Promise((resolve) => setTimeout(resolve, 30));

  console.log(label + ': server text "' + serverText + '", text after hydration "' + container.textContent + '", recoverable errors: ' + problems.length);
  if (problems.length) console.log(label + ' error: ' + problems[0]);
}

await hydrateWith('naive', Naive);
await hydrateWith('safe', Safe);

This ran as a script in the development build of React 19. The "environment" variable simulates the server and the browser producing different values. Output of the run: naive: server text "Rendered on the server", text after hydration "Rendered on the client", recoverable errors: 1 naive error: Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used: safe: server text "Rendered on the server", text after hydration "Rendered on the client", recoverable errors: 0

Key points

  • The first client render must match the server HTML. Time, randomness and window checks break it.
  • React reports a recoverable error and client-renders the affected boundary or root.
  • Use deterministic props, useId, useSyncExternalStore with getServerSnapshot, or effects for browser-only values.
  • suppressHydrationWarning is a one-level escape hatch for expected text differences.
  • Selective hydration hydrates Suspense boundaries independently and prioritizes the one the user interacts with.

Common mistakes

  • Reading Date, Math.random or window directly during render in server-rendered components.
  • Hiding the warning everywhere with suppressHydrationWarning.
  • Invalid HTML nesting such as a div inside a p.
  • Reading localStorage during the first render.
  • Ignoring recoverable errors in production monitoring.

Follow-ups

  • How does useId avoid mismatches for generated ids?
  • What happens to a Suspense boundary that mismatches during hydration?
  • How would you render a client-only widget such as a map?

Tips

  • Name three concrete causes. It shows you have debugged it.
  • Explain getServerSnapshot. It is the modern fix.
  • Describe selective hydration with the replayed click.
96.react-0096Hardsenior

What does the Activity component (React 19.2) do, and how does it differ from conditional rendering or hiding with CSS?

Activity lets you hide part of the UI without losing its state. With mode="hidden", React keeps the component state and DOM, hides the content, unmounts its effects (cleanups run) and renders it at low priority. With mode="visible" it shows again and re-creates the effects. Conditional rendering destroys state, and plain CSS hiding keeps effects running and updates at normal priority.

Full answer

Tabs, wizards and sidebars often need the inactive view to keep its state: a half-filled form, a scroll position, a loaded list. Before React 19.2 there were two options. Conditional rendering ({tab === 'notes' && <Notes />}) unmounts the component and loses state. Keeping it mounted but hidden with CSS preserves state, but its effects keep running (subscriptions, timers, fetches) and it re-renders at normal priority although nobody sees it.

<Activity mode="visible" | "hidden"> was added in React 19.2 and sits between them.

  • In hidden mode React keeps the fiber's state and DOM, but sets the content hidden (with display: none), and unmounts its effects, so subscriptions are cleaned up. Updates for hidden content are rendered at a low priority when React is idle.
  • When mode returns to visible, React shows the content and runs the effects again. State is as you left it.

Use cases: tabs and navigation where users go back and forth, preserving form input and scroll position, pre-rendering a screen the user is likely to open next (hidden Activity can render data in the background, so the switch is quick), and keeping expensive subtrees alive without paying for their effects.

Important details. Effects clean up when hidden, so code that must keep running in the background (a socket for notifications) should live outside the hidden subtree. Layout effects clean up too. DOM state that React does not control (video playback, an uncontrolled input's value in some cases) needs thought: the elements stay in the DOM but are hidden. Hidden content still occupies memory, so do not keep dozens of heavy screens alive. Server rendering renders hidden children at lower priority and without blocking visible content.

Compare with key change (reset on purpose) and with state lifted to a parent (persist data, but not DOM or scroll). Choose Activity when the whole subtree's state should survive.

The example has two tabs and logs effect setup and cleanup.

jsx
import { Activity, useEffect, useState } from 'react';

function Notes() {
  const [text, setText] = useState('');

  useEffect(() => {
    console.log('Notes effect started');
    return () => console.log('Notes effect cleaned up');
  }, []);

  return (
    <section data-tab="notes">
      <input aria-label="Notes" value={text} onChange={(e) => setText(e.target.value)} />
    </section>
  );
}

function Settings() {
  return <section data-tab="settings">Settings content</section>;
}

export default function Tabs() {
  const [tab, setTab] = useState('notes');

  return (
    <div>
      <button onClick={() => setTab('notes')}>Notes</button>
      <button onClick={() => setTab('settings')}>Settings</button>
      <Activity mode={tab === 'notes' ? 'visible' : 'hidden'}>
        <Notes />
      </Activity>
      <Activity mode={tab === 'settings' ? 'visible' : 'hidden'}>
        <Settings />
      </Activity>
    </div>
  );
}

The check typed in the Notes input, switched to Settings, and came back. The typed text is still there, and the console lines show the effect cleanup and restart. Output of the run: Notes effect started typed in the Notes tab | input value: "draft text" Notes effect cleaned up Settings tab selected (Notes hidden) | input value: "draft text" Notes effect started Notes tab selected again | input value: "draft text" hidden attribute states: notes=, settings=none Notes effect cleaned up

Key points

  • Activity hidden keeps state and DOM but cleans up effects and renders updates at low priority.
  • Conditional rendering loses state. CSS hiding keeps effects running.
  • Visible mode shows the content again and re-runs effects with the preserved state.
  • Good for tabs, wizards and pre-rendering likely next screens.
  • Do not put needed background work (sockets) inside hidden content, and do not keep too many heavy screens alive.

Common mistakes

  • Putting a socket or subscription that must stay alive inside a hidden Activity.
  • Using conditional rendering and then wondering why form input is lost.
  • Keeping many heavy screens alive and using too much memory.
  • Assuming CSS-hidden content stops running effects.
  • Using Activity where a key reset is the intended behaviour.

Follow-ups

  • How would you pre-render the next tab with Activity?
  • How does Activity relate to Suspense and transitions?
  • What happens to layout effects in a hidden Activity?

Tips

  • Compare the three options (unmount, CSS hide, Activity). The comparison is the answer.
  • Mention that effects are cleaned up while hidden.
  • Say it needs React 19.2 or later.
97.react-0097Hardsenior

How do you structure a large React codebase (feature folders, module boundaries) and decide where state lives (colocation versus lifting)?

Organize by feature, not by file type: each feature folder holds its components, hooks, API calls, tests and a small public index that other features import from. Enforce dependency direction (shared to features to app) with lint rules. Keep state as close as possible to where it is used (colocation) and lift only when siblings need it, because state that sits too high re-renders large trees and spreads coupling. Server data goes in a query cache, URL-shareable state goes in the URL, and global stores are for truly global client state.

Full answer

Folder structure. A layout by type (components/, hooks/, utils/) works for small apps but turns into a place where every change touches ten folders. At scale, group by feature (also called a vertical slice): features/courses/ contains its components, hooks, API functions, types and tests. A feature exposes a small public API through an index file, and other code imports only from that index, not from internal paths. A common layering is shared/ (design system, utilities), features/ (business logic), and app/ or pages/ (routing and composition). Dependencies point one way: shared does not import from features, and features do not import from each other's internals. Lint rules such as eslint-plugin-boundaries, import/no-restricted-paths or Nx module boundaries enforce this automatically. Fewer cross-feature imports make code easier to delete, own and split into packages.

State placement. Ask in order:

  1. Can it be derived? Compute during render, do not store it.
  2. Is it server data? Use a query cache (TanStack Query, RTK Query, framework loaders), not hand-copied state.
  3. Should it be shareable or survive refresh? Put it in the URL (search params).
  4. Is it used by one component or subtree? Keep it local with useState or useReducer in the lowest component that needs it.
  5. Do distant components need it? Lift it to the nearest common parent, or use context for slow-changing values like theme and user, or a store (Redux Toolkit, Zustand) for frequently changing client state.

Colocation is also a performance technique. When state lives high, each change re-renders everything below it unless memoized. Moving the state down into the component that uses it limits the work. A well-known trick is to move the stateful part into its own component, or pass expensive subtrees as children, which keep their element identity across the parent's state changes.

Trade-offs: feature folders can duplicate small helpers, shared code can become a dumping ground (review what enters shared), and strict boundaries need tooling discipline.

The example compares a lifted state version and a colocated version of the same page, counting renders of an expensive report.

jsx
import { memo, useState } from 'react';

const Report = memo(function Report({ tag }) {
  console.log(tag + ' report render');
  return <p>Report ({tag})</p>;
});

// State sits too high: every keystroke re-renders the whole page, and the Report is re-created.
function LiftedPage() {
  const [query, setQuery] = useState('');
  return (
    <section>
      <input aria-label="Lifted search" value={query} onChange={(e) => setQuery(e.target.value)} />
      <Report tag="lifted" data={{ query }} />
    </section>
  );
}

// State lives in the component that uses it. The Report does not depend on it.
function SearchBox() {
  const [query, setQuery] = useState('');
  return <input aria-label="Colocated search" value={query} onChange={(e) => setQuery(e.target.value)} />;
}

function ColocatedPage() {
  return (
    <section>
      <SearchBox />
      <Report tag="colocated" />
    </section>
  );
}

export default function App() {
  return (
    <div>
      <LiftedPage />
      <ColocatedPage />
    </div>
  );
}

In the lifted version the Report receives a new data object on every render, which shows how a parent's state change reaches it even through memo. The check typed three characters into each search box, and the sidecar counted the render messages. Output of the run: report renders on mount: lifted=1, colocated=1 report renders after typing 3 characters in each box: lifted=3, colocated=0

Key points

  • Group code by feature with a small public index, and enforce import directions with lint rules.
  • Layer shared, features and app. Dependencies point one way.
  • Decide state placement in order: derive, server cache, URL, local, lifted or global.
  • Keep state in the lowest component that needs it. Colocation limits re-renders.
  • Review shared folders so they do not become dumping grounds.

Common mistakes

  • Organizing only by file type in a large codebase.
  • Importing deep paths of another feature instead of its public index.
  • Lifting all state to the top "just in case".
  • Copying server data into local state.
  • Letting shared folders collect business logic.

Follow-ups

  • How would you enforce module boundaries automatically?
  • When would you split a feature into its own package or micro-frontend?
  • How does passing children help avoid re-renders?

Tips

  • Give the ordered state decision list. It is easy to remember and defend.
  • Mention automatic boundary enforcement. It separates convention from practice.
  • Show that colocation is a performance tool.
98.react-0098Hardsenior

How do you integrate a real-time source such as a WebSocket into React, and why is useSyncExternalStore the right tool for an external store?

Wrap the connection in a store outside React with subscribe and getSnapshot functions, and read it with useSyncExternalStore. React then re-renders safely under concurrent rendering, avoids tearing (different parts showing different values), and calls subscribe and its cleanup for you. Open the socket when the first subscriber arrives and close it when the last one leaves, keep snapshots immutable and cached, and handle reconnection with backoff, message ordering and cleanup in the store.

Full answer

Real-time data comes from outside React. A common beginner approach is useEffect that opens a socket and stores messages with setState. It works for one component, but each component opens its own connection, and with concurrent rendering a value read during render may differ from what another component saw (tearing).

useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) is designed for external stores. subscribe(callback) registers a listener and returns an unsubscribe function. getSnapshot() returns the current value, and it must return the same reference when nothing changed, or React will loop. React calls getSnapshot during render and after changes, and it forces updates from the store to be synchronous, which keeps the UI consistent. The optional getServerSnapshot supports server rendering and hydration.

Store design:

  • A module or class holds the connection, the list of listeners and an immutable snapshot ({ status, messages }).
  • On each incoming message, create a new snapshot object (do not mutate the old one) and notify listeners.
  • Connect lazily when the first listener subscribes and disconnect when the last one unsubscribes, so unused pages cost nothing.
  • Reconnect with exponential backoff and jitter after a drop, and expose status (connecting, open, closed) so the UI can show it. Resend the subscription and request missed messages after reconnecting, using a sequence number or last event id.
  • Parse and validate messages at the boundary. Cap the buffer size.
  • For high frequency updates, batch (for example at animation frame) and use selectors so components read only what they need.

Alternatives: Server-Sent Events for one-way streams, polling for simple needs, and data libraries that integrate sockets with the cache (for example calling queryClient.setQueryData when a message arrives). Libraries such as Zustand and Redux are built on the same hook.

The example uses a fake socket made of timers, so no network is needed.

jsx
import { useSyncExternalStore } from 'react';

function createMessageStore(openSocket) {
  let snapshot = { status: 'closed', messages: [] };
  let socket = null;
  const listeners = new Set();

  function update(next) {
    snapshot = { ...snapshot, ...next };
    listeners.forEach((listener) => listener());
  }

  return {
    subscribe(listener) {
      listeners.add(listener);
      if (listeners.size === 1) {
        console.log('first subscriber: connecting');
        update({ status: 'connecting' });
        socket = openSocket({
          onOpen: () => update({ status: 'open' }),
          onMessage: (text) => update({ messages: [...snapshot.messages, text] }),
        });
      }
      return () => {
        listeners.delete(listener);
        if (listeners.size === 0) {
          console.log('last subscriber left: disconnecting');
          socket.close();
          update({ status: 'closed' });
        }
      };
    },
    getSnapshot: () => snapshot,
  };
}

// A fake socket: opens after 10 ms and sends three messages.
function openFakeSocket({ onOpen, onMessage }) {
  const timers = [setTimeout(onOpen, 10)];
  ['Lesson 1 published', 'Lesson 2 published', 'Quiz opened'].forEach((text, i) => {
    timers.push(setTimeout(() => onMessage(text), 20 + i * 10));
  });
  return { close: () => timers.forEach(clearTimeout) };
}

const store = createMessageStore(openFakeSocket);

export default function Updates() {
  const { status, messages } = useSyncExternalStore(store.subscribe, store.getSnapshot);

  return (
    <div>
      <p>Status: {status}</p>
      <ul>
        {messages.map((message) => (
          <li key={message}>{message}</li>
        ))}
      </ul>
    </div>
  );
}

The store connects when the component subscribes and disconnects when it unmounts. The check waited for the fake socket to finish. A real store would add reconnect with backoff. Output of the run: first subscriber: connecting after the connection delivered messages: Status: openLesson 1 publishedLesson 2 publishedQuiz opened last subscriber left: disconnecting

Key points

  • Put the connection in a store outside React and read it with useSyncExternalStore.
  • getSnapshot must return a cached, immutable value that changes only when data changes.
  • Connect on the first subscriber and disconnect on the last one.
  • Handle reconnect with backoff, missed messages, validation and bounded buffers.
  • For high-frequency data, batch updates and select only what a component needs.

Common mistakes

  • Returning a new object from getSnapshot on every call, which causes an infinite loop.
  • Mutating the snapshot instead of creating a new one.
  • Opening one connection per component.
  • Not cleaning up the socket on unmount.
  • Reconnecting immediately in a tight loop with no backoff.

Follow-ups

  • What is tearing and how does useSyncExternalStore prevent it?
  • How would you implement reconnect with exponential backoff and jitter?
  • How would you feed socket messages into a TanStack Query cache?

Tips

  • Mention tearing. It is the reason the hook exists.
  • State the getSnapshot caching rule. It is the most common bug.
  • Describe lazy connect and disconnect.
99.react-0099Hardsenior

How do you implement optimistic updates with TanStack Query, including cancelling queries, rollback on error and revalidation?

In useMutation, onMutate cancels outgoing refetches for the key, saves the previous cache value, writes the optimistic value with setQueryData, and returns the previous value as context. onError restores that context. onSettled invalidates the query so the cache syncs with the server whichever way the mutation ended. The UI changes immediately, and a failure rolls back. React 19's useOptimistic is an alternative for local, form-based cases.

Full answer

Waiting for the server before showing a change feels slow. An optimistic update shows the expected result at once and corrects it if the request fails. It suits low-risk actions that nearly always succeed: toggles, likes, reordering. Avoid it for payments or operations with complex server rules.

TanStack Query provides the lifecycle in useMutation:

  1. onMutate(variables) runs before the request. Call await queryClient.cancelQueries({ queryKey }) so an in-flight refetch cannot overwrite the optimistic value. Read previous = queryClient.getQueryData(queryKey). Write the new value with queryClient.setQueryData(queryKey, updater) and return { previous }.
  2. onError(error, variables, context) restores context.previous with setQueryData.
  3. onSettled calls queryClient.invalidateQueries({ queryKey }), so the cache is refreshed from the server whether the request succeeded or failed. This corrects any difference between the guess and the real result.

Details that matter. Updaters must be immutable: return a new array or object. When several mutations can overlap, rolling back a snapshot may undo a later successful change, so invalidate and refetch after the last one finishes or use mutation keys and isMutating to skip invalidation until the queue is empty. A simpler variant (since v5) renders the pending variables directly from useMutation's variables while isPending is true, without touching the cache, which avoids rollback code entirely and works well for a single list. Show errors with a toast so users know the change did not stick.

Alternatives: React 19 useOptimistic gives local optimistic state tied to a transition or form action and reverts automatically when the action ends. For server-driven frameworks that is often enough. For shared cache state across components, the query cache approach is better.

Test the failure path, because rollback code is rarely exercised in manual testing.

The example toggles a lesson as done. The first request fails on purpose.

jsx
import { QueryClient, QueryClientProvider, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

let serverDone = false;
let calls = 0;

const fetchLesson = () => new Promise((resolve) => setTimeout(() => resolve({ done: serverDone }), 10));
const saveLesson = (done) =>
  new Promise((resolve, reject) =>
    setTimeout(() => {
      calls += 1;
      if (calls === 1) reject(new Error('Network error'));
      else {
        serverDone = done;
        resolve({ done });
      }
    }, 80)
  );

const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });

function Lesson() {
  const client = useQueryClient();
  const { data } = useQuery({ queryKey: ['lesson'], queryFn: fetchLesson });

  const mutation = useMutation({
    mutationFn: saveLesson,
    onMutate: async (done) => {
      await client.cancelQueries({ queryKey: ['lesson'] });
      const previous = client.getQueryData(['lesson']);
      client.setQueryData(['lesson'], { done });
      return { previous };
    },
    onError: (_error, _done, context) => {
      client.setQueryData(['lesson'], context.previous);
    },
    onSettled: () => client.invalidateQueries({ queryKey: ['lesson'] }),
  });

  if (!data) return <p>Loading...</p>;

  return (
    <div>
      <p>{data.done ? 'Lesson done' : 'Lesson not done'}</p>
      <button onClick={() => mutation.mutate(!data.done)}>Toggle</button>
    </div>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Lesson />
    </QueryClientProvider>
  );
}

The fake server rejects the first request and accepts the next ones. The check clicked Toggle, read the text before the server answered, and again after the failure, and then repeated with a request that succeeds. Output of the run: loaded: Lesson not done right after clicking (server not answered yet, request will fail): Lesson done after the failed request: Lesson not done second click, optimistic: Lesson done after the successful request: Lesson done

Key points

  • onMutate cancels queries, snapshots the cache, writes the optimistic value and returns context.
  • onError restores the snapshot. onSettled invalidates to sync with the server.
  • Updaters must be immutable, and overlapping mutations need care.
  • The variables-based variant renders pending data without cache writes.
  • useOptimistic is the React-level alternative for local or form-driven cases.

Common mistakes

  • Forgetting cancelQueries, so a refetch overwrites the optimistic value.
  • Mutating cached data instead of returning a new value.
  • Skipping onSettled invalidation, leaving the cache out of sync.
  • Using optimistic updates for actions that often fail or have side effects.
  • Not testing the rollback path.

Follow-ups

  • How do you handle two quick mutations that overlap?
  • When is useOptimistic a better choice than the query cache?
  • How does the variables-based approach avoid rollback code?

Tips

  • Walk through the three callbacks in order.
  • Mention overlapping mutations. It is the senior-level caveat.
  • Say you test the failure path.
100.react-0100Hardsenior

How do you analyze and reduce a React bundle, and how does code splitting with dynamic import and React.lazy work?

Measure first with a bundle analyzer or the bundler's metafile to see which modules take the space. Then split: load routes and heavy, rarely used features with dynamic import() and React.lazy inside Suspense, so they become separate chunks fetched on demand. Reduce what remains by tree shaking (ES modules, sideEffects flag, direct imports instead of barrels), replacing heavy libraries, removing duplicates, and enforcing budgets in CI. Prefetch likely next chunks to avoid delays.

Full answer

Bundle size affects download, parse and execution time, so it shows up in load speed and in INP on slow devices. Work in a loop: measure, change, measure again.

Measure. Visualize the output with webpack-bundle-analyzer, rollup-plugin-visualizer, source-map-explorer or the framework's own report (for Next.js, @next/bundle-analyzer). With esbuild or Vite, the metafile or rollup output lists every module and size. Look for large libraries, duplicated packages (two versions of the same library), whole locale or icon sets, and code that is used on one page but loaded everywhere. Compare gzip or brotli sizes, because those are transferred. Use Lighthouse or the Coverage panel to see how much loaded code is unused at startup.

Split. A dynamic import('./Chart.js') returns a promise and tells the bundler to create a separate chunk. React.lazy(() => import('./Chart')) wraps it as a component that suspends until the chunk loads, and needs a <Suspense fallback> ancestor. Natural split points are routes (first priority), modals and drawers, tabs the user may never open, and heavy libraries used on interaction (a markdown editor, a PDF viewer). Lazy components must be the default export of the imported module. Place Suspense boundaries so a fallback does not replace the whole page, and give the fallback a similar size to avoid layout shift. Handle chunk load failures (offline, or a new deployment removed the old chunk) with an error boundary that offers a reload.

Prefetch. Start loading the chunk on hover, on focus, when idle or when the link scrolls into view, by calling the import function early. Bundlers support hints such as /* webpackPrefetch: true */. Framework routers do this for links.

Shrink what remains. Use ES module versions of libraries so tree shaking works, and set sideEffects: false in your own packages when safe. Import directly (date-fns/format, or the library's documented path) instead of through large barrel files, unless the library supports tree shaking well. Replace heavy libraries with lighter ones or platform APIs (Intl instead of moment). Check polyfills and browserslist targets. Move non-critical third-party scripts out of the main bundle. Server Components keep server-only code out of the client bundle entirely.

Guardrails. Add a size budget in CI (for example with size-limit or bundler warnings), review bundle changes in pull requests, and watch real-user metrics.

The example uses esbuild's API to build the same code with and without splitting.

jsx
import { build } from 'esbuild';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

const dir = await mkdtemp(path.join(tmpdir(), 'split-'));
await writeFile(path.join(dir, 'greet.js'), "export const greet = (name) => 'Hello ' + name;\n");
await writeFile(path.join(dir, 'chart.js'), 'export const data = ' + JSON.stringify('x'.repeat(30000)) + ';\n');
await writeFile(
  path.join(dir, 'main.js'),
  "import { greet } from './greet.js';\nconsole.log(greet('Asha'));\nexport const loadChart = () => import('./chart.js');\n"
);

async function bundle(splitting) {
  const result = await build({
    entryPoints: [path.join(dir, 'main.js')],
    bundle: true,
    format: 'esm',
    splitting,
    minify: true,
    outdir: path.join(dir, splitting ? 'split' : 'single'),
    metafile: true,
    write: false,
  });
  return Object.entries(result.metafile.outputs).map(([file, info]) => ({
    name: path.basename(file).replace(/-[A-Z0-9]+\./, '.'),
    kb: Math.round(info.bytes / 1000),
  }));
}

const single = await bundle(false);
const split = await bundle(true);
console.log('without splitting: ' + single.map((f) => f.name + ' ' + f.kb + ' kB').join(', '));
console.log('with splitting: ' + split.map((f) => f.name + ' ' + f.kb + ' kB').join(', '));

This ran esbuild on the box with a small synthetic project. The chart module contains 30 kB of data, standing for a heavy library. With splitting, the entry stays tiny and the chart becomes its own chunk, loaded only when loadChart runs. Output of the run: without splitting: main.js 30 kB with splitting: main.js 0 kB, chart.js 30 kB

Key points

  • Measure with an analyzer or metafile before changing anything, and compare compressed sizes.
  • Split by route first, then by rarely used features and heavy libraries, with import() and React.lazy inside Suspense.
  • Handle chunk load failures and use similar-size fallbacks.
  • Prefetch likely chunks on hover, focus or idle time.
  • Reduce the remainder with tree shaking, direct imports, lighter libraries and CI size budgets.

Common mistakes

  • Optimizing without looking at an analyzer.
  • Lazy-loading everything, including small above-the-fold components, and creating loading waterfalls.
  • Forgetting a Suspense boundary around lazy components.
  • Ignoring chunk load errors after a new deployment.
  • Importing a whole library for one function.

Follow-ups

  • How does tree shaking work and what breaks it?
  • How would you prefetch a route chunk when the user hovers a link?
  • How do React Server Components change client bundle size?

Tips

  • Start with measurement. It prevents guesswork.
  • Say route-level splitting comes first, and mention chunk load errors.
  • Give one concrete library replacement, such as Intl instead of moment.