React Interview Questions
Work through React state, effects, reconciliation, forms, accessibility, testing, and production performance.
Explained React questions
How do hooks and effect dependencies work when fetching API data?
Hooks let function components use React state and lifecycle-related behavior. An effect runs after a commit; its dependency list must include every reactive value it reads. For requests that can be superseded, cleanup should abort the old request or mark its result stale so an earlier response cannot overwrite newer state. Prefer framework or query-library data loading when the app already provides it.
Example
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) throw new Error('Search failed');
return response.json();
})
.then(setResults)
.catch((error) => {
if (error.name !== 'AbortError') setError(error.message);
});
return () => controller.abort();
}, [query]);
Why it works
The effect is tied to the current query. Cleanup runs before the next setup and on unmount, preventing stale requests from committing results after the query changes.
Common mistakes
- Omitting a dependency to silence reruns and thereby reading stale state.
- Assuming requests resolve in the order they were sent.
- Ignoring non-success HTTP status codes because fetch itself resolved.
Follow-up questions
- When should work happen in an event handler instead of an effect?
- How would you cache or deduplicate repeated requests?
Real-world use
Race-safe effects matter for search, route changes, and any UI where users can trigger a second request before the first finishes.
Further reading: React: Synchronizing with Effects · React: You might not need an Effect
What are reconciliation and keys, and when should a component be memoized?
React compares the next element tree with the previous one to determine updates. Keys identify siblings across renders so React can preserve the right component and DOM state when items are inserted, removed, or reordered. memo, useMemo, and useCallback can avoid work when inputs are stable, but they add complexity and do not replace fixing expensive rendering or data flow.
Example
function TodoList({ todos }) {
return todos.map((todo) => (
<TodoRow key={todo.id} todo={todo} />
));
}
Why it works
A stable database or domain identifier lets React match the same logical item after reordering. An array index can point to a different item when the list changes.
Common mistakes
- Using array indexes as keys for reorderable or editable lists.
- Generating random keys on each render, which remounts components.
- Adding memoization without measuring whether a real bottleneck exists.
Follow-up questions
- How can an unstable object prop defeat memoization?
- What does changing a component key intentionally reset?
Real-world use
Profile a slow interaction first; stable keys and appropriately scoped state often solve more issues than blanket memoization.
Further reading: React: Rendering Lists · React: memo
How would you choose between local state, context, and a state-management library?
Keep state close to the components that own it. Lift state when siblings need to coordinate; use context for values needed by a broad subtree, such as a theme or current identity. A dedicated state or server-cache library becomes useful when updates, derived state, persistence, or asynchronous cache behavior are difficult to manage with local state and context alone. Forms should provide labels, validation feedback, and a clear distinction between client-side checks and server validation.
Example
function EmailField({ value, onChange, error }) {
return (
<div>
<label htmlFor='email'>Email address</label>
<input id='email' type='email' value={value} onChange={onChange}
aria-invalid={Boolean(error)} aria-describedby={error ? 'email-error' : undefined} />
{error && <p id='email-error' role='alert'>{error}</p>}
</div>
);
}
Why it works
Explicit ownership limits unnecessary rerenders and makes updates easier to reason about. Labels and associated error text help assistive technology users understand both the field and its validation state.
Common mistakes
- Putting all application state in one context, causing broad updates.
- Treating browser validation as a replacement for server-side validation.
- Displaying an error without associating it with its control.
Follow-up questions
- How can a context value be split to reduce rerenders?
- Which validation rules must run on the server?
Real-world use
Choose the lightest state mechanism that expresses the data's lifetime and sharing needs, then test keyboard and screen-reader interactions.
Further reading: React: Sharing State Between Components · W3C: Forms Tutorial
How do you handle React errors, test accessible behavior, and debug production rendering?
An error boundary can catch rendering errors in its descendant tree and show a recovery UI; it does not catch every asynchronous error or event-handler exception. Test observable user behavior, including labels, keyboard interaction, loading and failure states. In production, correlate client errors with route, release, and source maps while avoiding sensitive user data. Use the React Profiler and browser performance tools to identify actual render or network bottlenecks.
Example
import React from 'react';
class ErrorBoundary extends React.Component {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() {
return this.state.failed
? <p role='alert'>This section could not be displayed.</p>
: this.props.children;
}
}
Why it works
A boundary isolates render-time failures in a subtree, while semantic roles and labels make the fallback and normal UI testable without relying on implementation details.
Common mistakes
- Expecting an error boundary to catch a rejected promise or an error in the boundary itself.
- Testing only component internals rather than accessible user-facing behavior.
- Logging full request data or personal information in client diagnostics.
Follow-up questions
- How would you reset a boundary after the user changes route or input?
- How do you tell a slow render from a slow API request?
Real-world use
Use boundaries for recoverable page regions, automated tests for core flows, and privacy-aware telemetry to diagnose real user failures.
Further reading: React: Error Boundaries · Testing Library: Guiding Principles
How do you prevent stale API responses from overwriting newer React state?
When a component starts a request for one input and then starts another, the first response may arrive last. Tie each request to the current effect and cancel it with AbortController where supported, or ignore its result during cleanup. Also model loading, success, and failure states explicitly; cancellation is expected control flow, not a user-facing failure.
Example
useEffect(() => {
const controller = new AbortController();
setStatus('loading');
fetch(`/api/users?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) throw new Error('Request failed');
return response.json();
})
.then((data) => {
setUsers(data);
setStatus('success');
})
.catch((error) => {
if (error.name !== 'AbortError') setStatus('error');
});
return () => controller.abort();
}, [query]);
Why it works
React runs the previous effect's cleanup before setting up the effect for a changed query. Aborting prevents an obsolete request from committing results after the user has moved on.
Common mistakes
- Assuming network responses arrive in request order.
- Suppressing dependency warnings instead of ensuring the effect uses current values.
- Showing an error state when a request was intentionally aborted.
Follow-up questions
- When would a query cache be preferable to a component-owned effect?
- How should a screen announce loading and error states accessibly?
Real-world use
Use cancellation or request identity for search boxes, route-driven data, and any rapidly changing filter to prevent flickering or incorrect results.
Further reading: React: Synchronizing with Effects · MDN: AbortController