Skip to content
>_ StartupJobList_

Interview questions · Worked answers

React Interview Questions: 11 Worked Answers

Trace a render and its state through the component tree, then explain when an Effect or shared owner is actually needed.

For: Intermediate React developers

Guide scope and versions

React function components and Hooks. React Native, routers and server frameworks are outside scope; version-specific behavior is labeled.

Question 1 of 11

Why does state still have its old value after a setter?

A render receives a snapshot of props and state. An event handler created during that render closes over that snapshot. A setter queues an update; it does not mutate the local variable in the already-running handler.

Both expressions read the same captured count, so from zero the next state is one. If each update depends on the result of the earlier update, use setCount(current => current + 1) twice. React applies updater functions to queued state in sequence, producing two.

JSX · Worked example
function Counter() {
  const [count, setCount] = useState(0);
  function addWithValueForm() {
    setCount(count + 1);
    setCount(count + 1);
  }
  function addWithUpdaterForm() {
    setCount(current => current + 1);
    setCount(current => current + 1);
  }
  return <>
    <button onClick={addWithValueForm}>value form: {count}</button>
    <button onClick={addWithUpdaterForm}>updater form: {count}</button>
  </>;
}

Starting from zero in a fresh component, the value-form button sets the count to 1 because both updates use the captured zero. The updater-form button sets it to 2 when clicked from zero; if clicked after the value-form button, it takes the current count from 1 to 3.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: Does batching mean React delays every update until an arbitrary timer?

No. Batching groups updates in supported contexts to avoid unnecessary renders; it does not change the snapshot rule or promise a specific wall-clock delay.

Read the source: State as a Snapshot · Queueing a Series of State Updates

↑ Back to questions

Question 2 of 11

What is the difference between render and commit?

A render calculates what the UI should look like from current inputs. React may render without changing the DOM if the output is equivalent. The commit phase applies needed changes to the host environment. Rendering must therefore be pure: it cannot safely perform a network write or mutate a shared external object.

Concurrent work can be interrupted or restarted before commit. Side effects performed during render could then run for UI that never commits. Put user actions in event handlers and external synchronization in Effects with cleanup.

text · Worked example
state update triggers render
component functions calculate next UI
React compares/reconciles output
commit applies necessary DOM changes

The render phase may be restarted, so logging or mutating an external system there can happen for a tree that never reaches the screen. The commit is the point at which React applies the finished update; put synchronization in an Effect or user-caused work in its event handler.

Illustrative, not executed.

Follow-up: If a component function runs, did the browser repaint?

No. A render is not synonymous with a DOM mutation or a visible paint.

Read the source: Render and Commit · Keeping Components Pure

↑ Back to questions

Question 3 of 11

Why do keys affect state?

React uses element type, position and keys to determine component identity in a rendered tree. A stable key lets a list item keep its state when items move. An index key can attach a row's local state to the wrong record after insertion or reorder.

Keys are local identity hints among siblings, not globally unique database IDs by magic. Changing a key intentionally creates a new identity and resets that subtree's state, which can be useful for switching between different records.

JSX · Worked example
items.map(item => <Row key={item.id} item={item} />)

When the first row moves from index 0 to 1, index keys associate the old component state with the new occupant of index 0. Stable item IDs keep each row’s local state with the same record; changing an ID intentionally resets that row.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: Can I use the array index if the list is static?

If order and membership truly never change and there is no local state that could be misassigned, it may be acceptable. Use stable domain IDs when available.

Read the source: Rendering Lists · Preserving and Resetting State

↑ Back to questions

Question 4 of 11

Should derived data be stored in state?

If a value can be calculated from current props and state during render, storing a second copy creates a synchronization problem. Calculate it directly, then memoize only if measurement shows the calculation is costly.

Keeping visible in separate state and updating it in an Effect creates a render where items or query changed but the derived copy is stale. It also adds a second update path. State should represent information that cannot be derived from the other current inputs, such as an in-progress edit.

