React Fundamentals Interview Questions
With Answers & Code Examples

18 carefully curated React Fundamentals interview questions with working code examples and real interview gotchas.

18questions
6beginner
4core
8advanced

What is React and what problem does it solve?

Question 1Beginner

Hint: Declarative UI library — describe what the UI should look like, not how to update it

React is a JavaScript library for building user interfaces. It solves the problem of keeping the UI in sync with application state.

Core ideas:

  • Declarative — you describe the desired UI for a given state; React figures out DOM updates
  • Component-based — split UI into reusable, self-contained pieces
  • Virtual DOM — React maintains a lightweight copy of the DOM, diffs it on state change, and batches minimal real DOM updates
  • Unidirectional data flow — data flows down (props), events flow up (callbacks)

// Imperative (jQuery style) — how to update
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
  const count = parseInt(btn.textContent) + 1;
  btn.textContent = count;
});

// Declarative (React style) — what it should look like
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
💡 React's real innovation was making UI a pure function of state: UI = f(state). Any time state changes, React re-runs the function and reconciles the difference.

What is JSX and how does it work under the hood?

Question 2Beginner

Hint: JSX is syntactic sugar — Babel transforms it into React.createElement() calls

JSX is a syntax extension that looks like HTML inside JavaScript. It is NOT valid JS — it gets compiled by Babel into React.createElement() calls.

// What you write
const el = <h2 className="title">Hello {name}</h2>;

// What Babel compiles it to
const el = React.createElement('h1', { className: 'title' }, 'Hello ', name);

// React 17+ — new JSX transform (no need to import React)
import { jsx as _jsx } from 'react/jsx-runtime';
const el = _jsx('h1', { className: 'title', children: ['Hello ', name] });

Key rules:

  • Single root element required (use <></> Fragment if needed)
  • Use className not class, htmlFor not for
  • Expressions in {} — not statements (if, for)
  • Self-close empty tags: <img />, <br />
  • camelCase for attributes: onClick, onChange
💡 JSX returns plain JS objects (React elements). They're just descriptions — cheap to create. React uses these to build and diff the Virtual DOM.

What is the Virtual DOM and how does reconciliation work?

Question 3Beginner

Hint: Lightweight JS copy of the DOM — React diffs old vs new tree, applies minimal patches

The Virtual DOM is a JavaScript object tree that mirrors the real DOM. It's cheap to create and manipulate.

Reconciliation process:

  1. State/props change triggers a re-render — React calls your component function
  2. React builds a new Virtual DOM tree
  3. Diffing — React compares (diffs) new tree with the previous tree
  4. Committing — React applies only the changed nodes to the real DOM

Diffing heuristics (O(n) instead of O(n³)):

  • Elements of different types → tear down and rebuild the whole subtree
  • Same type → update only changed attributes
  • Lists → use key prop to match old and new items
// React sees these as DIFFERENT types → full rebuild
<div>...</div>  →  <span>...</span>  // destroys div, creates span

// Same type → just updates className attribute
<div className="old" />  →  <div className="new" />
💡 Reconciliation is why key matters so much in lists. Without a stable key, React might reuse the wrong DOM node, causing subtle bugs like input state being wrong item.

What is the difference between a controlled and uncontrolled component?

Question 4Beginner

Hint: Controlled = React owns the value; uncontrolled = DOM owns it (accessed via ref)

Controlled component — React state is the single source of truth. Every change goes through setState.

Uncontrolled component — the DOM stores the value. You pull it with a ref when needed.

// Controlled — React owns the value
function Controlled() {
  const [value, setValue] = useState('');
  return (
    <input
      value={value}
      onChange={e => setValue(e.target.value)}
    />
  );
}

// Uncontrolled — DOM owns the value
function Uncontrolled() {
  const inputRef = useRef(null);
  function handleSubmit() {
    console.log(inputRef.current.value); // pull on demand
  }
  return <input ref={inputRef} defaultValue="initial" />;
}

