🎓 A1Learner
🔍

Home / Blog / Programming / React

Top 50 React Interview Questions with Answers

Programming · React · 39 min read

Fifty React interview questions with answers, from hooks and state to React 19. Every example rendered for real with React 19.3.1.

How this sheet works

This sheet holds fifty React interview questions, sorted by topic. The opening ten cover the core ideas: components, JSX, props, state, and how React turns a list into HTML. Hooks follow, first the core set and then the traps that catch experienced developers. Performance and state management come after those. React 19 closes the theory, and testing and TypeScript end the sheet.

Each program on this page ran for real with React 19.3.1 and react-dom/server, the same versions the React Beginner course uses. The markup shown beside each program is the markup that run printed, word for word. A static render runs no effects, so effect programs show the first render and say so. A click or a typed letter is shown as a second variant rendered with the changed state value, the same standard the course uses. One program is a model of update logic, not a live click: it computes what three stale updates and three functional updates each leave behind.

Go through the questions one by one. Say your answer aloud before reading the one written here, then run the program beside it. Speaking an answer and running its program fixes the idea far better than reading the page straight through.

The ideas here rest on one course. React Beginner covers the ground: components, props, events, state, hooks, lists, forms, and fetching data. Where an answer leans on a lesson, that lesson is named. The Top 50 JavaScript Interview Questions with Answers sheet covers the language underneath: closures, the event loop, and promises.

Three limits are worth stating. This sheet renders components on the server for checking, so it never shows a live browser click. Server Components are explained, not run: they need a framework, and this sheet has none. And it never teaches routing or styling in depth. Those belong to their own courses.

1. What is React?

React is a JavaScript library that builds user interfaces. A user interface is what a person sees and uses on a web page: the buttons, the text, the lists, the forms. React builds it from JavaScript functions that hand back markup, and the browser shows the result.

React works in components. A component is a small function that returns the markup for one piece of a page. Small components join into larger ones, and the page is the tree they form.

React is a library, not a framework. A framework decides the shape of the whole application. React decides only how the interface is built. Routing, data fetching, and styling come from other tools, chosen by the team.

2. What is a component?

A component is a JavaScript function that hands back the markup for one piece of a page. Its name starts with a capital letter. React reads a capitalised name as a component and a lowercase name as a plain HTML tag.

A component takes in props and returns what the page should show. The same component can render many times with different props. Each render is independent, with its own props and its own state.

The program below defines a Greeting component and renders it once with the name Asha. The printed markup is one heading. The Your First React Component lesson builds the same shape from scratch.

function Greeting({ name }) {
  return <h1>Hello, {name}</h1>;
}

export default function App() {
  return <Greeting name="Asha" />;
}

Output:
<h1>Hello, Asha</h1>

3. What is JSX?

JSX is a way of writing markup inside JavaScript. It looks like HTML, but it runs as JavaScript. A build step turns it into plain function calls before the browser ever sees it.

JSX takes expressions inside curly braces. Any JavaScript value can sit between the braces: a variable, a calculation, or a function call. The expression is worked out first, and its result goes into the markup.

The program below puts the sum 2 + 2 inside braces. The printed markup reads Two plus two is 4. The JSX Introduction and JSX Expressions lessons show the same pattern with variables and function calls.

export default function App() {
  const total = 2 + 2;
  return <p>Two plus two is {total}.</p>;
}

Output:
<p>Two plus two is 4.</p>

4. What is the difference between props and state?

Props are values a parent passes down to a child. State is a value a component owns and can change. Props flow one way, from parent to child. State lives inside one component.

A component cannot change its own props. Props are read-only, like function arguments. A component changes its state with a setter function, and React re-renders it with the new value.

The program below shows both at once. The name Asha arrives as a prop. The count starts at 0 in state. The printed line reads Asha has 0 open tasks. The Props Introduction and useState Introduction lessons teach each half.

import { useState } from 'react';

function TaskCount({ name }) {
  const [count] = useState(0);
  return <p>{name} has {count} open tasks.</p>;
}

export default function App() {
  return <TaskCount name="Asha" />;
}

Output:
<p>Asha has 0 open tasks.</p>

5. What is the Virtual DOM, and how does reconciliation work?

The Virtual DOM is a plain JavaScript copy of the page that React keeps in memory. It is a tree of lightweight objects, not real browser nodes. React compares the new tree with the old one after every render.

Reconciliation is that comparison. React walks the two trees together and notes what changed. It changes only the real DOM nodes that differ, and leaves the rest alone. A list that gains one item gets one new node, not a fresh list.

Reconciliation is fast because it compares by position and type. Two elements of the same type at the same spot are compared child by child. Two elements of different types are torn down and rebuilt. Keys tell React which list items are the same item, which is the subject of the next question.

6. What are keys, and why do lists need them?

A key is a short string that marks one item in a list as itself. React reads keys when a list changes. A stable key says this item is the same item as before, even if it moved.

Keys must be stable and unique among siblings. A database id is a good key. An array index is a poor one, because the index follows the position, not the item. Reordering a list keyed by index makes React reuse the wrong nodes.

The program below renders three tasks, each keyed by its id. The printed list reads Buy milk, Walk the dog, Read ten pages. The Keys in Lists lesson states the same rule: a good key comes from the data itself, such as an id.

