← Interview prep

React interview questions

Hooks, rendering, state, and React interview favorites.

150 questions · Page 3 of 8

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

Page 3 of 8

Questions 41–60 of 150 · 0 of 20 on this page marked learned

41.react-0041Hardsenior

What are Server Actions (Server Functions), how are they called from the client, and how do you secure them?

A Server Function is an async function marked with "use server" that runs on the server but can be called from client components, often as a form action. The framework turns each into an HTTP endpoint, and the client call becomes a request. Because anyone can send that request, every action must authenticate the caller, authorize the operation, validate all input on the server, and return only safe data.

Full answer

Server Functions remove the manual work of writing an API route, a fetch call and a JSON contract for each mutation. You write a function in a file with the "use server" directive, import it in a client component, and pass it to a form's action or call it from an event handler or transition. React and the framework handle the serialization and the network request. (The older name Server Actions referred to the form use case. The general feature is now Server Functions.)

What looks like a function call is a public HTTP POST endpoint. The client code is only a convenience. An attacker does not need your UI: they can send a crafted request directly with any arguments. So the security rules are the same as for any API.

Authenticate: read the session on the server inside the function. Never trust a user id, a role or a price sent from the client. Authorize: check that this user may act on this record, not only that they are logged in. Validate: check types, ranges and lengths of everything in FormData or arguments with a schema library or explicit checks, and return field errors. Do not return secrets, internal errors or full database rows. Limit rates for sensitive operations, and protect against forged cross-site requests (frameworks include checks on the Origin header, but verify the defaults for your setup).

Only async functions can be exported from a "use server" file, and arguments and return values must be serializable. Inline functions in a Server Component that are marked "use server" can capture variables, and some frameworks encrypt those captured values for the round trip, but treat them as data from the client anyway.

Keep server packages up to date. In December 2025 a critical remote code execution flaw in the Server Components protocol was fixed in React 19.0.1, 19.1.2 and 19.2.1.

The function below checks the caller, validates the input and returns a result for useActionState. It is run here as a plain async function.

js
'use server';

const students = new Map([['1', { id: '1', name: 'Asha' }]]);

async function getCurrentUser() {
  // Stands in for reading the session cookie on the server.
  return { id: 'teacher-1', role: 'teacher' };
}

export async function renameStudent(previousState, formData) {
  const user = await getCurrentUser();
  if (!user || user.role !== 'teacher') {
    return { ok: false, error: 'Not allowed' };
  }

  const id = String(formData.get('id') ?? '');
  const name = String(formData.get('name') ?? '').trim();

  if (!students.has(id)) {
    return { ok: false, error: 'Unknown student' };
  }
  if (name.length < 2 || name.length > 50) {
    return { ok: false, error: 'Name must be 2 to 50 characters' };
  }

  students.set(id, { id, name });
  return { ok: true, name };
}

The function checks who is calling, validates both fields and returns a small result object. In a real project it would be used from a client component through useActionState and a form. This check called it three times as an ordinary async function, which does not test the HTTP layer a framework adds. Output of the run: valid rename: {"ok":true,"name":"Asha Verma"} name too short: {"ok":false,"error":"Name must be 2 to 50 characters"} unknown student: {"ok":false,"error":"Unknown student"}

Key points

  • A Server Function is an async "use server" function callable from client code. It is exposed as an HTTP endpoint.
  • Never trust arguments. Authenticate, authorize and validate on the server every time.
  • Return minimal, serializable results. Do not leak errors or secrets.
  • Only async functions can be exported from a "use server" file.
  • Keep React and the framework patched, since the protocol has had security fixes.

Common mistakes

  • Treating an action as private because only your form calls it.
  • Checking that the user is logged in but not that they own the record.
  • Trusting hidden form fields such as a role or a price.
  • Returning raw database errors or whole records.
  • Exporting non-async helpers from a "use server" file.

Follow-ups

  • How would you protect against forged cross-site requests for actions?
  • How do Server Functions differ from route handlers or API routes in design terms?
  • How would you use the returned error object with useActionState in the client component?

Tips

  • Open with "it is a public endpoint". Security-minded interviewers look for this sentence.
  • List authenticate, authorize, validate in that order.
  • Mention that you validate even when the form already has client-side checks.
42.react-0042Mediummid

What are the main changes in React 19 and the later 19.x releases that you would use in everyday code?

React 19 added Actions with useActionState, useFormStatus and useOptimistic, the use API for promises and context, ref as a normal prop, context as its own provider, built-in document metadata tags, better error reporting and stable Server Components. Version 19.2 added Activity and useEffectEvent, and 19.3 added View Transitions and Fragment refs. It also removed old APIs such as propTypes for functions and ReactDOM.render.

Full answer

The most visible theme of React 19 is making async work and forms first-class.

Actions let a transition contain an async function, with pending state, errors and optimistic updates handled by React. useActionState tracks the result of an action, useFormStatus reads the parent form's pending state, and useOptimistic shows an expected result while a request is in flight. Forms accept a function in action.

The use API reads a resource during render. With a promise it suspends until the promise resolves. With a context it reads the value, and unlike useContext it may be called after an early return or inside a condition.

Smaller changes remove boilerplate. ref is a regular prop for function components, so forwardRef is not needed. A context object works as its own provider (<ThemeContext value={...}>). Ref callbacks can return cleanup functions. React elements such as <title>, <meta> and <link> can be rendered anywhere in a component and are placed in the document head. Stylesheets and scripts can declare priority and loading order, and custom elements are supported.

Error handling improved: errors are reported once, and createRoot and hydrateRoot accept onCaughtError, onUncaughtError and onRecoverableError. Hydration errors show a readable diff.

React 19.2 added Activity, which hides part of the UI while keeping its state and pausing its effects, and useEffectEvent. React 19.3 added View Transitions and Fragment refs. The React Compiler became stable separately.

Several old APIs were removed: propTypes and defaultProps on function components (use TypeScript and default parameters), string refs, legacy context, findDOMNode, and ReactDOM.render and hydrate. act now lives in the react package.

Upgrade note: install the codemods, update libraries that pass refs or read internals, and keep Server Component packages patched.

The example uses several of these features together.

jsx
import { createContext, use, useRef, useState } from 'react';

const LanguageContext = createContext('en');

function Greeting() {
  const language = use(LanguageContext);
  return <p>{language === 'hi' ? 'Namaste' : 'Hello'}</p>;
}

function NameField({ ref, label }) {
  return (
    <label>
      {label}
      <input ref={ref} />
    </label>
  );
}

export default function App() {
  const [language, setLanguage] = useState('en');
  const fieldRef = useRef(null);

  return (
    <LanguageContext value={language}>
      <title>Student portal</title>
      <meta name="description" content="Check your marks" />
      <Greeting />
      <NameField ref={fieldRef} label="Name" />
      <button onClick={() => setLanguage('hi')}>Switch language</button>
    </LanguageContext>
  );
}

The example uses use with context, ref as a prop, a context as its own provider, and title and meta tags rendered inside the component. After the click, the greeting changes. Rendered result: <p>Namaste</p><label>Name<input></label><button>Switch language</button> Document head after the run: <title>Student portal</title><meta name="description" content="Check your marks">

Key points

  • Actions: async transitions with useActionState, useFormStatus, useOptimistic and form action props.
  • use reads promises and context, and can be called conditionally.
  • ref is a normal prop, a context is its own provider, and ref callbacks can clean up.
  • Document metadata tags render from any component and are hoisted to the head.
  • 19.2 and 19.3 add Activity, useEffectEvent, View Transitions and Fragment refs. Old APIs like ReactDOM.render are removed.

Common mistakes

  • Still wrapping every component in forwardRef in new React 19 code.
  • Expecting use to work like a normal hook inside try and catch, or to accept a promise created during render.
  • Relying on defaultProps or propTypes on function components, which are no longer supported.
  • Assuming Server Components work without a framework or bundler integration.
  • Calling ReactDOM.render in a migrated project.

Follow-ups

  • How does use differ from useContext and from await?
  • What does Activity do compared with conditional rendering?
  • What did the React Compiler 1.0 release change about manual memoization?

Tips

  • Group the answer by theme (async, ergonomics, errors, removals) instead of a list of hook names.
  • State which release added each feature. Version precision signals real familiarity.
  • Mention what was removed. Migration questions often follow.
43.react-0043Hardsenior

What does the React Compiler do, what are its limits, and how does it change the way you use memo, useMemo and useCallback?

React Compiler is a build-time tool, a Babel plugin, that analyzes components and hooks and adds memoization automatically, skipping work when inputs have not changed. It assumes your code follows the Rules of React: pure render, no mutation of props or state. You write plain components and the compiler caches values, functions and JSX. Manual memo hooks are still useful as an escape hatch and for precise control over effect dependencies.

Full answer

Manual memoization is tedious and easy to get wrong. A missing dependency causes a stale value, and a forgotten useCallback causes needless re-renders. React Compiler 1.0, stable since October 2025, does this analysis for you at build time.

It reads each component and hook, builds a model of which values depend on which inputs, and rewrites the function so that each piece of the output is cached and reused when its inputs are unchanged. The compiled code keeps a small cache array, created with a function imported from react/compiler-runtime, and compares inputs with Object.is. It can memoize things hooks cannot, such as values after a conditional return, and the JSX of unchanged branches. As a result, a child component receives the same element and React skips it, even without memo.

It works only when the code follows the Rules of React. It does not change behaviour for correct code. For code that mutates props, reads and writes refs during render, or otherwise breaks the rules, the compiler skips that component, and the bundled ESLint rules report why. You can opt in per file with the "use memo" directive or opt out with "use no memo" while debugging. Teams usually adopt it gradually, with the compilationMode: 'annotation' option or by directory.

What changes for you? Stop adding useMemo and useCallback for performance by default. Keep them where you need a guaranteed stable reference, such as an effect dependency or a value passed to a non-React library, and keep React.memo for expensive children when you want an explicit contract. Existing manual memoization is safe to leave.