When to use each:

  • Controlled — instant validation, conditional disabling, dynamic inputs, format-on-type
  • Uncontrolled — file inputs (always uncontrolled), integrating with non-React code, simple one-off forms where you only need value on submit
💡 React recommends controlled components for most cases. File inputs (<input type="file">) are always uncontrolled — you can't set their value programmatically for security reasons.

What are props and how is prop drilling a problem?

Question 5Beginner

Hint: Props pass data down; drilling = passing through many layers just to reach a deeply nested child

Props are the inputs to a component — passed from parent to child. They are read-only (immutable from the child's perspective).

function Button({ label, onClick, disabled = false }) {
  return <button onClick={onClick} disabled={disabled}>{label}</button>;
}

// Usage
<Button label="Save" onClick={handleSave} disabled={isLoading} />

Prop drilling — passing props through intermediate components that don't need them, just so a deep child can access them:

// ❌ Drilling — Middle doesn't need user, just passes it down
function App() {
  const user = { name: 'Alice' };
  return <Middle user={user} />;
}
function Middle({ user }) {
  return <Deep user={user} />;
}
function Deep({ user }) {
  return <p>{user.name}</p>;
}

Solutions to prop drilling:

  • Context API — broadcast value to any descendant
  • Component composition — lift rendering up, pass JSX as children or slots
  • State management — Zustand, Redux, Jotai for global state
💡 Before reaching for Context, try composition first. Pass children or render props — often eliminates drilling without the overhead of a context.

What is the key prop and why is it critical in lists?

Question 6Core

Hint: Key lets React identify which item changed, was added, or removed — must be stable and unique

The key prop is React's mechanism to identify list items across renders. Without stable keys, React can't efficiently reconcile list changes.

// ❌ Using index as key — problematic when list reorders or items are inserted
{items.map((item, index) => (
  <ListItem key={index} item={item} />
))}

// ✅ Use a stable unique ID from the data
{items.map(item => (
  <ListItem key={item.id} item={item} />
))}

Why index keys fail:

// Initial:  [A(key=0), B(key=1), C(key=2)]
// Delete A: [B(key=0), C(key=1)]
// React sees key=0 CHANGED (not deleted) → updates B in place
// Key=2 REMOVED → destroys C
// Result: input state, focus, animations on wrong elements

When index keys are safe:

  • The list never reorders
  • Items are never inserted or deleted from the middle
  • Items have no state (text-only renders)
💡 Keys must be unique among siblings, not globally. Keys don't get passed as props — if you need the ID in the component, pass it explicitly as a separate prop.

What are React Fragments and when do you need them?

Question 7Core

Hint: <></> lets you return multiple elements without adding an extra DOM node

Fragments let you group multiple elements without adding an extra DOM wrapper node.

// ❌ Extra div pollutes the DOM
function TableRow() {
  return (
    <div>         {/* invalid inside <tbody> */}
      <td>Name</td>
      <td>Age</td>
    </div>
  );
}

// ✅ Fragment — no DOM node added
function TableRow() {
  return (
    <>
      <td>Name</td>
      <td>Age</td>
    
  );
}

// Keyed fragments — use the long form syntax (shorthand doesn't support key)
function List({ items }) {
  return items.map(item => (
    <React.Fragment key={item.id}>
      <dt>{item.term}</dt>
      <dd>{item.description}</dd>
    </React.Fragment>
  ));
}
💡 Fragments matter most in table structures (tr/td/th must be direct children) and flexbox/grid layouts where an extra wrapper breaks the CSS.

What is the component lifecycle and how do hooks map to it?

Question 8Core

Hint: Mount → Update → Unmount — useEffect covers all three phases

Class components had explicit lifecycle methods. Hooks cover the same phases:

Class methodHook equivalent
componentDidMountuseEffect(() => { ... }, [])
componentDidUpdateuseEffect(() => { ... }, [deps])
componentWillUnmountuseEffect(() => { return () => cleanup() }, [])
shouldComponentUpdateReact.memo + useMemo
getDerivedStateFromPropsCompute during render (no hook needed)
getSnapshotBeforeUpdateNo hook equivalent (rare — use a class component)
useEffect(() => {
  // componentDidMount — runs after first render
  const sub = subscribe(userId);

  // componentWillUnmount — cleanup function
  return () => sub.unsubscribe();
}, []); // [] = run once

useEffect(() => {
  // componentDidUpdate for userId — runs when userId changes
  fetchUser(userId);
}, [userId]);
💡 useEffect runs AFTER the browser paints. For DOM measurements that need to run synchronously before paint (to avoid flicker), use useLayoutEffect instead.

What is the difference between state and props?

Question 9Beginner

Hint: Props = external inputs (immutable); state = internal memory (mutable via setState)

  • Props — passed in from outside, owned by the parent, read-only inside the component
  • State — owned and managed by the component itself, mutable via setState/useState, triggers re-render when changed
function Counter({ initialCount, step = 1 }) {
  //              ↑ props — given from parent, read-only here

  const [count, setCount] = useState(initialCount);
  //     ↑ state — owned by this component

  return (
    <button onClick={() => setCount(c => c + step)}>
      Count: {count}
    </button>
  );
}

When state changes: React re-renders the component and all its children.

When props change: the parent re-renders, passing new props, which causes the child to re-render.

💡 A common mistake: trying to sync state with props using useEffect. Instead, derive values during render if possible. If a prop controls the initial value, use it only in useState's initializer — not as a useEffect dep.

What is StrictMode and what does it do in development?

Question 10Advanced

Hint: Intentionally double-invokes render, effects to expose impure code and side effects — dev only, no production cost

React.StrictMode is a development tool that helps you find bugs by intentionally stressing your components.

What it does (dev only):

  • Double-invokes render functions — component function called twice to detect impure renders
  • Double-invokes effects — mounts, unmounts, and remounts every component to surface missing cleanup
  • Warns about deprecated APIs — componentWillMount, findDOMNode, etc.
// StrictMode reveals this bug:
function BadComponent() {
  const items = []; // 💥 rendered twice, items reset each time — detected!
  items.push('item'); // pure render must not have side effects
  return <div>{items}</div>;
}

// StrictMode reveals missing cleanup:
useEffect(() => {
  const ws = new WebSocket(url); // mount #1 — created
  // StrictMode: unmount → cleanup should close ws
  //             mount #2 — second connection opened
  // If no cleanup, you'd have two connections — StrictMode exposes this
  return () => ws.close(); // ✅ proper cleanup
}, [url]);

// Usage
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
💡 In React 18, StrictMode's double-effect firing is intentional preparation for a future feature (Offscreen). If your effect fires twice and causes a bug, you have a missing cleanup function — fix that, don't remove StrictMode.

What is interruptible rendering in React?

Question 11Advanced

Hint: Think about what happens to a slow render when the user types — and which APIs mark an update as low priority.

Before React 18, a render ran start to finish without stopping; a big update could freeze input for hundreds of milliseconds. With concurrent rendering, React works in small units (fibers) and checks between them whether something more urgent is waiting. If it is, it pauses or throws away the in-progress render, handles the urgent update, then restarts.

Only updates marked as non-urgent are interruptible. You mark them with startTransition, useTransition or useDeferredValue:

function Search() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [isPending, startTransition] = useTransition();

  function onChange(e) {
    setQuery(e.target.value);          // urgent: input stays responsive
    startTransition(() => {
      setResults(filterHugeList(e.target.value)); // interruptible
    });
  }

  return (
    <>
      <input value={query} onChange={onChange} />
      {isPending ? <Spinner /> : <List items={results} />}
    </>
  );
}