const tasks = [
  { id: 't1', text: 'Buy milk' },
  { id: 't2', text: 'Walk the dog' },
  { id: 't3', text: 'Read ten pages' },
];

export default function App() {
  return (
    <ul>
      {tasks.map((task) => <li key={task.id}>{task.text}</li>)}
    </ul>
  );
}

Output:
<ul><li>Buy milk</li><li>Walk the dog</li><li>Read ten pages</li></ul>

7. What is the difference between a controlled and an uncontrolled input?

A controlled input takes its value from React state. Every keystroke updates the state, and the state writes the value back into the input. React owns the text, and the input only shows it.

An uncontrolled input keeps its own value in the DOM. React reads it when it needs it, usually through a ref. The input owns the text, and React asks for it on submit.

The program below renders a controlled input with the value Asha. The printed markup carries value equals Asha. Controlled inputs suit forms that check each keystroke. Uncontrolled inputs suit simple forms read once at the end. The Controlled Inputs lesson builds a controlled form step by step.

import { useState } from 'react';

export default function App() {
  const [name] = useState('Asha');
  return <input value={name} onChange={() => {}} />;
}

Output:
<input value="Asha"/>

8. How does conditional rendering work?

Conditional rendering shows different markup for different values. The tool is ordinary JavaScript: an if statement, a ternary, or a logical AND. React renders whatever the expression gives back.

An if statement picks between two returns. A ternary picks between two values inside the markup. A logical AND shows its second half only when its first half is true. All three are the same idea in different clothes.

The program below renders one Greeting twice: once signed in, once signed out. The printed markup reads Welcome back, then Please sign in. The Conditional Rendering, Ternary Expressions, and Logical AND Rendering lessons cover each form.

function Greeting({ loggedIn }) {
  if (loggedIn) {
    return <p>Welcome back.</p>;
  }
  return <p>Please sign in.</p>;
}

export default function App() {
  return (
    <>
      <Greeting loggedIn={true} />
      <Greeting loggedIn={false} />
    </>
  );
}

Output:
<p>Welcome back.</p><p>Please sign in.</p>

9. How do you render a list in React?

A list is rendered with map. The array is mapped over, and each item becomes one element. The result is an array of elements, and React renders arrays in order.

Every element in the mapped array needs a key. The key is usually the item itself when items are unique strings, or an id when items are objects. The key is not rendered. It is only a hint for reconciliation.

The program below maps three fruits into list items. The printed markup is a list of Apple, Banana, and Cherry. The Rendering Lists lesson starts from this shape and adds filtering and sorting.

const fruits = ['Apple', 'Banana', 'Cherry'];

export default function App() {
  return (
    <ul>
      {fruits.map((fruit) => <li key={fruit}>{fruit}</li>)}
    </ul>
  );
}

Output:
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>

10. What is a fragment, and when do you use one?

A fragment groups elements without adding a node to the page. It is written as empty angle brackets, or as React.Fragment when a key is needed. The children render as siblings, with no wrapper around them.

Fragments are needed when a component must return two elements at once. A component can only return one thing, so two siblings need a wrapper. A div would add a node that breaks the layout. A fragment adds nothing.

The program below returns a heading and a paragraph inside a fragment. The printed markup is the two elements side by side, with no wrapper div. The Fragments lesson states the same point: the fragment adds nothing to the page itself.

export default function App() {
  return (
    <>
      <h1>Shopping list</h1>
      <p>Three items, no wrapper.</p>
    </>
  );
}

Output:
<h1>Shopping list</h1><p>Three items, no wrapper.</p>

11. What does useState do?

useState adds state to a component. It takes the starting value and returns two things: the current value and a function that sets the next one. The pair is usually named with array destructuring.

Calling the setter does not change the value at once. It asks React to re-render the component with the new value. The old value stays in place until that render happens. Reading state right after setting it still gives the old value.

The program below starts a counter at 0. The printed markup reads Count: 0. The Updating State lesson shows the setter in a click handler, and the State and Events lesson shows why the old value lingers.

import { useState } from 'react';

export default function App() {
  const [count] = useState(0);
  return <p>Count: {count}</p>;
}

Output:
<p>Count: 0</p>

12. Why does calling setCount three times add only one?

State updates are batched. React gathers the updates from one event handler and runs a single re-render at the end. Three setter calls in one handler cause one render, not three.

The trap is the value each call reads. A handler closes over the state value from its render. Three calls to setCount with count plus 1 all read the same count, so all three write the same next value. The count moves by one, not three.

The fix is a functional update: setCount with a function that takes the latest value and returns the next one. Each function runs in turn, so three calls add three. The program below computes both endings: stale updates leave 1, functional updates leave 3. The Updating State lesson states the same rule.

function afterThreeStaleUpdates() {
  let count = 0;
  const handlerCount = count; // the value the handler closed over: 0
  const setCount = (value) => { count = value; };
  setCount(handlerCount + 1);
  setCount(handlerCount + 1);
  setCount(handlerCount + 1);
  return count;
}

function afterThreeFunctionalUpdates() {
  let count = 0;
  const setCount = (updater) => { count = updater(count); };
  setCount((c) => c + 1);
  setCount((c) => c + 1);
  setCount((c) => c + 1);
  return count;
}