The compiler needs a build step: the Babel plugin, or the Vite, Next.js and other integrations. It does not fix slow algorithms, giant lists, waterfalls or bad data fetching, so profiling still matters.

The example below was compiled and run twice, once plain and once with the compiler, and the render counts were compared.

jsx
import { useState } from 'react';

function Roster({ names }) {
  console.log('Roster rendered');
  return (
    <ul>
      {names.map((name) => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  );
}

export default function Gradebook() {
  const [ticks, setTicks] = useState(0);
  const names = ['Asha', 'Ravi', 'Meera'].map((n) => n.toUpperCase());

  return (
    <div>
      <button onClick={() => setTicks(ticks + 1)}>Ticks: {ticks}</button>
      <Roster names={names} />
    </div>
  );
}

The component has no useMemo, useCallback or memo. Without the compiler, names is a new array on every render, so Roster rendered again after the tick button was pressed once: the console showed two lines. With babel-plugin-react-compiler 1.0.0 applied, the same code logged one line, because the compiler cached names and the Roster element. Both runs used React 19 in jsdom. Output without the compiler: Roster rendered Roster rendered

Key points

  • React Compiler adds memoization at build time using Rules of React analysis. It reached 1.0 in October 2025.
  • Correct code behaves the same. Components that break the rules are skipped, and the linter explains why.
  • Manual useMemo, useCallback and memo become an escape hatch, not a default.
  • Adopt gradually with directives and compilation modes.
  • It does not replace profiling, virtualization or good data loading.

Common mistakes

  • Believing the compiler fixes code that mutates props or state.
  • Removing all manual memoization at once without measuring.
  • Expecting speedups without profiling the actual bottleneck.
  • Disabling the compiler lint rules instead of fixing the violations.
  • Using refs in render and then wondering why a component is skipped.

Follow-ups

  • Which patterns make the compiler skip a component?
  • Would you remove existing useMemo calls after enabling the compiler? Why or why not?
  • How would you roll out the compiler in a large codebase?

Tips

  • Describe the mechanism (cache plus Object.is comparison), not just "it memoizes for you".
  • Say that correct code is a precondition. It links the compiler to the Rules of React.
  • State a rollout plan (annotation mode, directories). It shows practical thinking.
44.react-0044Hardsenior

A React screen feels slow. How do you find out why, and what are the usual fixes in order?

Measure first. Record an interaction in the React DevTools Profiler and in the browser Performance panel to see which components render, how often and why. Then fix the biggest cause: move state down or split components so fewer things re-render, stabilize props with memo or the compiler, virtualize long lists, defer or transition non-urgent updates, and reduce bundle size or network waterfalls. Do not memoize at random.

Full answer

Start by defining what slow means. Is it input lag (INP), a slow first load (LCP), or a janky scroll? The tool and the fix depend on the answer.

For render problems, open React DevTools, record a Profiler session while performing the slow action, and read the flame graph. It shows which components rendered, how long each took, and, with "record why each component rendered" enabled, whether a prop, state or context change was the cause. In code, the <Profiler id onRender> component reports the same data programmatically. React 19.2 also adds Performance Tracks to the browser's performance timeline. Use the browser Performance panel to see long tasks, layout and paint cost outside React.

Common causes and fixes, from cheapest:

  1. State is too high. A keystroke in a form re-renders the whole page. Move the state into a smaller component, or pass expensive parts as children so they keep the same element.
  2. Unstable props defeat memo. Stabilize them or enable the React Compiler.
  3. Expensive work in render. Cache it with useMemo, or move it to a worker or the server.
  4. Huge lists. Virtualize them so only visible rows exist in the DOM.
  5. Urgent and non-urgent updates mixed. Use transitions or useDeferredValue.
  6. Context that changes often. Split it or switch to a store with selectors.
  7. Loading cost. Split code with lazy, remove unused libraries, and fetch in parallel with route loaders or Server Components.

After each change, measure again to confirm. Production builds behave differently from development, which has extra checks, so confirm in a production build with profiling enabled.

The example wraps a component in the Profiler, which reports each commit. Durations are not printed because they differ between runs.

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

function onRender(id, phase) {
  console.log('profiler ' + id + ': ' + phase);
}

function Cart({ items }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const [items, setItems] = useState(['Notebook']);

  return (
    <div>
      <button onClick={() => setItems((list) => [...list, 'Pen'])}>Add item</button>
      <Profiler id="cart" onRender={onRender}>
        <Cart items={items} />
      </Profiler>
    </div>
  );
}

Profiler calls onRender whenever a component inside it commits. In the first commit the phase is mount, after adding an item it is update. Output of the run in a development build: profiler cart: mount profiler cart: update

Key points

  • Define the symptom first and measure with the React Profiler and the browser Performance panel.
  • Enable "record why each component rendered" to find the trigger.
  • Fix structure first (state placement, composition), then memoization, then lists, then scheduling.
  • Verify in a production build and measure again after each change.
  • Loading performance (bundle size, waterfalls) is a separate problem from render performance.

Common mistakes

  • Adding memo and useMemo everywhere before measuring.
  • Profiling a development build and treating its timings as production numbers.
  • Fixing re-render counts that do not affect what users feel.
  • Ignoring network and bundle size when the problem is the first load.
  • Reading a flame graph without enabling the "why did this render" option.

Follow-ups

  • What would you do about a keystroke in a form that re-renders a table of 5000 rows?
  • How do Core Web Vitals such as INP relate to React rendering?
  • How do you decide between memoization and restructuring components?

Tips

  • Start the answer with the word "measure" and name the tool. It shows process.
  • Give the fixes in a clear priority order.
  • Mention production builds. Many candidates profile the slower development build.
45.react-0045Hardsenior

Why can React context cause unnecessary re-renders, and how do you structure providers to avoid it?

Every component that calls useContext for a context re-renders when that context's value changes, even if it uses only part of the value. Avoid it by splitting contexts (one for state, one for dispatch, one per concern), keeping the provider's value stable, passing children through the provider so they do not re-render with it, and moving fast-changing state into a store with selectors when context is not enough.

Full answer

Context has no selector. If the value is { user, theme, notifications } and only notifications changes, every consumer re-renders, because React compares the whole value with Object.is and sees a different object.

Two separate causes hide inside this problem. First, a new value object on every provider render, such as value={{ a, b }}, re-renders all consumers even when a and b did not change. Second, a provider that holds state re-renders its own subtree when the state changes, unless the subtree is passed as children.

The remedies, in order of effort:

  1. Keep the value stable. Memoize it with useMemo, or use a value that is already stable.
  2. Pass children. function Provider({ children }) renders <Ctx value={...}>{children}</Ctx>. The children elements are created by the parent of the Provider, so they are the same on a state change and React skips re-rendering them. Only the consumers re-render.
  3. Split by change frequency and by role. A common pattern keeps state in one context and the dispatch function in another. Dispatch from useReducer is stable, so components that only trigger actions never re-render when state changes.
  4. Split by domain: separate AuthContext, ThemeContext and CartContext.
  5. If many components need slices of fast-changing state, use a store with selectors (Zustand, Redux Toolkit, Jotai) or build one on useSyncExternalStore. Components subscribe to a slice and re-render only when that slice changes.

React.memo on consumers does not help against context changes: a context update bypasses memo. And the compiler does not change the rule either, because it concerns the value changing.

The example logs which components render. A button that only dispatches does not re-render when the count changes.

jsx
import { createContext, useContext, useReducer } from 'react';

const CountStateContext = createContext(0);
const CountDispatchContext = createContext(null);

function reducer(count, action) {
  if (action === 'add') return count + 1;
  throw new Error('Unknown action');
}

function CountProvider({ children }) {
  const [count, dispatch] = useReducer(reducer, 0);
  return (
    <CountStateContext value={count}>
      <CountDispatchContext value={dispatch}>{children}</CountDispatchContext>
    </CountStateContext>
  );
}

function CountDisplay() {
  const count = useContext(CountStateContext);
  console.log('CountDisplay rendered');
  return <p>Count: {count}</p>;
}

function AddButton() {
  const dispatch = useContext(CountDispatchContext);
  console.log('AddButton rendered');
  return <button onClick={() => dispatch('add')}>Add</button>;
}

export default function App() {
  return (
    <CountProvider>
      <CountDisplay />
      <AddButton />
    </CountProvider>
  );
}

State and dispatch live in two contexts, and the components are passed as children. After one click only the component that reads the count renders again. Console output (the first two lines are the mount): CountDisplay rendered AddButton rendered CountDisplay rendered

Key points

  • All consumers re-render when the context value changes, with no selector support.
  • Do not create the value object inline on every provider render.
  • Pass children to the provider so unrelated subtrees are not re-rendered with it.
  • Split state and dispatch, and split by domain and update frequency.
  • Use a store with selectors for fast-changing shared state.

Common mistakes

  • Putting the whole application state in one large context.
  • Creating a new value object in the provider on every render.
  • Expecting React.memo on a consumer to stop context-driven re-renders.
  • Placing a fast-changing value such as pointer position in context.
  • Rendering the subtree inside the same component that owns the state instead of passing children.

Follow-ups

  • How does useSyncExternalStore help build a selector-based store?
  • Why does the dispatch function from useReducer have a stable identity?
  • When is context still the right tool compared with Zustand or Redux Toolkit?

Tips

  • Open with "no selectors". It names the root cause precisely.
  • Explain the children trick. Few candidates know it.
  • Close with the limit: context for slow data, a store for fast data.
46.react-0046Hardsenior

How do you decide where state should live in a React app, and when would you pick Redux Toolkit, Zustand, TanStack Query or plain context?

Classify the state first. Local UI state stays in useState. Server data (cached API results) belongs in a query library such as TanStack Query. State in the URL belongs to the router. Shared client state that many distant components read and change often fits a store with selectors: Zustand for a small footprint, Redux Toolkit for strict structure, devtools and large teams. Context suits rarely changing values such as theme and the current user.

Full answer

Most "we need Redux" problems are really "we mixed several kinds of state". Sorting them first removes most of the need for a global store.

Local state is used by one component or a small subtree: an open dropdown, an input value. Use useState or useReducer, and lift state only as far as needed.

Server state is a copy of data owned by a backend. It needs fetching, caching, refetching, deduplication, retries and invalidation after mutations. Writing that in effects and a global store is a lot of work. TanStack Query (or SWR, or the data layer of a framework) handles it, and removes most of the data from client stores.

URL state, such as filters, pagination and the selected tab, belongs in the address with the router's search params, which makes pages shareable and back-button friendly.

Form state with many fields and validation can use actions, or a library such as React Hook Form.

What remains is shared client state: a shopping cart, a multi-step wizard, a drawing tool's selection. For this, context works only if the data changes rarely, because every consumer re-renders. A store with selectors lets each component subscribe to a slice.

Zustand creates a store with one function, needs no provider and re-renders a component only when its selected value changes. Jotai uses small atoms for fine-grained updates. Redux Toolkit adds slices, immutable updates through Immer, middleware, strong devtools with time travel, and conventions that help large teams stay consistent. Its cost is more ceremony.

A reasonable default for a new product is useState, a query library and the router first, then add Zustand or Redux Toolkit when a real shared client state appears.

The store in the example uses selectors, so the component that shows the last action does not re-render when the same action repeats.

jsx
import { create } from 'zustand';

const useCartStore = create((set) => ({
  items: [],
  lastAction: 'none',
  add: (name) =>
    set((state) => ({ items: [...state.items, name], lastAction: 'add ' + name })),
  clear: () => set({ items: [], lastAction: 'clear' }),
}));

function CartCount() {
  const count = useCartStore((state) => state.items.length);
  console.log('CartCount rendered');
  return <p>Items: {count}</p>;
}

function LastAction() {
  const lastAction = useCartStore((state) => state.lastAction);
  console.log('LastAction rendered');
  return <p>Last action: {lastAction}</p>;
}

function Controls() {
  const add = useCartStore((state) => state.add);
  const clear = useCartStore((state) => state.clear);
  return (
    <div>
      <button onClick={() => add('pen')}>Add pen</button>
      <button onClick={clear}>Clear</button>
    </div>
  );
}

export default function App() {
  return (
    <div>
      <Controls />
      <CartCount />
      <LastAction />
    </div>
  );
}

This example uses the zustand package. Each component selects only what it needs. The check added a pen twice and then cleared the cart. The second add does not change lastAction, so only CartCount rendered again for it. Console output (the first two lines are the mount): CartCount rendered LastAction rendered CartCount rendered LastAction rendered CartCount rendered CartCount rendered LastAction rendered

Key points

  • Separate local, server, URL, form and shared client state before choosing a tool.
  • A query library handles server data, so most data should not live in a client store.
  • Context is for low-frequency values. Fast-changing shared state needs a store with selectors.
  • Zustand is small and flexible. Redux Toolkit gives structure, middleware and devtools for larger teams.
  • Start simple and add a store only when a real shared client state exists.

Common mistakes

  • Putting server data into a client store and rewriting caching by hand.
  • Putting every value in a global store, including local form inputs.
  • Selecting the whole store in a component, which re-renders on any change.
  • Selecting a new object or array in a selector without equality handling.
  • Choosing Redux or Zustand from habit instead of from the kind of state.

Follow-ups

  • What does TanStack Query give you that a Redux store does not?
  • How would you persist part of a Zustand store to local storage?
  • How do Server Components change where data fetching and state live?

Tips

  • Begin with the classification of state. It shows a framework for thinking, not tool loyalty.
  • Name one criterion for each tool. Do not just list libraries.
  • State the default stack for a new project and when you would add a store.
47.react-0047Hardsenior

What is useSyncExternalStore, why was it introduced, and what are the rules for getSnapshot?

useSyncExternalStore subscribes a component to data that lives outside React, such as a store, the browser's online status or a media query, in a way that is safe with concurrent rendering. It takes subscribe, getSnapshot and an optional getServerSnapshot. React reads a consistent snapshot throughout a render to prevent tearing. getSnapshot must return the same value when the data has not changed, or React loops.

Full answer

React state is private to React. Many things are not: a Redux-style store, localStorage, window size, network status, a WebSocket cache. Before React 18 libraries subscribed with useEffect and copied data into state. With concurrent rendering this can produce tearing: the render is interruptible, the store changes in the middle, and two components in the same pass show different values.

const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) solves it. subscribe(callback) registers a listener, calls callback when the store changes, and returns an unsubscribe function. getSnapshot returns the current value. React calls it during render and again before committing, and if the value changed it re-renders synchronously, so the UI never commits an inconsistent view. Updates triggered by this hook cannot be deferred by transitions, which is the price for consistency.

The rules matter. getSnapshot must be pure and fast, and it must return a cached, immutable result: calling it twice without a store change must give an identical value according to Object.is. If it builds a new object each call, React sees a change every time and throws an infinite-loop error. The subscribe function must be stable, defined outside the component or memoized, otherwise React resubscribes on every render.

getServerSnapshot returns the initial value during server rendering and hydration. It must return the same data on both sides. Without it, using the hook on the server throws an error.

You rarely call it directly. State libraries use it inside: Zustand, Redux and Jotai build on it, and it is also the right tool for small hooks such as useOnlineStatus or useMediaQuery.

The example builds a tiny store and an online-status hook.

jsx
import { useSyncExternalStore } from 'react';

function createStore(initialState) {
  let state = initialState;
  const listeners = new Set();
  return {
    getSnapshot: () => state,
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    setState(next) {
      state = next;
      listeners.forEach((listener) => listener());
    },
  };
}

const counterStore = createStore({ count: 0 });

function subscribeToOnline(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

function useOnlineStatus() {
  return useSyncExternalStore(
    subscribeToOnline,
    () => window.navigator.onLine,
    () => true
  );
}

function Counter() {
  const state = useSyncExternalStore(counterStore.subscribe, counterStore.getSnapshot);
  return (
    <button onClick={() => counterStore.setState({ count: state.count + 1 })}>
      Count: {state.count}
    </button>
  );
}

export default function App() {
  const online = useOnlineStatus();
  return (
    <div>
      <Counter />
      <p>{online ? 'Online' : 'Offline'}</p>
    </div>
  );
}

The counter lives in a store outside React and the component re-renders when the store notifies it. The online hook reads the browser state, with a fixed value for server rendering. The check clicked the counter once. Rendered result: <div><button>Count: 1</button><p>Online</p></div>

Key points

  • It connects components to external stores safely in concurrent React.
  • It prevents tearing by reading one consistent snapshot per render.
  • getSnapshot must return a stable, cached, immutable value when nothing changed.
  • subscribe must be a stable function that returns an unsubscribe.
  • getServerSnapshot gives the same initial value on the server and during hydration.

Common mistakes

  • Returning a new object from getSnapshot on every call, which causes an infinite loop.
  • Defining subscribe inside the component, which resubscribes on every render.
  • Omitting getServerSnapshot in a server-rendered app.
  • Using useEffect and useState to mirror a store, which allows tearing.
  • Mutating the store state in place so the snapshot reference never changes.

Follow-ups

  • Why can transitions not defer updates that come from useSyncExternalStore?
  • How would you add selector support on top of this hook?
  • What does getServerSnapshot have to do with hydration mismatches?

Tips

  • Define tearing in one sentence with an example. It is the heart of the question.
  • State the snapshot caching rule early. It is the most common bug.
  • Say that you would use a library built on it rather than write a store from scratch.
48.react-0048Hardsenior

What is hydration, what causes hydration mismatches, and how do you fix them?

Hydration attaches React to HTML that was already rendered on the server, reusing the existing DOM and adding event handlers. For it to work, the client's first render must produce the same output as the server's. A mismatch happens when something differs between the two, such as dates, random values, browser-only checks or invalid HTML nesting. Fix it by making the first render deterministic and moving client-only values into an effect.

Full answer

With server rendering, the server turns components into HTML so users see content before JavaScript loads. The page is not interactive yet. Hydration, started with hydrateRoot(container, <App />), walks the existing DOM next to the component tree, adopts the nodes and attaches handlers. It does not rebuild the DOM, which is why it is fast.

This works only if the first client render matches the server HTML. If a text node or an attribute differs, React cannot trust the markup. In React 19 it reports a recoverable error with a readable diff, through the onRecoverableError option, and falls back to client rendering for the affected part. The page works, but the user may see a flicker and you lose the benefit of server rendering.

The usual causes are:

  • Values that change between renders: Date.now(), new Date() formatted in a different time zone, Math.random(), or any counter written during render.
  • Branches on the environment: typeof window !== 'undefined' inside render shows one thing on the server and another in the browser.
  • Reading localStorage, cookies or media queries during the first render.
  • Invalid HTML nesting, such as a div inside a p, which the browser parser repairs differently from React's output.
  • Browser extensions or CDNs that modify the HTML before React hydrates.

Fixes: render a neutral value first and set the real value in a useEffect, which runs only on the client after hydration. Use useId for identifiers, because it gives the same id on both sides. Use useSyncExternalStore with a getServerSnapshot for browser data. For a single known difference, suppressHydrationWarning on that one element is acceptable, but use it sparingly. Frameworks also offer client-only wrappers.

The example renders on the server renderer, loads the HTML into the container and hydrates it.

jsx
import { Suspense, useEffect, useId, useState } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';

let ticket = 0;

function BadTicket() {
  ticket += 1; // impure: differs between the server and the client render
  return <p>Ticket {ticket}</p>;
}

function GoodYear() {
  const [year, setYear] = useState(null);
  useEffect(() => {
    setYear(2026); // client-only value, set after hydration
  }, []);
  return <p>Year: {year ?? '...'}</p>;
}

function LabelledField() {
  const id = useId(); // same id on server and client
  return (
    <div>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </div>
  );
}

function App() {
  return (
    <main>
      <Suspense fallback={<p>Loading ticket...</p>}>
        <BadTicket />
      </Suspense>
      <GoodYear />
      <LabelledField />
    </main>
  );
}

const container = document.getElementById('root');
container.innerHTML = renderToString(<App />);
console.log('server html: ' + container.innerHTML);

hydrateRoot(container, <App />, {
  onRecoverableError(error) {
    console.log('recoverable error: ' + error.message.split('\n')[0]);
  },
});

setTimeout(() => console.log('after hydration: ' + container.innerHTML), 80);

BadTicket renders Ticket 1 on the server and a different number on the client, so React reports a recoverable error and re-renders that part on the client. It sits inside a Suspense boundary, so only that part is regenerated, while GoodYear and LabelledField hydrate normally. This was run in jsdom with a React 19 development build. Output of the run: server html: <main><!--$--><p>Ticket <!-- -->1</p><!--/$--><p>Year: <!-- -->...</p><div><label for="_R_3_">Name</label><input id="_R_3_"></div></main> recoverable 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: after hydration: <main><p>Ticket 4</p><p>Year: <!-- -->2026</p><div><label for="_R_3_">Name</label><input id="_R_3_"></div></main>

Key points

  • Hydration reuses server HTML and attaches handlers. The first client render must match it.
  • Mismatches come from time, randomness, window checks, client-only storage and invalid nesting.
  • React 19 reports them through onRecoverableError and recovers by client rendering the part.
  • Fix with deterministic first renders, effects for client-only values, useId and getServerSnapshot.
  • suppressHydrationWarning is a last resort for single, harmless differences.

Common mistakes

  • Using Date.now(), Math.random() or new Date() in render of a server-rendered component.
  • Branching on typeof window inside render.
  • Reading localStorage during the first render.
  • Placing block elements inside paragraph elements.
  • Suppressing every warning instead of finding the difference.

Follow-ups

  • How does useSyncExternalStore with getServerSnapshot avoid mismatches?
  • What is selective hydration and how does Suspense enable it?
  • How would you render a time stamp in the user's time zone without a mismatch?

Tips

  • State the invariant: the first client render must equal the server HTML.
  • List the four common causes from memory. It signals real debugging experience.
  • Give the standard fix, a neutral first render plus an effect.
49.react-0049Hardsenior

What is the compound component pattern, and how would you design a flexible Tabs component with it?

Compound components are a set of components that work together and share implicit state, usually through context, so the consumer composes the parts in JSX, for example Tabs, Tabs.List, Tabs.Tab and Tabs.Panel. It gives users control over markup and order without a long list of props, and keeps the state logic inside the parent. It suits components with several related parts, such as tabs, accordions and menus.

Full answer

A single component with many props, such as <Tabs tabs={[...]} panels={[...]} renderTab={...} />, grows into a prop explosion. Every new layout need becomes another prop. Compound components turn the structure over to the consumer:

<Tabs defaultValue="marks"><Tabs.List><Tabs.Tab value="marks">Marks</Tabs.Tab></Tabs.List><Tabs.Panel value="marks">...</Tabs.Panel></Tabs>

The parent owns the state (which tab is active) and shares it through a context. The children read it with a hook. Because the parts are ordinary components, the consumer can wrap them, reorder them, add icons or put extra markup between them.

Design decisions that make it good. Throw a clear error if a part is used outside its parent, by checking the context. Support both controlled (value and onValueChange) and uncontrolled (defaultValue) use. Keep each part small and give it an accessible role: tablist, tab with aria-selected, tabpanel, plus keyboard navigation with arrow keys. Spread remaining props onto the underlying element so consumers can pass className and data attributes. Attach the parts as properties of the parent for discoverability (Tabs.Tab = Tab), or export them separately for better tree shaking.

Alternatives. A render-prop or a headless hook (useTabs) gives the logic without markup. Libraries such as Radix UI and React Aria use the compound approach for this reason. The trade-off is that the consumer can compose invalid combinations, so validate with the context check.

Context re-renders every part when the active tab changes, which is fine here because the set is small.

The example is a compact Tabs with an uncontrolled default and clear error handling.

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

const TabsContext = createContext(null);

function useTabs() {
  const context = useContext(TabsContext);
  if (context === null) {
    throw new Error('Tabs parts must be used inside <Tabs>');
  }
  return context;
}

function Tabs({ defaultValue, children }) {
  const [active, setActive] = useState(defaultValue);
  return <TabsContext value={{ active, setActive }}>{children}</TabsContext>;
}

function TabList({ children }) {
  return <div role="tablist">{children}</div>;
}

function Tab({ value, children }) {
  const { active, setActive } = useTabs();
  return (
    <button role="tab" aria-selected={active === value} onClick={() => setActive(value)}>
      {children}
    </button>
  );
}

function TabPanel({ value, children }) {
  const { active } = useTabs();
  return active === value ? <div role="tabpanel">{children}</div> : null;
}

Tabs.List = TabList;
Tabs.Tab = Tab;
Tabs.Panel = TabPanel;

export default function App() {
  return (
    <Tabs defaultValue="marks">
      <Tabs.List>
        <Tabs.Tab value="marks">Marks</Tabs.Tab>
        <Tabs.Tab value="attendance">Attendance</Tabs.Tab>
      </Tabs.List>
      <Tabs.Panel value="marks">Marks: 82 out of 100</Tabs.Panel>
      <Tabs.Panel value="attendance">Attendance: 91 percent</Tabs.Panel>
    </Tabs>
  );
}

Tabs holds the active value. Each part reads it from context and the consumer controls the structure. The check pressed each tab button once, so the last tab pressed is active. Rendered result: <div role="tablist"><button role="tab" aria-selected="false">Marks</button><button role="tab" aria-selected="true">Attendance</button></div><div role="tabpanel">Attendance: 91 percent</div>

Key points

  • Compound components share implicit state through context and let the consumer compose the parts.
  • They replace configuration-heavy props with flexible JSX structure.
  • Support controlled and uncontrolled use, and throw a clear error when a part is used outside its parent.
  • Add ARIA roles and keyboard handling for accessibility.
  • Headless hooks and libraries such as Radix and React Aria apply the same idea.

Common mistakes

  • Building the pattern with React.Children and cloneElement, which breaks when a consumer wraps a part in another component.
  • Forgetting to support controlled use.
  • No error when a part is used outside its parent.
  • Ignoring accessibility roles and keyboard support.
  • Creating a new context value object on every render of a large component set without considering the cost.

Follow-ups

  • Why is context better than cloneElement for this pattern?
  • How would you add keyboard navigation with arrow keys to the tab list?
  • When would you prefer a headless hook over compound components?

Tips

  • Show the target JSX first. It makes the design goal clear.
  • Mention controlled and uncontrolled support. It signals library-level thinking.
  • Reference real libraries (Radix, React Aria) as proof the pattern is established.
50.react-0050Hardsenior

How do you render a very large list efficiently in React, and how does virtualization (windowing) work?

Virtualization renders only the rows that are visible in the scroll container, plus a few extra, instead of all of them. It keeps the DOM small by calculating which items fall in the viewport from the scroll position and the row height, and by placing them with padding or absolute positioning inside a container as tall as the full list. Libraries such as TanStack Virtual and react-window handle the details, including variable heights.

Full answer

Rendering 10,000 rows creates 10,000 DOM nodes plus the work for React to create and update them. Mounting is slow, memory use is high, and every update that touches the list costs more. Most of those rows are off-screen.

Virtualization (or windowing) fixes this. The container has a fixed height and overflow: auto. Inside it, an element is given the height of the entire list, which is the item count times the row height, so the scrollbar is the right size. The component reads scrollTop, calculates the first visible index as Math.floor(scrollTop / rowHeight) and the last from the container height, adds an overscan of a few rows to avoid blank flashes, and renders only that slice. Each row is positioned at index * rowHeight, with absolute positioning or a transform.

With fixed heights the maths is trivial. Variable heights require measuring rows as they render and keeping a cache of sizes, which is what libraries do. Grids need the same idea in two dimensions.

Use a library in production. TanStack Virtual (a hook with no markup) and react-window are common. Hand-written versions miss keyboard focus, find-in-page, accessibility semantics, dynamic sizes and scroll restoration.

Trade-offs to mention. Browser find-in-page cannot find text that is not in the DOM. Screen readers need proper roles and counts, for example aria-rowcount. Items need stable keys so recycled rows keep the correct state.

Alternatives for lighter cases: pagination, infinite scroll with a limit, or the CSS property content-visibility: auto, which lets the browser skip rendering off-screen content, though it still keeps all nodes.

The example is a fixed-height windowed list of 10,000 rows, written by hand to show the arithmetic.

jsx
import { useState } from 'react';

const ROW_HEIGHT = 30;
const VIEWPORT_HEIGHT = 120;
const OVERSCAN = 2;
const rows = Array.from({ length: 10000 }, (_, i) => 'Student ' + (i + 1));

export default function VirtualList() {
  const [scrollTop, setScrollTop] = useState(0);

  const first = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN);
  const last = Math.min(
    rows.length - 1,
    Math.ceil((scrollTop + VIEWPORT_HEIGHT) / ROW_HEIGHT) + OVERSCAN
  );

  const visible = [];
  for (let index = first; index <= last; index++) {
    visible.push(
      <div
        key={index}
        role="listitem"
        style={{ position: 'absolute', top: index * ROW_HEIGHT, height: ROW_HEIGHT }}
      >
        {rows[index]}
      </div>
    );
  }

  return (
    <div
      role="list"
      style={{ height: VIEWPORT_HEIGHT, overflow: 'auto', position: 'relative' }}
      onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
    >
      <div style={{ height: rows.length * ROW_HEIGHT }}>{visible}</div>
    </div>
  );
}

Only the rows near the viewport are in the DOM, whatever the scroll position. The check scrolled to 3000 pixels, which is the row at index 100 (Student 101) with a row height of 30. With an overscan of two rows the DOM starts at Student 99. Output of the run (jsdom does no layout, so the scroll position was set by the check): at the top: 7 rows in the DOM, first is Student 1 after scrolling to 3000px: 9 rows in the DOM, first is Student 99

Key points

  • Virtualization renders only visible rows plus overscan, keeping the DOM small.
  • The container has the full list height. Row positions come from index times row height.
  • Variable heights need measurement and a size cache, which libraries provide.
  • Use TanStack Virtual or react-window in production, and handle accessibility and find-in-page limits.
  • content-visibility and pagination are lighter alternatives.

Common mistakes

  • Rendering all rows and trying to fix the slowness with memo alone.
  • Using the index as a key when the underlying data can reorder.
  • Forgetting overscan, which shows blank space during fast scrolling.
  • Hand-writing dynamic heights instead of using a library.
  • Ignoring accessibility roles and the loss of find-in-page.

Follow-ups

  • How would you support rows with variable height?
  • How would you keep keyboard focus on a row that scrolls out of the window?
  • When would pagination or content-visibility be better than virtualization?

Tips

  • Show the arithmetic (scrollTop divided by row height). It proves you understand the mechanism.
  • Recommend a library for production and name two.
  • Mention find-in-page and accessibility trade-offs. Seniors are expected to know them.
51.react-0051Easyfresher

How do you type props, children and event handlers in a React component with TypeScript?

Declare the props as a type or interface and annotate the function parameter. Use ReactNode for children, React's event types such as ChangeEvent<HTMLInputElement> for handlers, and a function type for callback props. You usually do not need React.FC. Let TypeScript infer the return type and the state type, and annotate only where inference is not enough.

Full answer

Typing a component means describing its inputs. Write a type for the props and use it on the parameter: function Badge({ label, tone }: BadgeProps). Optional props use a question mark. A prop that accepts only certain strings uses a union such as 'info' | 'warning', which gives autocomplete and compile errors for typos.

Children can be anything React renders: text, elements, arrays, null. The type for that is ReactNode. Add children: ReactNode to props that accept content. Use ReactElement only when you need exactly one element.

Event handlers have types from React: MouseEvent<HTMLButtonElement>, ChangeEvent<HTMLInputElement>, FormEvent<HTMLFormElement>, KeyboardEvent<HTMLInputElement>. The generic argument names the element, so event.currentTarget.value is typed as string. For a callback prop, type the function: onSelect: (id: number) => void. When the handler is written inline in JSX, TypeScript infers the event type from the attribute and you write no annotation.

React.FC is not required. It used to add implicit children, which was removed, and a plain function with typed props is simpler and works better with generics. Do not annotate the return type unless you want to restrict it.

To reuse the props of a native element, extend them: ComponentProps<'button'> gives every button attribute, and you can add your own.

Type checking happens at build time only. It does not validate data at runtime, so data from an API still needs validation with a schema library.

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

type Tone = 'info' | 'warning';

type BadgeProps = {
  label: string;
  tone?: Tone;
  children?: ReactNode;
};

function Badge({ label, tone = 'info', children }: BadgeProps) {
  return (
    <span data-tone={tone}>
      {label}
      {children}
    </span>
  );
}

type SaveButtonProps = ComponentProps<'button'> & { busy?: boolean };

function SaveButton({ busy = false, children, ...rest }: SaveButtonProps) {
  return (
    <button {...rest} disabled={busy || rest.disabled}>
      {busy ? 'Saving...' : children}
    </button>
  );
}

export default function Profile() {
  const [name, setName] = useState('');

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setName(event.currentTarget.value);
  }

  return (
    <div>
      <input value={name} onChange={handleChange} />
      <Badge label="Name length: " tone={name.length > 5 ? 'warning' : 'info'}>
        {name.length}
      </Badge>
      <SaveButton type="submit" onClick={() => console.log('saved ' + name)}>
        Save
      </SaveButton>
    </div>
  );
}