The render phase is interruptible because it has no side effects. The commit phase, where React writes to the DOM, always runs synchronously, so users never see half an update.

💡 Because a render can run more than once before it commits, render functions must be pure — side effects belong in effects or event handlers.

How does React's reconciliation (diffing) algorithm work?

Question 12Advanced

Hint: Comparing two trees in general is O(n³). Which two assumptions let React do it in O(n)?

Reconciliation is how React works out what changed between the previous render's element tree and the new one, so it can update only that part of the DOM. A general tree diff is O(n³); React makes it O(n) with two assumptions:

  1. Different type → different tree. If an element's type changes (<div> to <section>, or ComponentA to ComponentB), React destroys the old subtree, state included, and builds a new one.
  2. Keys identify children. In a list, React matches old and new children by key, so it can move, add or remove items instead of re-creating them.
// Same type: React keeps the DOM node and updates only className
<div className="old" />  →  <div className="new" />

// Stable keys: inserting at the top moves nothing else
{todos.map(todo => <Todo key={todo.id} todo={todo} />)}

// ❌ Index keys: inserting at the top shifts every key,
// so state (like input text) ends up on the wrong item
{todos.map((todo, i) => <Todo key={i} todo={todo} />)}

Reconciliation decides what changes; rendering a component still runs its function. To skip re-rendering a subtree whose props didn't change, use React.memo.

