React Interview Questions
Answers written to be said out loud in an interview — each with a common follow-up question and a link to the tutorial that explains it in depth.
- Beginner
- 10
- Intermediate
- 12
- Experienced
- 7
01Why does calling setCount(count + 1) twice only add one?Beginner
Both calls read count from the same render, so both schedule the same value. Use the updater form setCount(c => c + 1) so each update receives the latest value.
02Why do list items need keys, and why not use the array index?Beginner
Keys let React match items between renders. If items are reordered, inserted or removed, index keys can attach state to the wrong item. Use a stable unique id.
03What is JSX?Beginner
A syntax extension that lets you write HTML-like markup in JavaScript. A build tool compiles it into function calls that create React elements. Expressions go inside { }.
04Props vs state?Beginner
Props are inputs passed from a parent and are read-only inside the component. State is data a component owns and changes over time with a setter, triggering a re-render.
05What is a controlled component?Beginner
A form input whose value is driven by React state (value + onChange). React is the single source of truth, so you can validate or transform input as the user types.
06What is React, and what problem does it solve?Beginner
A JavaScript library for building user interfaces from components. You describe what the UI should look like for the current state, and React updates the DOM efficiently when state changes, instead of you writing manual DOM updates.
07What is a component, and what rules must it follow?Beginner
A function that returns JSX. Its name must start with a capital letter, it must be pure during rendering (same props and state → same output, no side effects), and it must not mutate props.
08How do you pass data from a child to a parent?Beginner
Pass a callback function as a prop. The child calls it with the data (onSave(product)) and the parent updates its own state. Data flows down through props; events flow up through callbacks.
09How do you render something conditionally?Beginner
Use if/else before the return, the ternary operator (cond ? <A /> : <B />) or && for “show or nothing”. Beware {count && <Badge />}: if count is 0, React renders 0.
10How do event handlers differ in React?Beginner
They are camelCase props (onClick, onChange) that take a function, not a string. Pass the function (onClick={save}), do not call it (onClick={save()}). Call e.preventDefault() explicitly; returning false does nothing.
11When should you use useEffect, and when not?Intermediate
Use it to synchronise with external systems: network requests, subscriptions, timers, DOM APIs. Do not use it to derive values from props/state (compute during render) or to respond to user events (use the event handler).
12What is the virtual DOM and reconciliation?Intermediate
React builds a lightweight tree describing the UI. When state changes, it renders a new tree, compares it with the previous one (reconciliation) and applies the minimal set of real DOM updates.
13When would you use useRef?Intermediate
To hold a mutable value that persists across renders without causing a re-render (timer IDs, previous values), or to access a DOM element directly (focusing an input).
14useContext — what problem does it solve, and what are its drawbacks?Intermediate
It avoids prop drilling by letting deeply nested components read shared values (theme, user). Every consumer re-renders when the context value changes, so split contexts and memoise values for frequently changing data.
15useState vs useReducer?Intermediate
useState is ideal for simple independent values. useReducer suits complex state with many related transitions, keeping update logic in one pure function that is easy to test.
16What is a custom hook?Intermediate
A function whose name starts with use and that calls other hooks, so stateful logic (fetching, form state, media queries) can be shared between components. Each component that calls it gets its own independent state.
function useOnline() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return online;
}
17What does the cleanup function in useEffect do?Intermediate
It runs before the effect runs again and when the component unmounts. Use it to unsubscribe, clear timers, abort fetches and remove listeners, otherwise you leak memory or update unmounted components.
18How do you map class lifecycle methods to hooks?Intermediate
componentDidMount → useEffect with []. componentDidUpdate → useEffect with dependencies. componentWillUnmount → the effect’s cleanup. shouldComponentUpdate → React.memo. Think in synchronisation rather than lifecycle events.
19How does React Router handle URLs and parameters?Intermediate
Routes map paths to elements; <Link> navigates without a page reload; useParams reads :id segments, useSearchParams reads the query string and useNavigate navigates in code. Nested routes render into <Outlet />.
20How do you handle loading and error states when fetching data?Intermediate
Keep status explicitly (idle, loading, success, error) or use a data library like TanStack Query. Show a skeleton while loading, a helpful error with a retry, an empty state for no results, and ignore responses from outdated requests.
21What is prop drilling, and how do you avoid it?Intermediate
Passing props through several layers that do not use them. Fix it with composition (pass children or elements), context for truly global data (theme, user), or a state library for complex shared state.
22How do you validate forms in React?Intermediate
Validate on submit (and optionally on blur), keep errors in state, show messages next to fields with aria-describedby, and disable the submit button while sending. Libraries like React Hook Form with zod reduce re-renders and boilerplate.
23What are React.memo, useMemo and useCallback for?Experienced
React.memo skips re-rendering a component when its props are unchanged. useMemo caches an expensive computed value. useCallback caches a function reference so memoised children don’t re-render. Measure first; they add complexity.
24What are error boundaries?Experienced
Components that catch rendering errors in their child tree and show a fallback UI instead of crashing the whole app. They do not catch errors in event handlers or async code.
25How do you implement protected routes?Experienced
Wrap private routes in a component that checks auth state; while loading show a spinner, if unauthenticated redirect to /login with the intended location, otherwise render the children. Always enforce authorization on the server too.
26How do you code-split a React app?Experienced
Use React.lazy with dynamic import() for routes and heavy components, wrapped in <Suspense fallback>. The bundler creates separate chunks loaded on demand, shrinking the initial download.
27How do you test React components?Experienced
With React Testing Library and Vitest or Jest: render the component, find elements the way a user would (getByRole, getByLabelText), interact with userEvent and assert on what is visible. Mock the network with MSW rather than mocking fetch internals.
28How do you store and send an authentication token in a React app?Experienced
Prefer an httpOnly, Secure, SameSite cookie set by the server, so JavaScript cannot read it. If you must use a bearer token, keep it in memory, refresh it with a cookie-based endpoint and add it in one fetch wrapper or Axios interceptor.
29How do you make a React app accessible?Experienced
Use semantic HTML before ARIA, label every input, manage focus after route changes and in modals, keep everything keyboard-operable, announce async updates with aria-live, and test with eslint-plugin-jsx-a11y, axe and a screen reader.