The file passed the TypeScript compiler in strict mode (tsc 7.0.2) and then ran after esbuild removed the types. The check typed a name and pressed Save. Output: saved Asha Rendered result: <div><input value="Asha"><span data-tone="info">Name length: 4</span><button type="submit">Save</button></div>

Key points

  • Describe props with a type or interface and annotate the parameter.
  • Use ReactNode for children, and unions for a closed set of strings.
  • Event types take the element as a generic: ChangeEvent<HTMLInputElement>.
  • Callback props are function types such as (id: number) => void.
  • React.FC is optional. ComponentProps<'button'> reuses native attributes.

Common mistakes

  • Typing event handlers with any, which loses currentTarget.value typing.
  • Using ReactElement for children and rejecting strings.
  • Copying a whole props interface instead of extending ComponentProps.
  • Trusting types for API data, which are not checked at runtime.
  • Using non-null assertions to silence errors that point to a real missing value.

Follow-ups

  • How do you type a component that accepts any native button attributes plus its own?
  • What is the difference between ReactNode and ReactElement?
  • How would you validate API data at runtime and derive the TypeScript type from it?

Tips

  • Show ReactNode and an event type. They are the two most common first questions.
  • Say React.FC is optional and why. It signals current practice.
  • Remember to say that types vanish at runtime.