💡 Changing a component's key is a deliberate way to reset its state: React treats it as a new component.

How does useMemo optimize component performance?

Question 13Core

Hint: useMemo compares its dependencies between renders. What happens if a dependency is a new array every render?

useMemo(fn, deps) caches the result of fn and only recomputes it when a dependency changes (compared with Object.is). It's for expensive calculations and for keeping object or array references stable between renders.

function ProductList({ products, query }) {
  // Re-filters only when products or query change
  const visible = useMemo(
    () => products.filter(p => p.name.includes(query)),
    [products, query]
  );

  // Stable reference so a memoized child can skip re-rendering
  const style = useMemo(() => ({ gap: 8 }), []);

  return <MemoGrid items={visible} style={style} />;
}

The common mistake: a dependency that's created during render, like const numbers = [1, 2, 3] inside the component, is a new array every time, so the memo recomputes on every render and does nothing. Move constants outside the component or memoize them too.

💡 Don't wrap every value in useMemo — it has its own cost. Reach for it when a calculation is measurably slow or when a stable reference matters (React.memo children, effect dependencies).

What happens when a React component re-renders?

Question 14Advanced

Hint: Separate trigger, render and commit. Which of the three actually touches the DOM?

A React update happens in three steps:

  1. Trigger — the initial root.render(), or a state update (setState, a reducer dispatch, a context change).
  2. Render — React calls the component function again (and its children's), producing a new element tree, then reconciles it against the previous one to find what changed. No DOM changes happen here.
  3. Commit — React applies the minimal set of DOM changes, then runs layout effects and, after paint, regular effects.
function Counter() {
  const [count, setCount] = useState(0);
  console.log('render', count); // runs on every render

  useEffect(() => {
    document.title = 'Count: ' + count; // runs after commit
  }, [count]);

  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

What re-renders: the component whose state changed and, by default, every component below it — even if their props are the same. React.memo lets a child skip re-rendering when its props are shallow-equal.

Setting state to the same value (by Object.is) lets React bail out without re-rendering the children.

💡 "Render" doesn't mean "DOM update". A component can render many times while the DOM changes only when the output differs.

What does flushSync do in React?

Question 15Advanced

Hint: flushSync takes a callback. What does React do with the updates made inside it?

flushSync(callback) from react-dom runs the callback and applies any state updates made inside it synchronously, so the DOM is updated before the next line runs. It opts those updates out of automatic batching.

import { flushSync } from 'react-dom';

function TodoList() {
  const [todos, setTodos] = useState([]);
  const listRef = useRef(null);

  function addTodo(text) {
    flushSync(() => {
      setTodos(t => [...t, text]);
    });
    // The new item is already in the DOM here
    listRef.current.lastElementChild.scrollIntoView();
  }
  // ...
}

Common uses: scrolling to or measuring an element that was just added, moving focus to it, or syncing with a non-React library that reads the DOM straight away.

💡 flushSync forces an extra render and can hurt performance. Use it rarely — most "read the DOM after update" needs are better served by useLayoutEffect.

What is React Fiber?

Question 16Advanced

Hint: The old reconciler used the JavaScript call stack. What does React gain by keeping its own linked list of work units instead?

Fiber is React's reconciler since React 16. The old "stack" reconciler walked the tree recursively and couldn't stop until it finished. Fiber turns each component into a fiber — a plain object describing one unit of work — linked by child, sibling and return pointers. Because React walks this list itself instead of using the call stack, it can pause, resume, prioritize or discard work.

// Simplified shape of a fiber
{
  type: Counter,          // component or host tag ('div')
  key: null,
  stateNode: null,        // DOM node for host components
  child: fiberA,          // first child
  sibling: fiberB,        // next sibling
  return: parentFiber,    // parent
  pendingProps: { step: 1 },
  memoizedState: hooksList,
  lanes: 0b0001,          // priority of pending work
  alternate: currentFiber // the other tree's copy
}

Double buffering: React keeps a current tree (on screen) and builds a work-in-progress tree. When the work-in-progress tree is complete, React commits it in one go and the two swap roles via alternate.

Two phases: the render phase (building the work-in-progress tree) can be split up and interrupted; the commit phase (DOM changes, layout effects) runs synchronously.

💡 Fiber is what makes concurrent features — transitions, Suspense, useDeferredValue — possible. It's an internal architecture: you never create fibers yourself.

What is automatic batching in React 18?

Question 17Advanced

Hint: Think about setState calls inside a setTimeout or a promise callback, before and after React 18.

Batching means React groups several state updates into one re-render. React 17 only batched updates inside its own event handlers. React 18, with createRoot, batches everywhere: timeouts, promises, native event listeners.

function handleClick() {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React 17 and 18: one re-render
}

setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React 17: two re-renders
  // React 18: one re-render
}, 1000);