JSX · Worked example
const visible = items.filter(item => item.name.includes(query));

If query changes from "a" to "b", a separate visible state remains based on "a" until its Effect runs, creating an extra stale render. Calculating the filtered list during render uses the same current items and query snapshot.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: When is useMemo useful?

As a performance optimization for a measured expensive calculation or stable identity needed by a consumer. Correctness must not depend on React retaining that cached value.

Read the source: Choosing the State Structure · You Might Not Need an Effect

↑ Back to questions

Question 5 of 11

When does an Effect belong in a component?

An Effect synchronizes a committed React component with an external system: a subscription, browser API, imperative widget or network connection. It is not the default place for calculations or for responding to a particular button click. Put interaction-specific actions in the event handler that knows which action occurred.

When roomId changes, React cleans up the prior synchronization and establishes the new one. Development Strict Mode may run an extra setup/cleanup cycle to expose missing cleanup; code should tolerate that lifecycle. It does not mean a production user necessarily connects twice.

JSX · Worked example
useEffect(() => {
  const connection = createConnection(roomId);
  connection.connect();
  return () => connection.disconnect();
}, [roomId]);

Changing roomId runs cleanup for the old connection before the replacement setup; unmount also disconnects. Strict Mode’s development setup/cleanup cycle exposes missing cleanup, so the connection code must tolerate being established, released, and established again.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: Should every fetch use an Effect?

No. A framework/data layer or an event-driven submit may be a better owner. An Effect is appropriate when the request truly synchronizes with the currently displayed state and cleanup/stale-result policy is defined.

Read the source: Synchronizing with Effects · You Might Not Need an Effect

↑ Back to questions

Question 6 of 11

How do missing dependencies create stale behavior?

An Effect or callback closes over values from a render. Its dependency list describes the reactive values it reads. Omitting a dependency can leave it using an old value after later renders. Suppressing the lint rule hides the symptom rather than fixing the ownership or synchronization design.

A common repair is to move event-specific work to the event handler, derive a value during render, use a functional state update, or restructure the Effect so it depends on the smallest meaningful input. The dependency list should follow the code, not serve as a manual scheduling switch.

Follow-up: Can I make a dependency stable with useCallback?

Sometimes, but memoizing a function does not fix incorrect captured data or an Effect that should not exist. First decide what behavior is being synchronized.

Read the source: Removing Effect Dependencies · Synchronizing with Effects

↑ Back to questions

Question 7 of 11

How do you prevent an old response from replacing newer results?

If an Effect fetches whenever a query changes, a slower earlier request may finish after a newer one. Clean up by aborting the request when supported and ignore results from an obsolete Effect. Cancellation reduces wasted work; a stale-result guard enforces UI correctness.

This illustrates the publication guard, not complete production error handling. Add loading/error policy and use AbortController for fetch where appropriate. If the request belongs to a submit action, keep it with that event instead of coupling it to every query render.

JSX · Worked example
useEffect(() => {
  let ignore = false;
  fetchResults(query).then(result => {
    if (!ignore) setResults(result);
  });
  return () => { ignore = true; };
}, [query]);

When query B supersedes query A, cleanup sets A's ignore flag, so A's late resolution cannot overwrite B's state. This guard prevents stale UI but does not define loading, error, or submit-action semantics.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: Why guard if the request is aborted?

An operation may already have completed, may not support abort, or may settle while cancellation races. A guard protects the state write.

Read the source: Synchronizing with Effects · React state snapshots

↑ Back to questions

Question 8 of 11

Where should shared state live?

Keep state with the smallest component subtree that owns it. When sibling components need the same source of truth, lift it to their closest common parent and pass data/actions down. Use context or a store when the ownership and access pattern justify them, not simply because state exists.

A cart quantity displayed in a header and cart panel needs one owner or shared store; separate copies can disagree. A tooltip's open state usually belongs near the tooltip. Server data caching is a different concern from transient interface state and may be better handled by a data library/framework.