52.react-0052Easyfresher

Explain the lifecycle of a class component (legacy knowledge that interviews still ask). Which methods exist and what is each for?

A class component mounts (constructor, render, componentDidMount), updates (render, getSnapshotBeforeUpdate, componentDidUpdate, optionally shouldComponentUpdate) and unmounts (componentWillUnmount). Errors use getDerivedStateFromError and componentDidCatch. New code uses function components, but classes remain in older codebases and error boundaries, so you should be able to read them.

Full answer

Class components are legacy for new work, yet many codebases have them and interviewers ask about the lifecycle to check you understand what hooks replaced.

Mounting: the constructor sets initial state and binds methods. render returns JSX and must be pure. componentDidMount runs once after the first commit, which is the place to start subscriptions, timers or requests.

Updating happens when props or state change. shouldComponentUpdate(nextProps, nextState) may return false to skip rendering (PureComponent does a shallow comparison for you). render runs again. getSnapshotBeforeUpdate reads the DOM just before it changes, for example a scroll position. componentDidUpdate(prevProps, prevState) runs after the commit. Compare with previous values before doing work, otherwise you get an infinite loop when you call setState there.

Unmounting: componentWillUnmount runs once before removal. Clean up what componentDidMount started.

Errors: static getDerivedStateFromError returns state to show a fallback, and componentDidCatch logs.