export default function App() {
  return (
    <>
      <p>Stale updates: {afterThreeStaleUpdates()}</p>
      <p>Functional updates: {afterThreeFunctionalUpdates()}</p>
    </>
  );
}

Output:
<p>Stale updates: 1</p><p>Functional updates: 3</p>

13. What does useEffect do, and when does it run?

useEffect runs code after a render, outside the render itself. It takes a function and a list of dependencies. React runs the function after the component appears, and again whenever a listed value changes.

The dependency list is the contract. Every value the effect reads must be listed, and the effect runs again when any of them changes. An empty list means the effect runs once, after the first render. No list at all means it runs after every render.

Two mistakes dominate. An effect that sets state it also depends on loops for ever: each run sets state, the state change runs the effect again. And an effect that reads a value it does not list goes stale. The program below shows the first render of a user loader, which reads Loading, because a static render runs no effects. The useEffect and Effects and Dependencies lessons cover the same ground.

import { useEffect, useState } from 'react';

function User({ id }) {
  const [name, setName] = useState(null);
  useEffect(() => {
    setName('User ' + id);
  }, [id]);
  if (name === null) {
    return <p>Loading…</p>;
  }
  return <p>{name}</p>;
}

export default function App() {
  return <User id={7} />;
}

Output:
<p>Loading…</p>

14. What is effect cleanup, and when do you need it?

Effect cleanup is a function an effect returns. React runs it before the effect runs again, and when the component leaves the page. Cleanup undoes what the effect set up: timers, subscriptions, and listeners.

Cleanup is needed whenever an effect opens something that outlives a render. A timer left running keeps firing after its component is gone. A subscription left open keeps calling a setter on a component that no longer exists.

A fetch with an abort signal is the common case. The effect starts the fetch and returns a cleanup that aborts it. A fast unmount then cancels the request instead of letting it land on a dead component. The Effect Cleanup lesson shows a timer stopped this way when the component leaves the page.

15. How do race conditions happen in effects, and how do you stop them?

A race condition happens when two requests overlap and the slower one lands last. A search box is the classic case. The user types react, then react hooks. The first request is slower, so its results arrive after the second and overwrite them. The page shows stale results for the old query.

The cause is that effects have no memory of order. Each run starts a request and trusts whatever comes back. A late answer is treated the same as a fresh one. The fix is a guard: a flag that the cleanup sets, or an abort signal that cancels the old request.

The program below shows the guarded shape. The effect sets a cancelled flag, and the cleanup sets it before the next run. An answer that arrives after its effect was cleaned up is dropped. The printed markup is the first render, Searching for react, because a static render runs no effects. The Loading and Error States lesson shows the loading and error states such a fetch needs.

import { useEffect, useState } from 'react';

function SearchResults({ query }) {
  const [results, setResults] = useState(null);
  useEffect(() => {
    let cancelled = false;
    const timer = setTimeout(() => {
      if (!cancelled) {
        setResults(['Result for ' + query]);
      }
    }, 0);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [query]);
  if (results === null) {
    return <p>Searching for {query}…</p>;
  }
  return <p>{results[0]}</p>;
}

export default function App() {
  return <SearchResults query="react" />;
}

Output:
<p>Searching for react…</p>

16. What is useRef for?

useRef holds a value that survives re-renders without causing one. It returns an object with one field, current. Changing current does not re-render the component. The value sits quietly until something reads it.

The main use is holding a DOM node. A ref attached to an input gives the input element itself, so code can focus it or measure it. The second use is holding any value that must survive renders: a timer id, a count of renders, or the previous value of a prop.

The program below attaches a ref to an input. The printed markup is the input and a line saying the ref starts empty and fills in after mount. That is the honest shape: current is null during the first render and set once the node exists. The useRef lesson states the same shape: a ref may hold a node from the page.

import { useRef } from 'react';

export default function App() {
  const inputRef = useRef(null);
  return (
    <>
      <input ref={inputRef} placeholder="Type your name" />
      <p>The ref starts empty and fills in after mount.</p>
    </>
  );
}

Output:
<input placeholder="Type your name"/><p>The ref starts empty and fills in after mount.</p>

17. What does useContext do?

useContext reads a value from the nearest provider above a component. The value is created with createContext and supplied with a Provider. Any component below the provider can read it without receiving it as a prop.

Context removes prop drilling: the passing of a value through layers of components that never use it. A theme or a signed-in user is passed once at the top and read wherever it is needed.

The program below provides the value dark and reads it in a panel. The printed markup reads Theme: dark. The useContext lesson builds the same shape: a Provider gives a value, and components below it read it. Context also has a cost, which is the subject of question 36.

import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function Panel() {
  const theme = useContext(ThemeContext);
  return <p>Theme: {theme}</p>;
}

export default function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Panel />
    </ThemeContext.Provider>
  );
}

Output:
<p>Theme: dark</p>

18. When do you reach for useReducer instead of useState?

useReducer fits state that changes in several related ways. It takes a reducer function and a starting value, and returns the current state and a dispatch function. Dispatch sends an action, and the reducer works out the next state.

A counter with one button is a useState job. A form with five fields, a shopping cart with add, remove, and clear, or a fetch with loading, success, and error are useReducer jobs. The reducer puts every transition in one place, so the rules are visible together.