Follow-up: When does a reducer help?

When several actions update coupled fields and transitions need a named, centralized policy. A reducer is not mandatory just because there are multiple useState calls.

Read the source: Sharing State Between Components · Scaling Up with Reducer and Context

↑ Back to questions

Question 9 of 11

What should a reducer make explicit?

A reducer maps current state and an action to next state. It is useful when transitions have related consequences, such as loading, success, failure and reset. It should remain pure so the same state/action pair yields the same next state; I/O belongs outside it.

This JS example permits inconsistent state if represented with optional fields; a TypeScript discriminated union can encode valid variants. In React, dispatching an action asks for another render; it does not mutate the current state's object.

JS · Worked example
function reducer(state, action) {
  switch (action.type) {
    case 'started': return { status: 'loading' };
    case 'loaded': return { status: 'ready', value: action.value };
    case 'failed': return { status: 'error', message: action.message };
    default: return state;
  }
}

The started action returns a loading state, loaded replaces it with ready data, and failed returns an error state. Unknown actions preserve the current state. A TypeScript union can reject impossible combinations at compile time; this JavaScript reducer still needs tests for each transition.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: Should a reducer perform the request?

No. Keep the reducer deterministic and side-effect free. An event handler, Effect, or data layer performs the request and dispatches its result.

Read the source: Extracting State Logic into a Reducer · Keeping Components Pure

↑ Back to questions

Question 10 of 11

What do memoization APIs guarantee?

useMemo and useCallback can avoid some recalculation or preserve a reference between renders while dependencies stay equal. They are performance tools; React may discard cached values in some situations. Program behavior must remain correct without treating a memo as durable state.

Before adding memoization, measure a real cost or identify a consumer that depends on stable identity. Repeatedly wrapping every value can make dependency logic harder to read without reducing meaningful work.

Follow-up: Should useMemo store an expensive resource that must survive?

No. Store durable component state with state/ref as appropriate, or manage the external resource with an Effect and cleanup. A memo is not a lifecycle guarantee.

Read the source: React useMemo · React useCallback

↑ Back to questions

Question 11 of 11

What makes a custom React control keyboard-accessible?

Start with the native element that already matches the action. A <button> provides keyboard activation, focus behavior and button semantics. A clickable <div> provides none of those by default; adding onClick alone leaves keyboard and assistive-technology users with a different control. For form fields, give each input a programmatic label and connect validation help or errors to the field.

React renders the underlying HTML attributes; it does not supply accessible behavior merely because a component uses JSX. A reusable field component should preserve the label and description relationship and expose a real focusable control. When validation fails, focus management should follow the user flow rather than moving focus on every keystroke.

JSX · Worked example
<button type="button">Save</button>
<label htmlFor="email">Email address</label>
<input id="email" name="email" type="email" aria-describedby="email-help" />
<p id="email-help">We will use this for account notices.</p>

The native button shown supports keyboard focus and activation without custom key handlers. For the field, htmlFor matches the input's id, and aria-describedby points to the help text. A clickable div would need additional keyboard and focus behavior that this example avoids.

Executed with React 19.2.0 and jsdom 27.0.0 on Node.js v24.14.0.

Follow-up: Does adding an ARIA role make a div behave like a button?

No. A role announces semantics; it does not add keyboard handling, focusability or native activation. Use the native element or implement and test every required interaction.

Read the source: MDN button element · W3C WAI form labels · React Quick Start

↑ Back to questions

Salary context

Advertised salaries for these skills

These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.

React posts

422 posts · 422 usable advertised salary amounts

2024-06-04 to 2026-11-06

$150,000

Median advertised minimum, approximate USD/year

Middle 50%: $110,000–$170,000

Explore React salaries → Browse matching job posts →
Currency and calculation basis

Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged React, rather than every job in the broader technology family.

↑ Back to questions

Keep exploring