Names that were renamed or removed: componentWillMount, componentWillReceiveProps and componentWillUpdate carry the UNSAFE_ prefix because they misbehave with concurrent rendering. Do not use them.

setState is asynchronous and batched. When the next state depends on the previous, pass a function: this.setState((s) => ({ count: s.count + 1 })). Event handlers must be arrow functions or bound, otherwise this is undefined.

The mapping to hooks is useEffect for mount, update and cleanup, useState for state, and useMemo or memo for shouldComponentUpdate. The logs in the example show the order.

jsx
import { Component } from 'react';

class Timer extends Component {
  state = { seconds: 0 };

  componentDidMount() {
    console.log('mounted with step ' + this.props.step);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.seconds !== this.state.seconds) {
      console.log('updated: ' + prevState.seconds + ' to ' + this.state.seconds);
    }
  }

  componentWillUnmount() {
    console.log('unmounting at ' + this.state.seconds);
  }

  tick = () => {
    this.setState((s) => ({ seconds: s.seconds + this.props.step }));
  };

  render() {
    return <button onClick={this.tick}>Seconds: {this.state.seconds}</button>;
  }
}

export default class App extends Component {
  state = { show: true };

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ show: false })}>Remove timer</button>
        {this.state.show && <Timer step={5} />}
      </div>
    );
  }
}

The check pressed the remove button first, which unmounts the timer, so only the mount and unmount lines appear. Output: mounted with step 5 updated: 0 to 5 unmounting at 5

Key points

  • Mount: constructor, render, componentDidMount. Update: render, componentDidUpdate. Unmount: componentWillUnmount.
  • Compare previous and current values in componentDidUpdate before calling setState.
  • Use the functional form of setState when the next state depends on the previous.
  • UNSAFE_ lifecycle methods should not be used.
  • Hooks replaced this with useEffect, useState and memo. Error boundaries still require a class.

Common mistakes

  • Calling setState in componentDidUpdate without a condition, which loops forever.
  • Mutating this.state directly.
  • Forgetting to bind a normal method, so this is undefined.
  • Starting a subscription in componentDidMount and not removing it in componentWillUnmount.
  • Using the UNSAFE_ methods in new code.

Follow-ups

  • How does getDerivedStateFromProps differ from componentDidUpdate, and why is it rarely needed?
  • How would you convert this component to a function with hooks?
  • What does PureComponent do?

Tips

  • Say it is legacy, then show you know it well. That is the balanced answer.
  • Give the order of calls for mount and update.
  • Mention the hook equivalents at the end.
53.react-0053Easyfresher

What is a higher-order component (HOC), and why have hooks mostly replaced them? (legacy pattern)

A higher-order component is a function that takes a component and returns a new component with extra behaviour, such as `withAuth(Page)`. It was the main way to share logic between class components. Custom hooks now do this more simply, without wrapper nesting or prop name clashes. HOCs still appear in older code and some libraries, so you should be able to read and write one.

Full answer

A HOC is a function: const Enhanced = withSomething(Base). It does not change Base. It returns a new component that renders Base and passes extra props, or decides not to render it.

Before hooks, classes could not share stateful logic except through patterns like HOCs and render props. Examples are connect from older Redux, withRouter from older React Router, and permission wrappers such as withAuth.