The program below starts a counter at 0 through useReducer and shows the reducer's own answer to an increment: 1. The printed lines are Count: 0 and After one increment: 1.

import { useReducer } from 'react';

function reducer(count, action) {
  if (action.type === 'increment') {
    return count + 1;
  }
  return count;
}

export default function App() {
  const [count] = useReducer(reducer, 0);
  return (
    <>
      <p>Count: {count}</p>
      <p>After one increment: {reducer(0, { type: 'increment' })}</p>
    </>
  );
}

Output:
<p>Count: 0</p><p>After one increment: 1</p>

19. What is a custom hook?

A custom hook is a function that calls other hooks and shares the logic between components. Its name starts with use. React treats it like any hook: it must be called at the top of a component, never inside a condition or a loop.

A custom hook shares behaviour, not state. Two components that call useToggle each get their own value. The logic is shared. The state is not.

The program below defines useToggle and uses it twice, once starting off and once starting on. The printed markup reads Off, then On. The Custom Hooks lesson builds a useCounter hook on the same pattern.

import { useState } from 'react';

function useToggle(start) {
  const [value, setValue] = useState(start);
  const toggle = () => setValue((v) => !v);
  return [value, toggle];
}

function Switch({ start }) {
  const [on] = useToggle(start);
  return <p>{on ? 'On' : 'Off'}</p>;
}

export default function App() {
  return (
    <>
      <Switch start={false} />
      <Switch start={true} />
    </>
  );
}

Output:
<p>Off</p><p>On</p>

20. What are the Rules of Hooks, and why do they exist?

The rules are two. Hooks are called at the top level of a component, never inside a condition, a loop, or a nested function. And hooks are called only from React components or other custom hooks, never from plain JavaScript functions.

The reason is how React tracks hooks. React keeps a list of hook calls in the order they ran. Each render must run the same calls in the same order, so React can match each call to its stored state. A conditional hook changes the order on some renders, and the matching breaks.

A hook inside a condition is the classic violation. On one render the condition is true and the hook runs. On the next it is false and the hook is skipped. Every hook after it shifts by one place, and each one reads the wrong stored value. The fix is to call the hook always and put the condition inside it, or inside the value it returns.

21. What is a stale closure?

A stale closure is a function that holds an old value because it was created during an old render. Every render creates fresh functions, and each one closes over the values of its own render. A function that lives on, like a timer callback, keeps the values from the render that made it.

The classic case is an interval set up once. The effect runs on mount, when count is 0, and the callback inside it closes over that 0. The interval fires for ever, and each time it reads the same 0. The count on screen never moves.

The program below shows the starting point: Count: 0, with an interval that logs count each second. The fix is a functional update, which reads the latest value instead of the closed-over one, or a ref that always holds the current value. The Effect Cleanup lesson shows a timer stopped this way when the component leaves.

import { useEffect, useState } from 'react';

export default function App() {
  const [count] = useState(0);
  useEffect(() => {
    const timer = setInterval(() => {
      console.log(count);
    }, 1000);
    return () => clearInterval(timer);
  }, []);
  return <p>Count: {count}</p>;
}

Output:
<p>Count: 0</p>

22. How do you know an effect should be deleted?

An effect should be deleted when the value it sets can be worked out during render. State that is only a copy of other state is the tell. If a value can be computed from props or state, computing it is cheaper and always in step.

A full name is the plain example. Storing it in state means an effect must watch first and last name and keep the copy updated. Computing it during render means it can never fall behind, because it is worked out fresh on every render.

The program below computes a full name during render from Asha and Verma. The printed markup reads Asha Verma. No state holds the name, and no effect keeps it in step. The Effects and Dependencies lesson names the same rule: derive during render when you can.

export default function App() {
  const firstName = 'Asha';
  const lastName = 'Verma';
  const fullName = firstName + ' ' + lastName;
  return <p>{fullName}</p>;
}

Output:
<p>Asha Verma</p>

23. What is the difference between useMemo, useCallback and React.memo?

The three memoise different things. useMemo memoises a value: the result of a calculation. useCallback memoises a function: the same function reference across renders. React.memo memoises a component: it skips re-rendering when its props are unchanged.

useMemo takes a function and a dependency list, and returns the cached result until a dependency changes. useCallback is the same idea for functions: it is useMemo returning a function. React.memo wraps a component and compares its props before rendering.

The program below memoises the sum of 1 to 100. The printed line reads Total of 1 to 100: 5050. The deeper point is when not to memoise: a cheap calculation costs more to cache than to redo, and a memoised component with new props every render saves nothing. The React Compiler, in question 33, now does this work automatically in new code.

import { useMemo } from 'react';

function totalUpTo(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) {
    total += i;
  }
  return total;
}

export default function App() {
  const total = useMemo(() => totalUpTo(100), []);
  return <p>Total of 1 to 100: {total}</p>;
}

Output:
<p>Total of 1 to 100: 5050</p>

24. What is the difference between useEffect and useLayoutEffect?

The two run at different times. useEffect runs after the browser has painted. useLayoutEffect runs after the DOM is updated but before the paint. The difference is visible only when the effect changes layout.

useLayoutEffect suits measurements and layout fixes. Reading an element's size and then moving it must happen before paint, or the user sees a flicker: the element in the old spot, then the new one. useEffect suits everything else: fetching, subscriptions, and logging.