fetch('/api').then(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React 18: one re-render
});

Batching changes when React re-renders, not what state ends up as. Two setCount(count + 1) calls still read the same count, so the counter goes up by one — use the updater form c => c + 1 when the next value depends on the previous one.

To opt out for a specific update, wrap it in flushSync from react-dom.

💡 Automatic batching needs createRoot. Apps still on the legacy ReactDOM.render keep React 17 behaviour.

How does React batch state updates, and how do you control it?

Question 18Advanced

Hint: Since React 18, batching is automatic. Which API forces an update out of a batch, and which old one is no longer needed?

React batches state updates: several setState calls in the same tick produce one re-render. Since React 18 (with createRoot) this happens everywhere — event handlers, timeouts, promises and native listeners.

// One re-render for both updates — no extra API needed
async function save() {
  const data = await api.save();
  setSaving(false);
  setResult(data);
}

// Opt out: apply this update immediately
import { flushSync } from 'react-dom';
flushSync(() => setOpen(true));
// DOM is updated here
  • unstable_batchedUpdates was the React 17 workaround for batching outside event handlers. In React 18+ it's unnecessary.
  • flushSync does the opposite of batching: it forces the updates inside it to render synchronously.
  • useMemo / useCallback don't batch anything. They reduce the cost of each render by keeping values stable for memoized children.
💡 To cut re-renders further, put related state in one object or a reducer, and keep state as close as possible to where it's used.

Other React Interview Topics

Ready to practice React Fundamentals?

Get AI feedback on your answers, predict code output, and fix real bugs.