How to write one properly: forward all props with {...props} so the wrapped component keeps working. Set a display name so React DevTools shows WithAuth(Page). Never create a HOC inside render, because every render would make a new component type and reset state. Copy static methods if needed, and forward refs deliberately, since ref is not a normal prop for older React versions (in React 19 it is a prop for function components).

Problems that hooks solve. Several HOCs wrapped around one component give a deep tree and hard-to-follow props. Two HOCs can inject the same prop name and overwrite each other. The source of a prop is not visible in the component, which makes it harder to read and to type.

A custom hook useAuth() is called inside the component, so the data source is explicit and there is no extra tree layer.

HOCs still make sense for cross-cutting wrappers that decide whether to render at all (feature flags, permission gates) and for code that must wrap class components. The example implements a permission wrapper.

jsx
function withPermission(Wrapped, required) {
  function WithPermission({ user, ...props }) {
    if (!user.permissions.includes(required)) {
      return <p>You do not have access.</p>;
    }
    return <Wrapped {...props} />;
  }
  WithPermission.displayName = 'WithPermission(' + (Wrapped.displayName || Wrapped.name) + ')';
  return WithPermission;
}

function Gradebook({ course }) {
  return <h2>Gradebook for {course}</h2>;
}

const TeacherGradebook = withPermission(Gradebook, 'grades:edit');

export default function App() {
  const teacher = { name: 'Asha', permissions: ['grades:edit'] };
  const student = { name: 'Ravi', permissions: [] };
  return (
    <div>
      <TeacherGradebook user={teacher} course="Maths" />
      <TeacherGradebook user={student} course="Maths" />
      <p>{TeacherGradebook.displayName}</p>
    </div>
  );
}

withPermission returns a new component that either renders the wrapped one or a message. Rendered result: <div><h2>Gradebook for Maths</h2><p>You do not have access.</p><p>WithPermission(Gradebook)</p></div>

Key points

  • A HOC is a function from a component to an enhanced component.
  • Forward all props, set a display name and never create a HOC during render.
  • Drawbacks: wrapper nesting, prop name collisions and hidden data sources.
  • Custom hooks are the modern way to share stateful logic.
  • HOCs remain useful for gates that decide whether to render.

Common mistakes

  • Creating a HOC inside a component, which remounts it on every render.
  • Not forwarding props to the wrapped component.
  • Forgetting displayName, which makes DevTools output unreadable.
  • Letting two HOCs inject the same prop name.
  • Using a HOC for logic that a custom hook handles more clearly.

Follow-ups

  • How would you rewrite withPermission as a hook or a small gate component?
  • Why does calling a HOC inside render lose state?
  • How do HOCs interact with refs in React 19?

Tips

  • Label it legacy, but show you can still write one safely.
  • Name the three problems (nesting, collisions, hidden source). It shows you understand why hooks won.
  • Mention that gate wrappers are the case where HOCs still fit.
54.react-0054Easyfresher

What is the render props pattern, how does it compare with hooks, and when is it still useful? (legacy-ish pattern)

A render prop is a prop whose value is a function that a component calls to decide what to render, so the component shares its state or behaviour while the caller controls the markup. Hooks replaced most uses, because a hook shares logic without extra nesting. The pattern still fits cases where the component owns a piece of UI structure, such as lists, virtualized rows and headless components.

Full answer

The idea is simple. Instead of a component rendering fixed markup, it receives a function and calls it with data: <MouseTracker render={(pos) => <p>{pos.x}</p>} />. The children prop can carry the function too, which is called function as children.

This pattern solved logic sharing for class components. The tracking logic lives in one component. The caller decides how to display the numbers. It is explicit about where data comes from, unlike a HOC, but it can create "callback pyramids" when several render props are nested.

A custom hook gives the same logic without any wrapper: const pos = useMousePosition(). For logic-only sharing, prefer the hook.

Render props are still good when the component must call your function many times or at specific places in its own structure. A list that renders each row, a virtualized list, a table cell renderer, a form library field wrapper (<Field>{({ value, onChange }) => ...}</Field>), and headless components such as dropdown or combobox primitives all fit. The component owns the structure and behaviour, and the caller owns what each part looks like.

Keep the function cheap and stable where it matters. A new inline function on every render defeats memo on the component receiving it. Give the render function a clear argument object that is easy to extend.

The example implements a counter with a render prop and the hook form side by side.

jsx
import { useState } from 'react';

function Counter({ initial = 0, children }) {
  const [count, setCount] = useState(initial);
  return children({ count, increment: () => setCount((c) => c + 1) });
}

function useCounter(initial = 0) {
  const [count, setCount] = useState(initial);
  return { count, increment: () => setCount((c) => c + 1) };
}

function HookVersion() {
  const { count, increment } = useCounter(10);
  return <button onClick={increment}>Hook: {count}</button>;
}

export default function App() {
  return (
    <div>
      <Counter>
        {({ count, increment }) => <button onClick={increment}>Render prop: {count}</button>}
      </Counter>
      <HookVersion />
    </div>
  );
}

Both buttons share the same logic. The first uses a function as children and the second a custom hook. The check pressed each button once. Rendered result: <div><button>Render prop: 1</button><button>Hook: 11</button></div>

Key points

  • A render prop is a function prop the component calls to render part of its output.
  • It shares logic while the caller controls markup. Hooks now cover logic-only sharing.
  • Deep nesting of render props is hard to read.
  • It still suits lists, rows, cell renderers and headless UI parts.
  • Inline render functions create new references and can defeat memo.

Common mistakes

  • Using render props for logic that a hook shares more simply.
  • Nesting several render props, which creates a callback pyramid.
  • Passing a new inline function to a memoized component and defeating memo.
  • Calling the render function with inconsistent arguments between renders.

Follow-ups

  • How would you convert the Counter to a custom hook, and what would you lose?
  • Where have you seen function-as-children in popular libraries?
  • How do render props compare with compound components?

Tips

  • Show the same logic as a hook. It proves you understand why the pattern faded.
  • Name the cases where it still wins.
  • Use the term "function as children" so interviewers see you know both spellings.
55.react-0055Easyfresher

What does useId do, and why should you use it instead of hard-coded or random ids?

useId generates a unique, stable id string for a component instance. It gives the same value on the server and in the browser, so it is safe for server rendering and hydration. Use it to connect a label to an input with htmlFor and id, or for aria attributes, especially in a component that can appear many times on a page. Do not use it for list keys.

Full answer

Accessible forms need an id on the input and a label that points to it with htmlFor. If a component hard-codes id="email", then two copies on the same page create duplicate ids, which breaks label clicks and screen reader links. Random ids from Math.random differ between server and client, which causes hydration mismatches.

const id = useId() returns a string that is unique within the app and stable between server and client renders, because it is derived from the component's position in the tree. In React 19 it looks like _r_1_, and the format is not a promise, so treat it as opaque. Never use it as a CSS selector without escaping, since the characters may need escaping.

To make several ids from one call, add a suffix: id + '-error'. This is the pattern for linking an error message with aria-describedby.

useId is for accessibility and DOM linking. It is not for list keys, which should come from your data, and not for database ids. It is also not guaranteed to be unique across separate React roots, so pass identifierPrefix to createRoot if you run several apps on a page.

Design tip: build a small Field component that takes a label and renders the input with an id from useId. Every form then gets correct labelling by default.

The example builds that field, with a hint and an error message linked through aria-describedby.

jsx
import { useId } from 'react';

function Field({ label, hint, error }) {
  const id = useId();
  const hintId = id + '-hint';
  const errorId = id + '-error';

  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input
        id={id}
        aria-invalid={error ? 'true' : 'false'}
        aria-describedby={error ? errorId : hintId}
      />
      {error ? (
        <p id={errorId} role="alert">
          {error}
        </p>
      ) : (
        <p id={hintId}>{hint}</p>
      )}
    </div>
  );
}

export default function App() {
  return (
    <form>
      <Field label="Email" hint="We never share it" />
      <Field label="Backup email" hint="Optional" error="Enter a valid address" />
    </form>
  );
}

Two copies of the same component get different ids, so each label points to its own input. The id format is internal to React and the exact text may change. Rendered result: <form><div><label for="_r_0_">Email</label><input id="_r_0_" aria-invalid="false" aria-describedby="_r_0_-hint"><p id="_r_0_-hint">We never share it</p></div><div><label for="_r_1_">Backup email</label><input id="_r_1_" aria-invalid="true" aria-describedby="_r_1_-error"><p id="_r_1_-error" role="alert">Enter a valid address</p></div></form>

Key points

  • useId gives a unique id that is the same on the server and client.
  • Use it for htmlFor, aria-describedby and similar linked attributes.
  • Build suffixed ids from one call, such as id + '-error'.
  • Do not use it for list keys or as a data id.
  • Multiple React roots on one page need identifierPrefix.

Common mistakes

  • Hard-coding ids in a reusable component.
  • Using Math.random or a counter for ids in a server-rendered app.
  • Using useId for list keys.
  • Using the id in a CSS selector without escaping its characters.
  • Calling useId conditionally.

Follow-ups

  • Why does a random id cause a hydration mismatch?
  • How would you connect an error message to an input for screen readers?
  • What is identifierPrefix and when do you need it?

Tips

  • Link the answer to accessibility. That is the real purpose.
  • Mention hydration safety to show you understand the server side.
  • Give the suffix pattern for error and hint text.
56.react-0056Easyfresher

What are the common ways to style React components, and how do you choose between them?

The main options are plain CSS files, CSS Modules, utility classes such as Tailwind, CSS-in-JS libraries and inline style objects. CSS Modules and utility classes have no runtime cost and avoid global name clashes. Runtime CSS-in-JS gives dynamic styles but costs performance and has weak support with Server Components. Inline styles suit a few dynamic values only. Choose by team habits, build tooling and server rendering needs.

Full answer

