React interview questions
React interviews test whether you understand what a render is. Why does calling setCount(count + 1) twice only add one? What is the dependency array of useEffect doing? Where does state go when two siblings need it?
These questions cover JSX, props and state, keys, controlled inputs and effects, with three components that are missing the one line that makes them correct, and a few newer details such as useId and refs as props in React 19.
All 21 are the free Foundation level of the React topic in GapfyreSWE. Try each one before you open its answer.
-
What is JSX, and how does it relate to actual JavaScript function calls?
- JSX only works for static markup; any dynamic JavaScript expression must be written outside of it
- JSX replaced JavaScript function calls entirely in React 18, which no longer supports createElement
- JSX is HTML-like syntax that a build step compiles into ordinary JavaScript function calls
- JSX is a separate templating language that React interprets directly at runtime, with no compilation step involved
Show the answer
C. JSX is HTML-like syntax that a build step compiles into ordinary JavaScript function calls
JSX is a syntax extension that lets HTML-like markup be written directly inside JavaScript —
<div className="card">{title}</div>— which is not valid plain JavaScript on its own. A build step (via Babel or a similar transpiler) compiles JSX down into ordinary function calls, traditionallyReact.createElement(type, props, children)(or the newer automatic JSX runtime's equivalent), which is what actually runs in the browser. JSX is purely syntactic sugar for those calls — everything expressible in JSX can also be written by hand as nestedcreateElementcalls, just far less readably. -
Props vs state: what is the actual difference between a React component's props and its state?
- Props can change at any time without a re-render; state changes always require the whole page to reload
- They are interchangeable terms for the same concept, differing only in which hook is used to declare them
- Props are read-only inputs passed down from a parent; state is data a component manages and updates on its own
- State can be passed down to child components; props can only ever be read by the component that declares them
Show the answer
C. Props are read-only inputs passed down from a parent; state is data a component manages and updates on its own
Props are inputs passed *into* a component by its parent — read-only from the receiving component's own perspective, and changed only by the parent re-rendering it with different values. State is data a component manages *itself*, internal to that component, which it can update on its own (e.g. in response to a user interaction) to trigger a re-render — a parent generally has no direct visibility into or control over a child's internal state unless the child explicitly exposes a way to change it (for example, by lifting that state up).
-
What does the
useStatehook return, and what happens when the setter function it returns is called?- It returns a value and setter; the setter schedules a re-render rather than mutating
- It returns a Promise that resolves once the component has finished updating
- It returns a single object with a
.valueproperty that can be reassigned directly, like a plain mutable variable - Calling the setter function immediately updates the DOM without re-running the component function at all
Show the answer
A. It returns a value and setter; the setter schedules a re-render rather than mutating
useState(initialValue)returns a two-element array: the current state value, and a setter function to update it — typically destructured asconst [count, setCount] = useState(0). Calling the setter schedules a re-render of the component (and, generally, its children) with the new value; it does not mutate the existing state value in place, and the update is not applied synchronously mid-function the way a plain variable assignment would be — the component function runs again from the top, andcountreflects the new value on that subsequent render, not immediately after calling the setter within the same execution. -
What is the virtual DOM, and what problem does it solve compared to directly manipulating the real DOM on every update?
- It is a caching layer for network requests, unrelated to how the UI itself is rendered
- An in-memory representation React diffs against the previous one, applying minimal DOM changes
- The virtual DOM only exists in production builds; development builds manipulate the real DOM directly for faster debugging
- It is a separate browser API that replaces the real DOM entirely, so no actual DOM nodes are ever created
Show the answer
B. An in-memory representation React diffs against the previous one, applying minimal DOM changes
The virtual DOM is a lightweight, in-memory representation of what the UI should look like — plain JavaScript objects describing elements and their properties, far cheaper to create and compare than actual browser DOM nodes. Rather than directly mutating the real DOM every time state changes (which can be slow, especially with many small updates, since each real DOM mutation can trigger layout/reflow work), React builds a new virtual DOM tree, diffs it against the previous one, and applies only the minimal set of real DOM changes needed to reconcile the difference — batching and minimizing expensive direct DOM operations.
-
What is a controlled component in a React form, as opposed to an uncontrolled one?
- A controlled component's value is driven by React state; an uncontrolled one lets the DOM hold its own value
- They are the same thing; "controlled" and "uncontrolled" only describe which CSS framework styles the input
- A controlled component cannot accept user input at all; only an uncontrolled component can be typed into
- An uncontrolled component requires Redux; a controlled component does not need any state management at all
Show the answer
A. A controlled component's value is driven by React state; an uncontrolled one lets the DOM hold its own value
A controlled component has its form input's value driven entirely by React state — the input's
valueprop is set from state, and anonChangehandler updates that state on every keystroke, so React is always the single source of truth for what the input displays. An uncontrolled component instead lets the DOM itself hold the current value (typically read out later via a ref, e.g.inputRef.current.value), with React not tracking or re-rendering on every keystroke — simpler for a basic form, but harder to validate, transform, or react to changes in real time compared to a controlled input. -
What does React do differently when rendering a list of elements without a unique key prop on each item, compared to providing one?
- React falls back to matching by position, so state can attach to the wrong item after a reorder
- Keys only affect the visual styling applied to list items, with no effect on reconciliation behavior
- Without a key, React refuses to render the list at all and throws a runtime error
- A missing key causes React to re-fetch the entire list's data from the server on every render
Show the answer
A. React falls back to matching by position, so state can attach to the wrong item after a reorder
Without a stable, unique
key, React commonly falls back to using each item's position (index) in the list to match old and new elements during reconciliation — which works fine for a list that never reorders, is never filtered, and never has items inserted/removed from the middle, but otherwise makes React misattribute an existing DOM node (and its internal state) to the wrong logical item as the list changes shape. Providing a stable key tied to the item's actual identity (like a database ID) lets React correctly track which item is which across renders, re-using and correctly repositioning existing elements instead of destroying and recreating them or scrambling their associated state. -
What is the difference between a class component's
render()method and a function component's return value?render()executes once per component's entire lifetime; a function component's body executes on every state or prop change- A function component's return describes the UI like render() does, with hooks instead of lifecycle methods
- Class components can only return a single HTML element; function components can return arbitrarily many top-level elements
- They are unrelated concepts; function components have no equivalent to a class component's render output at all
Show the answer
B. A function component's return describes the UI like render() does, with hooks instead of lifecycle methods
A class component declares a
render()method that React calls to get the JSX (ornull) describing what should currently be displayed, alongside separate lifecycle methods (componentDidMount,componentDidUpdate, etc.) for side effects. A function component is itself the thing React calls each render — its return value (JSX ornull) plays the same rolerender()'s return value does in a class component, but there is no separate lifecycle-method structure; side effects are instead expressed with hooks likeuseEffectinside the same function body, which is the main structural difference between the two component styles beyond syntax. -
React is called declarative. What does a component actually describe?
- The sequence of DOM operations to apply, which React batches and replays in order
- What the UI should be for the current props and state; React works out the DOM changes to get there
- The difference from the previous render, which is why a component must return only what changed
- The final HTML string, which React parses and swaps in wholesale on every state change
Show the answer
B. What the UI should be for the current props and state; React works out the DOM changes to get there
What the UI should look like for the current props and state — not the steps to get there from what is on screen now. You return the markup for this state and React works out the minimal set of DOM changes to make reality match it. That is the whole difference from imperative DOM code, which has to find the elements and mutate them, and it is why reaching for document.querySelector inside a component is a warning sign: it makes a change React does not know about, and the next render can undo it.
-
What does it mean that a React component should be a pure function of its props and state?
- It must return the same element object each time, so React can compare by reference
- It must not read context or state, since only props are passed in explicitly
- It must be a function component rather than a class, since classes hold mutable instance state
- Same props and state give the same output, with no side effects during render
Show the answer
D. Same props and state give the same output, with no side effects during render
Given the same props and state it should render the same output, and rendering should not have side effects — no mutating props, no writing to variables outside itself, no fetching. That is what lets React call it whenever it likes, more than once, and discard the result, which is exactly what StrictMode does in development to surface violations. Side effects go in useEffect or in event handlers, which are the places React has defined for them.
-
A handler calls
setCount(count + 1)twice in a row and the count goes up by one. Why?- The second call runs before the first has been queued, so their order is not guaranteed
- React deduplicates identical setter calls within one handler, which is what discards the second
- Updates are throttled to one per frame, so the second is dropped when they happen close together
- Both calls read the same count from the current render, so use the functional form to build on the latest
Show the answer
D. Both calls read the same count from the current render, so use the functional form to build on the latest
Because state updates are queued and applied before the next render, not written into the variable you are holding. Both calls read the same
countfrom this render’s closure, so both compute the same value and the second simply overwrites the first. The functional form fixes it —setCount(c => c + 1)twice — because each update receives the latest queued value rather than the one captured when the handler was created. For the same reason, readingcountstraight aftersetCount(count + 1)in a handler gave the old value, 0, while the button went on to show 1: the setter asks for a render, and only that next render'suseStatereturns the new value. -
What is
useEffectfor, and what is the dependency array actually doing?- Running code before the component renders, with the array naming what must be ready first
- Synchronising with things outside React; the array names what the effect reads, and re-runs it when those change
- Registering the component with React, with the array listing the props it will receive
- Caching a computation between renders, with the array naming the inputs to the cache key
Show the answer
B. Synchronising with things outside React; the array names what the effect reads, and re-runs it when those change
It is for synchronising a component with something outside React — a subscription, a timer, a fetch, a DOM node — because those must not happen during render. The dependency array names the values the effect reads, and React re-runs it whenever one of them changes; an empty array means it runs once after mount, and omitting the array means after every render. Getting the list wrong is the usual bug: leave a value out and the effect keeps using a stale copy of it.
-
Two sibling components need the same piece of state. Where does it go?
- In a module-level variable both import, since React state cannot be shared between components
- In context, which is the intended mechanism for any state used by more than one component
- In their closest common parent, passed down as props, with changes made through a callback
- Duplicated in both, with an effect in each keeping the two copies synchronised
Show the answer
C. In their closest common parent, passed down as props, with changes made through a callback
In their closest common parent, passed down to both as props — "lifting state up". React data flows one way, so siblings have no channel between them; the shared value has to live above both, and whichever child changes it does so through a callback the parent passed down. That is the default answer, and only when the value is needed far down a deep tree does context or a store become worth its extra indirection.
-
Which line completes this effect, so the subscription is torn down when the component unmounts or the source changes?
useEffect(() => { const sub = source.subscribe(setValue); ___ }, [source]);return sub.unsubscribe;return () => sub.unsubscribe();sub.unsubscribe();useEffect(() => sub.unsubscribe(), []);
Show the answer
B.
return () => sub.unsubscribe();An effect cleans up by returning a function, which React calls before the next run of the effect and once more at unmount. Calling unsubscribe in the body tears the subscription down immediately, so the component never receives a value at all. Returning the method rather than a call looks right and usually is not: React invokes it detached from the subscription, so any implementation using
thisthrows. Nesting a second useEffect calls a hook from inside an effect body, which is not render at all, so React throws an invalid hook call rather than registering anything. -
Which line completes this handler, so two clicks in the same tick increment the counter twice rather than once?
const [count, setCount] = useState(0); function bump() { ___ }setCount((n) => n + 1);setCount(count + 1);count = count + 1;setCount(count++);
Show the answer
A.
setCount((n) => n + 1);count is a constant captured by this render, so
count + 1computes from whatever it was when the render happened — two updates queued before the next render both compute the same value, and the second overwrites the first. The updater form is handed the latest queued value instead, so the two compose. Assigning to count mutates a local binding React never reads, andcount++does the same while also passing the pre-increment value. The rule of thumb: if the next state is derived from the current state, pass a function. -
Which line completes this list, so React can tell the rows apart when they are reordered?
<ul> {rows.map((row, index) => ( ___ ))} </ul><li key={index}>{row.name}</li><li id={row.id}>{row.name}</li><li key={row.id}>{row.name}</li><li>{row.name}</li>
Show the answer
C.
<li key={row.id}>{row.name}</li>A key is how React matches an element in the new tree to one in the old, so it has to identify the row rather than its position. Keying by index says the third item is still the third item after a sort or a deletion, so React keeps the existing DOM node and its state and only changes the text — which is why a half-typed input or a checked checkbox follows the wrong row. Keying by index is fine for a list that is never reordered, filtered or inserted into. id is an ordinary DOM attribute and tells the reconciler nothing; omitting the key falls back to the index with a warning.
-
A reusable
Fieldcomponent needs an id to link its<label htmlFor>to its<input>, and the app is server-rendered. WhyuseId()rather than"f" + Math.random()?- useId returns the same id in every instance, which is what htmlFor requires
- There is no difference once the app is built, since ids are stripped from production HTML
- useId is unique per instance and stable across server and client; random ids mismatch
- useId is faster, since Math.random is too slow to call on every render
Show the answer
C. useId is unique per instance and stable across server and client; random ids mismatch
useIdreturns an id that is unique per component instance and the same on the server and in the browser, because it is derived from the component's position in the tree: twoFields got_R_1_and_R_2_, and hydrating the server HTML reported no errors. A random id differs between the server render and the hydrating one, and React reported that attributes of the server-rendered HTML did not match.useIdis for ids, not for list keys, which should come from the data. -
In React 19,
function Input({ ref, ...props }) { return <input ref={ref} {...props} /> }receives a ref from its parent with noforwardRef. What changed, and where doesuseImperativeHandlefit?- ref became a prop, and useImperativeHandle is now needed for every ref to reach the DOM
- Nothing changed: without forwardRef the ref is undefined, and useImperativeHandle cannot help
- ref became a prop in React 19; useImperativeHandle chooses what the parent's ref exposes
- React 19 removed refs; useImperativeHandle is the only way left to reach a DOM node
Show the answer
C. ref became a prop in React 19; useImperativeHandle chooses what the parent's ref exposes
React 19 passes
refto function components as an ordinary prop, so the parent's ref pointed at the INPUT element;forwardRefstill worked, but is no longer needed. In React 18.3 the same component gotundefined, with the warning "refis not a prop".useImperativeHandle(ref, () => ({ focusAndSelect }))sets what the parent's ref holds to a custom object instead of the DOM node — the parent saw onlyfocusAndSelect, not an HTMLElement — which keeps the component's internals private. -
A component builds classes with
cn("px-2 py-1", active && "px-4"), wherecnistwMerge(clsx(...)). What does each of the two libraries contribute?- clsx removes duplicates and conflicts; tailwind-merge converts the classes into inline styles
- clsx joins the conditional classes; tailwind-merge drops the earlier of two conflicting ones
- They do the same job; projects wrap both only to support older versions of Tailwind
- clsx sorts classes into Tailwind's order; tailwind-merge adds any classes that are missing
Show the answer
B. clsx joins the conditional classes; tailwind-merge drops the earlier of two conflicting ones
clsxassembles the string from conditional parts: it droppedfalseand kept the keys of an object whose values are true, giving "px-2 py-1 px-4". That string still contains two conflicting paddings, and which one wins depends on their order in the generated CSS, not in the attribute.tailwind-mergeknows Tailwind's classes and keeps the last of each conflicting group: "py-1 px-4". It understands overlaps too —p-4 px-2stayed, whilepx-2 p-4became "p-4" — and lefttext-red-500 text-lgalone, since colour and size do not conflict. -
A component keeps
fullNamein state and sets it withuseEffect(() => setFullName(first + " " + last), [first, last]). What does each change oflastcost, and what is simpler?- One render, since React runs the effect before painting and merges its update into it
- An infinite loop, since setting state inside an effect always runs the same effect again
- Two renders, the first still showing the old name; compute it during render instead
- Two renders, both with the new name; the extra one is cheap, so the effect can stay
Show the answer
C. Two renders, the first still showing the old name; compute it during render instead
Two renders, the first with the old name. An effect runs only after a render has been committed, so when
lastchanged to "Byron" the component first rendered "Ada Lovelace" again, then the effect set state and it rendered "Ada Byron"; on mount, its first render showed an empty string. A value that can be worked out from props or state belongs in the render itself —const fullName = first + " " + last— which rendered once each time, with the right name. Effects are for keeping in step with things outside React, not for deriving one value from another. -
A
<Draft user={user} />form keeps its text inuseState. Whenuserswitches from "ada" to "bob", the text typed for ada is still there. What does<Draft key={user} user={user} />change?- Nothing, since a key only matters on elements rendered from an array with map
- React mounts a new Draft for each user, so the text resets whenever the key changes
- React keeps the state but re-renders Draft, which clears every input it contains
- The keyed Draft keeps one copy of its state per user and restores ada's when she returns
Show the answer
B. React mounts a new Draft for each user, so the text resets whenever the key changes
It resets the form. React keeps a component's state for as long as the same type renders in the same place in the tree, and a changed prop does not change that, so the unkeyed draft still held "draft for ada" after the switch. A different
keytells React it is a different component: it unmounted the oldDraftand mounted a new one, and the keyed input was empty. Its state is gone, not set aside — switching back to ada left the keyed input empty too. A key is the usual way to reset state when the thing being edited changes, instead of an effect that clears each field. -
const Theme = createContext("light"). One component callsuseContext(Theme)with no<Theme.Provider>above it, and another sits inside<Theme.Provider value="dark">. What does each read?- "light" outside any provider, from the default, and "dark" inside it
- "light" for both, since the default given to createContext overrides every provider
- An error outside any provider, since useContext needs one above it; "dark" inside
- undefined outside any provider, since the default is only a type hint; "dark" inside
Show the answer
A. "light" outside any provider, from the default, and "dark" inside it
The first reads "light", the default given to
createContext, and the second "dark".useContextreturns the value of the nearest provider above the component, and the default only when there is no provider at all. It is not a fallback for a missing value: inside<Theme.Provider value={undefined}>the component read undefined, not "light".
Practise the rest in the app
GapfyreSWE has 33 more React questions at Intermediate and Advanced level, and over 4,700 across 80+ topics. It works offline and asks for no account.