useLayoutEffect blocks paint, so it must stay fast. A slow layout effect freezes the page visibly. The rule is simple: reach for useEffect first, and switch to useLayoutEffect only when you can see a flicker that the switch removes.

25. What are useTransition and useDeferredValue for?

The two keep typing responsive while a heavy update runs. useTransition marks an update as low priority: the old screen stays up while the new one is prepared. useDeferredValue gives a lagging copy of a value, so the screen can keep showing the old list while the new one is filtered.

A slow search list is the case both solve. Each keystroke filters thousands of rows, and filtering blocks the input. With useDeferredValue, the input updates at once and the list follows a beat later. With useTransition, the filter runs as a transition and the old list stays visible until the new one is ready.

The program below filters four fruits with a deferred query of ap. The printed list is apple and apricot. In a static render the deferred value equals the input at once, because there is no typing in progress. The difference only shows under load, which is the point: the hook trades a little staleness for a responsive input.

import { useDeferredValue } from 'react';

const fruits = ['apple', 'apricot', 'banana', 'avocado'];

export default function App() {
  const query = 'ap';
  const deferredQuery = useDeferredValue(query);
  const matches = fruits.filter((fruit) => fruit.startsWith(deferredQuery));
  return (
    <ul>
      {matches.map((fruit) => <li key={fruit}>{fruit}</li>)}
    </ul>
  );
}

Output:
<ul><li>apple</li><li>apricot</li></ul>

26. What is useId for?

useId gives a component a unique id that is stable across renders and the same on the server and the client. It is meant for linking a label to its input, and for aria attributes that need matching ids.

The id is not meant to be read or predicted. It is an opaque string React generates, and its shape can change between versions. It is also not a key: keys need stable values tied to data, and a generated id is tied to nothing.

The program below asks for an id and uses it for a label and an input. The printed markup links the two with the id _R_0_. The value will differ in another render tree, but the label and the input always match.

import { useId } from 'react';

export default function App() {
  const id = useId();
  return <label htmlFor={id}>Name<input id={id} /></label>;
}

Output:
<label for="_R_0_">Name<input id="_R_0_"/></label>

27. Why does a component re-render?

A component re-renders when its state changes, when its props change, or when its parent re-renders. A context value it reads changing also re-renders it. Nothing else does.

A parent re-render re-renders every child by default, even when the child's props are the same. React still runs the child's function and compares the result. The comparison is usually cheap, and the DOM is only touched where the result differs.

The common surprise is a new object or function passed as a prop. An inline object literal is a new object on every render, so a memoised child sees a changed prop and renders anyway. The fix is to keep the value stable: hold it in state, memoise it, or move it outside the component.

28. How do you find out why a component is slow?

Measure first, and measure in the browser. The React Profiler, in React DevTools, records each commit and shows which components rendered and how long each render took. A slow component shows up as a long bar, not as a guess.

The Profiler answers two questions: what rendered, and why. The why is usually a state change in a parent, a new prop, or a context update. The fix follows the cause: memoise the child, move the state down, or split the context.

Two mistakes waste the effort. Profiling a development build measures the development overhead, not the shipped code, so profile a production build. And optimising before measuring spends effort on a component that was never slow.

29. When does React.memo help, and when does it not?

React.memo helps when a component renders often with the same props. It compares the new props with the old ones and skips the render when nothing changed. A heavy list row or a chart that re-renders on every keystroke elsewhere is the case.

It does not help when the props change every time. An inline arrow function or a fresh object literal is a new value on each render, so the comparison always fails and the render runs anyway. It also does not help when the component is already cheap: the comparison itself costs more than the render it saves.

The program below wraps a greeting in memo and renders it once. The printed markup reads Hello, Asha. The wrap alone proves nothing about speed: the gain only shows when a parent re-renders and the props stay the same. The React Compiler, in question 33, now adds this memoisation at build time.

import { memo } from 'react';

const Greeting = memo(function Greeting({ name }) {
  return <p>Hello, {name}</p>;
});

export default function App() {
  return <Greeting name="Asha" />;
}

Output:
<p>Hello, Asha</p>

30. How do React.lazy and Suspense split code?

React.lazy loads a component only when it is first rendered. It takes a function that imports the component, usually with a dynamic import. The bundler turns that import into a separate chunk, and the chunk travels over the network only when needed.

Suspense draws the line around the lazy component and shows a fallback while the chunk loads. The fallback is ordinary markup: a spinner, a skeleton, or a short line. When the chunk arrives, React swaps the fallback for the real component.

The program below wraps a lazy component in Suspense. The chunk is not loaded in a static render, so the printed markup is the fallback: Loading. In a browser the same code shows the fallback briefly, then the loaded component. The pattern suits routes and heavy panels, not small components that load at once anyway.

import { Suspense, lazy } from 'react';

const Heavy = lazy(() => Promise.resolve({ default: () => <p>Heavy loaded</p> }));

export default function App() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Heavy />
    </Suspense>
  );
}

Output:
<p>Loading…</p>

31. How do you keep a long list fast?

A long list is slow because the browser holds thousands of nodes. Each node costs memory and layout time, even when it sits far below the fold. The fix is to render only the rows in view.