React does not decide how you style. It only renders className and style props. Each approach trades something.

Plain CSS with global class names is simple, but names collide in a large app and dead code is hard to find. A naming convention such as BEM reduces the problem.

CSS Modules scope class names per file at build time: styles.button becomes a unique class. There is no runtime work, normal CSS syntax is kept and server rendering works well. Dynamic variants use a class switch or CSS custom properties.

Utility-first CSS such as Tailwind composes small classes in markup. There is no naming and the output CSS is small, but markup gets long, so teams extract components. It works with Server Components.

CSS-in-JS libraries (styled-components, Emotion) write CSS in JavaScript with props-based styling. Runtime versions add JavaScript work during render and are harder to use with Server Components and streaming, so many teams moved to zero-runtime options (Vanilla Extract, Panda, Linaria) that extract CSS at build time.

Inline style objects (style={{ color }}) have no pseudo-classes, media queries or cascade, and a new object each render. They are right for values that truly change at runtime, such as a width from state. A good combination is classes for structure and CSS custom properties set inline for dynamic values: style={{ '--progress': '40%' }}.

Whatever you pick, keep design tokens (colours, spacing) in one place and make components accept a className so callers can adjust them.

The example uses a class for structure and a custom property for the dynamic value.

jsx
const css = `
.bar { background: #eee; height: 8px; }
.bar > span { display: block; height: 100%; width: var(--progress); background: teal; }
`;

function ProgressBar({ percent, className = '' }) {
  return (
    <div className={'bar ' + className} style={{ '--progress': percent + '%' }}>
      <span />
    </div>
  );
}

export default function App() {
  return (
    <div>
      <style>{css}</style>
      <ProgressBar percent={40} />
      <ProgressBar percent={85} className="wide" />
    </div>
  );
}

Structure lives in CSS and the changing value is passed through a custom property. A real project would keep the CSS in a file or a CSS Module. Rendered result: <div><style> .bar { background: #eee; height: 8px; } .bar > span { display: block; height: 100%; width: var(--progress); background: teal; } </style><div class="bar " style="--progress: 40%;"><span></span></div><div class="bar wide" style="--progress: 85%;"><span></span></div></div>

Key points

  • React renders className and style. The styling system is your choice.
  • CSS Modules and utility classes have no runtime cost and suit server rendering.
  • Runtime CSS-in-JS costs render time and complicates Server Components. Zero-runtime options avoid it.
  • Inline styles lack pseudo-classes and media queries. Use them for a few dynamic values.
  • Classes plus inline CSS custom properties is a clean way to handle dynamic values.

Common mistakes

  • Using inline style objects for everything and losing hover states and media queries.
  • Using runtime CSS-in-JS in a Server Components app without checking support.
  • Letting components ignore className so they cannot be adjusted.
  • Mixing three styling systems in one project.
  • Hard-coding colours instead of using tokens.

Follow-ups

  • Why is runtime CSS-in-JS a problem for Server Components?
  • How do CSS Modules produce unique class names?
  • How would you build a theme with CSS custom properties and a toggle?

Tips

  • Compare by runtime cost and server rendering support. Those are the real differences.
  • Do not argue for one tool. Show a decision rule.
  • Mention CSS custom properties for dynamic values. It is a modern, practical answer.
57.react-0057Mediummid

How does React protect against cross-site scripting (XSS), and where can you still introduce it?

React escapes values placed in JSX, so a string such as an img tag with an onerror handler is shown as text, not run. XSS returns when you bypass that: dangerouslySetInnerHTML with untrusted HTML, javascript: URLs in href, building HTML strings, or injecting unsafe values into places React does not escape, such as script content. Sanitize with a library like DOMPurify, validate URLs, and use a Content Security Policy as a second layer.

Full answer

XSS means an attacker gets their JavaScript to run in your user's session, usually through content you display: a comment, a profile bio, a query parameter. The script can read tokens that are available to JavaScript and act as the user.

JSX protects you by default. {userInput} becomes a text node, so markup characters are escaped. This is why most React apps are safe from the common case.

The ways around it:

  • dangerouslySetInnerHTML={{ __html: html }} inserts raw HTML. The name is a warning. If html contains untrusted content, it can contain scripts or event handler attributes. Sanitize first with DOMPurify, ideally on the server too, and prefer rendering Markdown through a parser configured to disallow raw HTML.
  • URLs. <a href={userUrl}> accepts a javascript: URL, which runs when clicked. Allow only http, https and mailto by parsing the URL and checking the protocol. React 19 still warns about javascript: URLs, but warnings are not protection.
  • Direct DOM writes with innerHTML or document.write in effects, and eval or new Function on user data.
  • Server-rendered pages that embed JSON in a script tag without escaping the closing tag sequence.
  • Third-party scripts and dependencies, which run with full rights. Use subresource integrity and audit packages.

Defence in depth: a Content Security Policy that blocks inline scripts limits the damage of a missed case. Store session tokens in HttpOnly cookies, so scripts cannot read them. Keep user-controlled data away from style and URL contexts.

The example shows plain text, a sanitized fragment and a URL check.

jsx
import DOMPurify from 'dompurify';

const untrusted = '<img src="x" onerror="stealCookies()"><b>Bold</b>';

function safeHref(url) {
  try {
    const parsed = new URL(url, 'https://example.com');
    return ['http:', 'https:', 'mailto:'].includes(parsed.protocol) ? parsed.href : '#';
  } catch {
    return '#';
  }
}

function Comment({ html }) {
  return <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />;
}

export default function App() {
  return (
    <div>
      <p>{untrusted}</p>
      <Comment html={untrusted} />
      <a href={safeHref('javascript:alert(1)')}>Blocked link</a>
      <a href={safeHref('https://schoolabe.com')}>Allowed link</a>
    </div>
  );
}

The first line is escaped text. The second goes through DOMPurify, which removes the onerror attribute. The unsafe link becomes a hash. This used the dompurify package with jsdom. Rendered result: <div><p>&lt;img src="x" onerror="stealCookies()"&gt;&lt;b&gt;Bold&lt;/b&gt;</p><div><img src="x"><b>Bold</b></div><a href="#">Blocked link</a><a href="https://schoolabe.com/">Allowed link</a></div>

Key points

  • JSX escapes text by default, which blocks most XSS.
  • dangerouslySetInnerHTML needs sanitized HTML. DOMPurify is the usual tool.
  • Validate URL protocols to block javascript: links.
  • Avoid innerHTML, eval and unescaped JSON in script tags.
  • Add a Content Security Policy and HttpOnly cookies as extra layers.

Common mistakes

  • Using dangerouslySetInnerHTML with unsanitized API content.
  • Checking URLs with a string prefix test instead of parsing them.
  • Believing a framework makes every output safe.
  • Storing tokens in localStorage where any injected script can read them.
  • Sanitizing only on the client when the HTML is stored and reused elsewhere.

Follow-ups

  • What does a Content Security Policy add if sanitization already runs?
  • Why are HttpOnly cookies safer for session tokens?
  • How would you render user-written Markdown safely?

Tips

  • Start from "JSX escapes by default", then list the exceptions. It shows you know the baseline.
  • Name DOMPurify and URL protocol checks as concrete defences.
  • Mention CSP and cookies as defence in depth.
58.react-0058Easyfresher

Build a todo list with add, toggle, delete and filter using useReducer. Explain your state shape and actions.

Keep one state object with the todos array, a next id and the filter. A pure reducer handles actions such as added, toggled, deleted and filter-changed. The component dispatches actions from handlers and derives the visible list from the state during render. Do not store the filtered list in state.

Full answer

Start with the state. Each todo has an id, text and done flag. Besides the list, the screen needs the current filter ("all", "active" or "done") and a source of new ids. Keeping nextId in state avoids random ids and makes the reducer pure and testable.

Actions describe events: added with text, toggled with an id, deleted with an id, and filtered with a value. The reducer returns a new state for each: spread the old state, and use map and filter for the list so nothing is mutated. Ignore blank text in the added case so the UI cannot create empty items.

The component dispatches in event handlers. The form uses onSubmit and a controlled input for the text. After adding, reset the input. The list uses the todo id as the key.

The visible todos are derived: todos.filter(...) according to the filter, calculated in render. Storing it would duplicate data and invite bugs.

Extras that interviewers may ask. Persist to localStorage in an effect keyed on the todos. Use useReducer's lazy init to read saved data once. Add undo by keeping a history array. Move to a store if the list is needed in many places. Accessibility: a label for the input, real checkboxes and buttons with names that include the todo text.

The reducer here is a plain function, so you can test it without React.

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

const initialState = { nextId: 1, filter: 'all', todos: [] };

function todoReducer(state, action) {
  switch (action.type) {
    case 'added': {
      const text = action.text.trim();
      if (text === '') return state;
      return { ...state, nextId: state.nextId + 1, todos: [...state.todos, { id: state.nextId, text, done: false }] };
    }
    case 'toggled':
      return { ...state, todos: state.todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t)) };
    case 'deleted':
      return { ...state, todos: state.todos.filter((t) => t.id !== action.id) };
    case 'filtered':
      return { ...state, filter: action.filter };
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

export default function TodoApp() {
  const [state, dispatch] = useReducer(todoReducer, initialState);
  const [text, setText] = useState('');

  const visible = state.todos.filter((t) => {
    if (state.filter === 'active') return !t.done;
    if (state.filter === 'done') return t.done;
    return true;
  });

  function handleSubmit(event) {
    event.preventDefault();
    dispatch({ type: 'added', text });
    setText('');
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={text} onChange={(e) => setText(e.target.value)} aria-label="New todo" />
        <button type="submit">Add</button>
      </form>
      <div>
        {['all', 'active', 'done'].map((f) => (
          <button key={f} onClick={() => dispatch({ type: 'filtered', filter: f })} aria-pressed={state.filter === f}>
            {f === 'all' ? 'All' : f === 'active' ? 'Active' : 'Done'}
          </button>
        ))}
      </div>
      <ul>
        {visible.map((t) => (
          <li key={t.id}>
            <input type="checkbox" checked={t.done} onChange={() => dispatch({ type: 'toggled', id: t.id })} aria-label={'Done: ' + t.text} />
            {t.text}
            <button onClick={() => dispatch({ type: 'deleted', id: t.id })}>Delete {t.text}</button>
          </li>
        ))}
      </ul>
      <p>{state.todos.filter((t) => !t.done).length} left</p>
    </div>
  );
}

The check added two todos, ticked the first, switched to the Active filter and deleted the second. Output of the run: after adding two and checking the first: Buy pensDelete Buy pensRead chapter 4Delete Read chapter 4 | 1 left Active filter: Read chapter 4Delete Read chapter 4 | 1 left after deleting the second: | 0 left

Key points

  • State shape: todos, nextId and filter in one object.
  • Actions describe events and the reducer returns new state without mutation.
  • Derive the visible list in render. Do not store it.
  • Use the todo id as the key and real inputs and buttons for accessibility.
  • A pure reducer is easy to test and to persist.

Common mistakes

  • Mutating the todos array in the reducer with push or splice.
  • Storing the filtered list in state.
  • Using the array index as the key for items that can be deleted.
  • Generating ids with Math.random in the reducer, which makes it impure.
  • Forgetting event.preventDefault() on form submit.

Follow-ups

  • How would you persist the list to localStorage and restore it?
  • How would you add undo and redo?
  • How would you write a unit test for the reducer?

Tips

  • Describe the state shape and actions before coding. Interviewers read that as design skill.
  • Keep derived data out of state and say so.
  • Offer persistence and undo as extensions without starting them unprompted.
59.react-0059Easyfresher

Implement client-side pagination for a list. How do you calculate the visible page and handle the edges?

Store only the current page number. Derive the total pages with Math.ceil(total / pageSize) and the visible items with slice((page - 1) * pageSize, page * pageSize). Disable Previous on the first page and Next on the last. Clamp the page if the list shrinks. For large or remote data, ask the server for one page at a time and keep the page in the URL.

Full answer

Pagination is an exercise in derived state. The only value that changes is the page. Everything else is a calculation: page count, the start and end index, and the items to show.

With page numbers starting at 1, the slice starts at (page - 1) * pageSize and ends at page * pageSize. The page count is Math.ceil(items.length / pageSize). Twenty-five items with a page size of ten give three pages, and the last page has five items.

Edge cases make the difference in an interview. Disable Previous on page 1 and Next on the last page, so state can never leave the valid range. When the list changes length, for example after filtering, the current page may no longer exist, so clamp it with Math.min(page, pageCount) or reset to 1. An empty list should show an empty state and "Page 1 of 1" rather than "Page 1 of 0".

Show where the user is: "Page 2 of 3" and the range "11 to 20 of 25". Give the nav element an aria-label and keep button text meaningful.

Client-side slicing is fine for hundreds of items. For thousands or remote data, request one page from the API (?page=2&limit=10), keep the page in the URL's search params so links and the back button work, and use a query library with keepPreviousData behaviour to avoid flashing a blank list between pages. For a feed that grows, use infinite scroll instead.

Putting the page into a state variable and deriving the rest avoids bugs where the stored slice and the page disagree.

jsx
import { useState } from 'react';

const students = Array.from({ length: 25 }, (_, i) => 'Student ' + (i + 1));
const PAGE_SIZE = 10;

export default function PagedList() {
  const [page, setPage] = useState(1);

  const pageCount = Math.max(1, Math.ceil(students.length / PAGE_SIZE));
  const safePage = Math.min(page, pageCount);
  const start = (safePage - 1) * PAGE_SIZE;
  const visible = students.slice(start, start + PAGE_SIZE);

  return (
    <div>
      <ul>
        {visible.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>
      <nav aria-label="Pagination">
        <button onClick={() => setPage(safePage - 1)} disabled={safePage === 1}>
          Previous
        </button>
        <button onClick={() => setPage(safePage + 1)} disabled={safePage === pageCount}>
          Next
        </button>
      </nav>
      <p>
        Page {safePage} of {pageCount}: showing {start + 1} to {start + visible.length} of {students.length}
      </p>
    </div>
  );
}

The check pressed Next twice (reaching the short last page), a third time (the button is disabled, so nothing changes), and then Previous. Output of the run: start: Student 1Student 2Student 3Student 4Student 5Student 6Student 7Student 8Student 9Student 10 | Page 1 of 3: showing 1 to 10 of 25 after two Next: Student 21Student 22Student 23Student 24Student 25 | Page 3 of 3: showing 21 to 25 of 25 after a third Next: Student 21Student 22Student 23Student 24Student 25 | Page 3 of 3: showing 21 to 25 of 25 after Previous: Student 11Student 12Student 13Student 14Student 15Student 16Student 17Student 18Student 19Student 20 | Page 2 of 3: showing 11 to 20 of 25

Key points

  • Store only the page. Derive page count and visible items.
  • Slice from (page - 1) * pageSize to page * pageSize.
  • Disable the buttons at the edges and clamp the page when the list shrinks.
  • Handle the empty list explicitly.
  • For remote data, fetch per page and keep the page in the URL.

Common mistakes

  • Using 0-based and 1-based page numbers inconsistently.
  • Allowing Next on the last page and showing an empty page.
  • Storing the sliced list in state.
  • Not clamping the page after the data shrinks.
  • Showing "Page 1 of 0" for an empty list.

Follow-ups

  • How would you move this to server-side pagination with a query library?
  • How would you keep the page in the URL?
  • When would you choose infinite scroll over pages?

Tips

  • Show the arithmetic for slice and page count out loud.
  • Name the edge cases (first page, last page, empty list) before the interviewer asks.
  • Mention URL state for shareable links.
60.react-0060Easyfresher

What are the accessibility basics every React developer should apply, and why is semantic HTML better than adding ARIA to a div?

Use the right HTML element first: button for actions, a for navigation, label with input, headings in order, nav and main landmarks, and alt text on images. Native elements bring keyboard support, focus and roles for free. ARIA only adds meaning and never adds behaviour, so a div with role="button" still needs tabIndex, key handlers and styling. Use ARIA when no native element fits.

Full answer

Accessibility means people using keyboards, screen readers, zoom or voice control can use your app. In React it is mostly the same as in HTML, because JSX renders real elements.

A native <button> is focusable, activates with Enter and Space, announces itself as a button, and can be disabled. A <div onClick> has none of that. To imitate it you need role, tabIndex, key handlers and focus styles, and you will usually miss one. So choose the element by what it does: button for actions, <a href> for navigation, <input> with a <label> for fields, <ul> for lists, <table> for data.

Page structure matters. Use landmarks (header, nav, main, footer) so screen reader users can jump around, and keep heading levels in order. Give images meaningful alt text, or alt="" when they are decorative. Make sure text has enough colour contrast and the layout works at 200 percent zoom.

Keyboard use: every interactive element must be reachable with Tab in a sensible order, and the focus indicator must be visible. Avoid positive tabIndex values. Do not trap focus except in a modal.

ARIA fills gaps: aria-label names an icon-only button, aria-pressed shows a toggle state, aria-expanded shows an open menu, and aria-live announces updates. The first rule of ARIA is to use a native element when one exists.

In React, use htmlFor, aria-* attributes in kebab-case and tabIndex in camelCase. Lint with eslint-plugin-jsx-a11y and test with a screen reader as well.

jsx
import { useState } from 'react';

export default function Toolbar() {
  const [bold, setBold] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <div>
      <header>
        <nav aria-label="Main">
          <a href="/courses">Courses</a>
        </nav>
      </header>
      <main>
        <h1>Notes editor</h1>
        <button aria-pressed={bold} onClick={() => setBold(!bold)}>
          Bold
        </button>
        <button aria-expanded={menuOpen} aria-controls="more" onClick={() => setMenuOpen(!menuOpen)}>
          More options
        </button>
        {menuOpen && <ul id="more"><li>Italic</li><li>Underline</li></ul>}
        <button aria-label="Delete note">
          <svg aria-hidden="true" width="12" height="12"><path d="M0 0L12 12" /></svg>
        </button>
        <img src="/chart.png" alt="Bar chart of marks by subject" />
        <label>
          Title <input />
        </label>
      </main>
    </div>
  );
}

Every control is a native element with a name. State is exposed with aria-pressed and aria-expanded, and the decorative icon is hidden. The check pressed each button once. Rendered result: <div><header><nav aria-label="Main"><a href="/courses">Courses</a></nav></header><main><h1>Notes editor</h1><button aria-pressed="true">Bold</button><button aria-expanded="true" aria-controls="more">More options</button><ul id="more"><li>Italic</li><li>Underline</li></ul><button aria-label="Delete note"><svg aria-hidden="true" width="12" height="12"><path d="M0 0L12 12"></path></svg></button><img alt="Bar chart of marks by subject" src="/chart.png"><label>Title <input></label></main></div>

Key points

  • Choose the element by purpose: button, a, label and input, lists, tables.
  • Native elements give keyboard behaviour, focus and role for free.
  • Landmarks, ordered headings and alt text structure the page.
  • ARIA adds meaning, not behaviour. Use it only when no native element fits.
  • Test with the keyboard, a linter and a screen reader.

Common mistakes

  • Using div or span with onClick for buttons.
  • Removing the focus outline without a replacement.
  • Skipping heading levels for visual size.
  • Putting aria-label on elements that already have visible text, which can conflict.
  • Adding ARIA roles that contradict the native role.

Follow-ups

  • What is the first rule of ARIA?
  • How would you make an icon-only button accessible?
  • How do you test accessibility automatically, and what can't tools catch?

Tips

  • Lead with "native element first". It is the best one-line answer.
  • Mention keyboard and focus, not only screen readers.
  • Name one linter or tool to show real practice.