Virtualisation renders a window of rows around the scroll position, plus a small buffer above and below. The list keeps its full height with a spacer, so the scrollbar behaves as if every row existed. As the user scrolls, rows leave one end of the window and enter the other.

Two cheaper steps come first. Give each row a stable key, so React can move rows instead of rebuilding them. And keep each row light: a row that runs a heavy calculation on every render defeats the window. Libraries like TanStack Virtual do the windowing; the list code only supplies a row renderer and a row height.

32. How do you keep a React bundle small?

A bundle grows from three places: the code the team writes, the libraries it imports, and the code that runs before the user needs it. Each has its own fix, and the fixes stack.

Import only what is used. A whole-library import pulls every export into the bundle, while a named import lets the bundler drop the rest. Tree-shaking removes unused exports, but only when the library is written to allow it. A quick check of the bundle with a visualiser shows which dependency is heavy.

Split what can wait. Routes load on navigation, not on first paint, and heavy panels load on first use. Images and fonts are the other half of the weight: a modern format and a sensible size do more than any code change. The rule is to measure the bundle before cutting it, because the biggest import is rarely the one anyone guesses.

33. What does the React Compiler change?

The React Compiler memoises components and hooks automatically at build time. It reads the component code and adds the caching that developers used to write by hand with useMemo, useCallback, and React.memo.

The change is in what developers must write. Manual memoisation is still allowed, but it is no longer the default advice for new code. A component that reads a value gets the cached version without a hook call, and a function passed to a child keeps its identity without useCallback.

The compiler reached a stable 1.0 release in October 2025, and it is opt-in: a project turns it on in its build. The advice it changes is narrow. It does not change when a component re-renders, or how state works. It only removes the hand-written caching that used to guard those renders.

34. Scenario: a form clears its fields when you type. What went wrong?

The fields clear because the inputs are being remounted on every keystroke. A remount destroys the old input and builds a new one, and the new one starts empty. The typed text dies with the old node.

The usual cause is a key that changes on every render. A key made from Math.random, or from a counter that ticks each render, makes React treat the input as a new element each time. Another cause is a component defined inside another component: a fresh function each render means a fresh component type, and React remounts it.

The fix is a stable key and a stable component type. Keys come from the data, never from a random call. Component definitions live at the top level of the file, never inside another component's body. The first check is always the same: open DevTools and watch whether the input node is replaced or only its value changes.

35. What does lifting state up mean?

Lifting state up moves shared state to the nearest common parent. Two children that need the same value stop owning it separately. The parent owns it once and passes it down to both.

The pattern shows in a counter with a display and a button. The display reads the count. The button changes it. Both need the same value, so the count lives in the parent, and the button gets a handler that sets it.

The program below shows the shape. The parent holds a count of 0 and passes it to a display and a button. The printed markup shows both reading 0: Shared count: 0, and a button reading Count is 0. The Sharing State lesson teaches the same shape: state sits in the parent, and props carry it down to the children.

import { useState } from 'react';

function CounterDisplay({ count }) {
  return <p>Shared count: {count}</p>;
}

function CounterButton({ count, onCount }) {
  return <button onClick={onCount}>Count is {count}</button>;
}

export default function App() {
  const [count] = useState(0);
  return (
    <>
      <CounterDisplay count={count} />
      <CounterButton count={count} onCount={() => {}} />
    </>
  );
}

Output:
<p>Shared count: 0</p><button>Count is 0</button>

36. What does Context cost?

Context costs a re-render of every consumer when the value changes. The value is compared by reference, not by contents. A new object with the same fields inside still counts as changed, because it is a different object.

The trap is a value built inline in the provider. An object literal in the render creates a new object each time, so every consumer re-renders on every parent render, even when nothing meaningful changed. The fix is to memoise the value, or to hold it in state so its identity only changes when the contents do.

The second fix is to split the context. A theme and a user in one context make a theme change re-render every user reader. Two contexts let each group of readers listen only to its own value. The program below provides one value, dark, to a toolbar and a footer. Both print their theme, because both read the same context.

import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <p>Toolbar theme: {theme}</p>;
}

function Footer() {
  const theme = useContext(ThemeContext);
  return <p>Footer theme: {theme}</p>;
}

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

Output:
<p>Toolbar theme: dark</p><p>Footer theme: dark</p>

37. Redux Toolkit, Zustand, or TanStack Query — how do you choose?

The choice starts with what kind of state it is. Client state is state the application owns: a theme, a cart, a draft. Server state is a copy of data that lives elsewhere: a user record, a list of tasks, a search result. The two kinds want different tools.

Server state belongs to TanStack Query or a similar data-fetching library. It caches, refetches, retries, and tracks loading and error states, which is work a hand-written fetch in an effect repeats badly. Client state that is small and local belongs in useState, lifted to the parent that needs it.

Global client state is where Redux Toolkit and Zustand compete. Redux Toolkit fits a large team with strict rules: one store, typed actions, and middleware for side effects. Zustand fits a smaller store with less ceremony: a single hook, no providers, and slices that update independently. Context alone fits a value that changes rarely, like a theme, and fails as a store because every consumer re-renders on every change.

38. How do you fetch data and show loading and error states?

Fetching has three states, and the component must render all three. Loading shows while the request travels. Success shows the data. Error shows the failure. A component that only renders success shows a blank page while the user waits, and a crash when the request fails.

The fetch runs in an effect, and the result goes into state. The effect depends on the inputs that shape the request, so a new search starts a new fetch. The cleanup aborts the old request, so a late answer cannot overwrite fresh data.

The program below shows the first and last states side by side. One profile has no user yet and prints Loading. The other has a user and prints Asha has 3 open tasks. The Fetching Data lesson shows the fetch inside an effect, and the Loading and Error States lesson shows the states it needs.

function Profile({ user }) {
  if (user === null) {
    return <p>Loading…</p>;
  }
  return <p>{user.name} has {user.tasks} open tasks.</p>;
}

export default function App() {
  return (
    <>
      <Profile user={null} />
      <Profile user={{ name: 'Asha', tasks: 3 }} />
    </>
  );
}

Output:
<p>Loading…</p><p>Asha has 3 open tasks.</p>

39. How do you handle forms in React?

A form in React is usually controlled: each input reads its value from state and reports each keystroke through onChange. The state is the single source of truth, and the submit handler reads it instead of reading the DOM.

One object can hold the whole form. A single handler updates one field by name, so five inputs need one handler instead of five. The shape is the same as five separate values, with less repetition.

The program below renders a sign-up form with two controlled inputs. The printed markup shows both values in place: Asha and asha@example.com. The Handling Submit lesson shows the submit handler reading state and stopping the page reload, and the Form State in One Object lesson shows the single-object shape.

import { useState } from 'react';

export default function App() {
  const [name] = useState('Asha');
  const [email] = useState('asha@example.com');
  return (
    <form>
      <input value={name} onChange={() => {}} />
      <input value={email} onChange={() => {}} />
      <button>Sign up</button>
    </form>
  );
}

Output:
<form><input value="Asha"/><input value="asha@example.com"/><button>Sign up</button></form>

40. What is an error boundary?

An error boundary is a class component that catches errors in the components below it. It defines a static method that returns a new state when a child throws, and a lifecycle method that can log the error. The boundary then renders a fallback instead of the crashed tree.

The boundary catches errors during rendering, in lifecycle methods, and in constructors below it. It does not catch errors in event handlers, in asynchronous code, or in the boundary itself. Those need their own handling, usually a try block around the risky call.

A boundary belongs around a risky subtree, not around the whole page. One around a comments widget lets the article survive when the widget fails. One around the whole page turns one small failure into a blank screen. Error boundaries are the only error handling React provides for rendering, and they are classes because hooks have no equivalent.

41. What is the difference between a Server Component and a Client Component?

A Server Component runs only on the server. It never ships its code to the browser, and it cannot use state, effects, or browser APIs. A Client Component runs in the browser, like every component before React 19, and it can use all of those.

The split is declared with a directive. A file without a directive is a Server Component by default in a framework that supports them. Adding 'use client' at the top marks the file and everything it imports as Client Components.

The split matters because it decides what travels to the browser. A product page can render its reviews on the server and keep its sort control as a small Client Component. The reviews cost no JavaScript. The control costs only its own code. Shipping a database client to the browser, by contrast, is a mistake the split is meant to stop.

42. What is the difference between Server Components and server-side rendering?

Server Components and server-side rendering both run code on the server, but they answer different questions. Server-side rendering asks how HTML reaches the browser. Server Components ask which components ever reach the browser at all.

Server-side rendering turns the whole tree into HTML on the server, sends it down, and hydrates it: React attaches event listeners and takes over in the browser. The client components still ship their JavaScript. Hydration makes the static HTML interactive.

Server Components skip that shipment. A Server Component renders on the server and its code stays there. The browser receives its output, not its source. The two compose: a page can render Server Components on the server, send HTML, and hydrate only the Client Components inside it.

43. How does streaming SSR work with Suspense?

Streaming SSR sends the page in pieces instead of all at once. The server renders the shell first and sends it, then streams each Suspense boundary's content as it becomes ready. The browser shows the shell early and fills in the slow parts as they arrive.

Suspense draws the lines. Each boundary has a fallback that renders at once, and the real content replaces it when the server finishes it. A slow reviews section shows its fallback while the rest of the page is already readable.

The gain is time to first content, not total time. The slow part still takes as long to compute. The user simply sees the rest of the page sooner, and the loading state is a real fallback in the page instead of a blank screen. Without Suspense the server must wait for the slowest part before sending anything.

44. What is the difference between an Action and a Server Action?

An Action is a function that handles a form submission in React 19. It runs on the client when passed to a form's action prop, and React manages the pending state while it runs. A Server Action is an Action defined on the server, marked with the 'use server' directive at the top of its function or file.

The directive is the whole distinction, and it is a known interview trap. An Action without 'use server' runs in the browser. A Server Action with it runs on the server, where it can touch a database directly. The form looks the same either way, which is why the directive matters.

Actions replace the old pattern of preventing the default submit and reading state by hand. React 19 pairs them with three hooks: useActionState for the result, useOptimistic for the instant update, and useFormStatus for the pending state. The next two questions cover them.

45. What is the use hook?

use is a React 19 API that reads a resource during render: a promise or a context value. It takes the resource and returns its value. Unlike other hooks, it can be called inside a condition or a loop, because React tracks it by the resource, not by call order.

With a promise, use suspends the component until the promise resolves. The nearest Suspense boundary shows its fallback meanwhile. With context, use reads the nearest provider's value, the same value useContext returns, but from inside a condition when needed.

use cannot be called with a promise created during the same render. A fresh promise each render would suspend for ever, because each render would make a new one. The promise must come from outside the render: passed in as a prop, or created in a Server Component and handed down.

46. What are useOptimistic, useActionState and useFormStatus for?

The three hooks cover the three states of a form Action. useActionState holds the result of the last submission and the pending state, so the form can show what happened. useOptimistic shows an instant guess while the Action runs, so the page feels fast before the server answers. useFormStatus reads the pending state of the enclosing form, so a submit button can disable itself while the Action runs.

useOptimistic takes the real value and a function that applies the guess. A like button with 12 likes calls the updater with 1, and the screen shows 13 at once. If the server answers with an error, React drops the guess and shows the real value again. The guess never writes to the server on its own.

The program below shows the starting point: a like count of 12, with no update in flight. The printed markup reads Likes: 12. The optimistic value only appears while an Action is running, which a static render cannot show. The trio is the standard answer for form questions in React 19 interviews.

import { useOptimistic, useState } from 'react';

export default function App() {
  const [likes] = useState(12);
  const [shownLikes] = useOptimistic(likes, (current, amount) => current + amount);
  return <p>Likes: {shownLikes}</p>;
}

Output:
<p>Likes: 12</p>

47. What changed about refs in React 19?

React 19 lets a function component take a ref as an ordinary prop. Before React 19, a ref passed to a function component was ignored unless the component was wrapped in forwardRef. The wrapper existed only to receive the ref and pass it on.

The change removes that wrapper. A component declares ref beside its other props, and the parent passes it the same way. Cleanup functions for refs are also new: a ref callback can return a function, and React runs it when the ref is removed or replaced.

The program below passes a ref to a plain function component and renders an input. The printed markup is a label holding the input. No forwardRef appears anywhere. The pattern is small, but it removes one of the most-asked beginner confusions in older React.

import { useRef } from 'react';

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

export default function App() {
  const inputRef = useRef(null);
  return <TextInput ref={inputRef} label="Name" />;
}

Output:
<label>Name<input/></label>

48. How do you test a React component with React Testing Library?

React Testing Library tests what a user sees and does, not how the component is built. The test renders the component, finds elements by their visible text or role, and fires events the way a user would: clicking a button, typing in an input.

The library's first rule is to query like a user. getByRole finds a button by its accessible name. getByText finds a heading by its words. Querying by test ids or by class names is a fallback, not a first choice, because it ties the test to details the user never sees.

A good test covers behaviour, not implementation. A counter test clicks the button and checks the count changed. It does not check state directly, because state is an internal detail. Mocks belong at the boundary: a fetch is mocked with a tool like Mock Service Worker, so the test checks the component against a fake server instead of a real one.

49. How do you type React props and components in TypeScript?

Props are typed with an interface or a type alias, named after the component. A Greeting that takes a name declares a GreetingProps type with name as a string, and the component's function takes that type as its props. The compiler then checks every use of the component.

Generics type components that work over any data. A List component that takes items and a render function declares a type parameter T, and the items are typed as T. The caller picks T by passing a list of strings or a list of users, and the compiler checks the render function against that choice.

Children are typed as ReactNode, which covers text, elements, and fragments. Event handlers use the React event types: a click handler takes React.MouseEvent, and a change handler takes React.ChangeEvent with the element type. The TypeScript course on this site teaches the language behind these types.

50. What happened to PropTypes in React 19?

PropTypes were removed from React in React 19. The separate prop-types package still exists for older code, but React itself no longer ships or reads them. A project that relied on them must move to TypeScript or keep the package pinned.

PropTypes checked props at runtime, in the browser, while the application ran. TypeScript checks props at build time, before the code ships. The build-time check catches the same mistakes earlier, and it covers more: return types, generics, and the shape of nested objects.

The removal is one line in an answer, but it signals the direction. React's own docs now show TypeScript in every example. An interviewer who asks about PropTypes is usually checking whether the candidate knows the ecosystem has moved on.

Questions readers ask

How should I work through this sheet?

Spread the groups across five days, one group a day, in the order they appear. Say each answer aloud before reading the one written here, then run the program beside it. Keep the React 19 group for the day before the interview, with any questions that tripped you up. Short daily sessions beat a single long night before.

Do I need React installed before I begin?

No. The sheet reads fine with no setup. To run the programs, install React through Vite: run npm create vite, pick the React template, and the examples drop into App.jsx. The versions used here are React 19.3.1 with Vite 8.3.7 and Node.js 24.22.1.

What should I study after this sheet?

React Beginner builds the skills behind the answers: components, hooks, forms, and fetching data. The Top 50 JavaScript Interview Questions with Answers sheet covers the language underneath. No React Intermediate course exists yet, and this sheet starts that ground.

Can I use this sheet with no JavaScript background?

Yes, but JavaScript comes first. JavaScript Beginner opens with a first program and introduces each idea at the moment it is needed. A background in another language makes functions and arrays easier, but the sheet does not rely on it. Every JavaScript idea is explained at the point where it appears, so nothing arrives unexplained.