React interview questions: hooks, rendering and state, explained
The component, hooks and rendering questions front-end developers prepare for, with JSX examples and small runnable models of how React behaves.
React interviews usually test components and JSX, props vs state, the rules of hooks, how useEffect dependencies and cleanup work, why lists need stable keys, controlled vs uncontrolled inputs, memoization (useMemo, useCallback, React.memo), context, error boundaries, and rendering behavior such as batching, StrictMode's double invocation in development and concurrent features like useTransition. Below are 20 questions from basic to advanced; the JSX examples were not executed, and three plain JavaScript models were run and show real output.
Basic react interview questions
Basic1. What is a React component, and what does JSX compile to?
A component is a function that takes props and returns a description of the UI. JSX is syntax that a compiler turns into function calls that create React elements (objects describing what to render), so <Greeting name="Ava" /> becomes a call that passes the component and its props. Component names start with a capital letter so JSX can tell them apart from HTML tags.
JSX · Example (not executed)function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
export default function App() {
return <Greeting name="Ava" />;
}Basic2. What is the difference between props and state?
Props are inputs passed from a parent; a component must treat them as read-only. State is data a component owns and changes over time with its setter, which schedules a re-render. If two components need the same changing data, lift the state up to their closest common parent and pass it down as props.
JSX · Example (not executed)import { useState } from 'react';
function Counter({ label }) { // label: a prop
const [count, setCount] = useState(0); // count: state
return <button onClick={() => setCount(count + 1)}>{label}: {count}</button>;
}Basic3. What are the rules of hooks?
Call hooks only at the top level of a React function component or a custom hook: never inside conditions, loops, nested functions or after an early return. React identifies each hook by its call order, so the order must be the same on every render. Custom hooks are functions whose names start with use and that call other hooks.
Basic4. Why does calling setCount(count + 1) three times only add one?
Each render sees a fixed value of state (a snapshot). setCount(count + 1) queues the same value three times, because count does not change until the next render. Passing an updater function, setCount(c => c + 1), queues functions that React applies in order to the latest pending value. The model below reproduces that queue.
JavaScript model (runs in Node.js; not React itself)// A model of how React processes queued state updates during one render (not React itself).
function processQueue(initial, queue) {
return queue.reduce((state, update) => (typeof update === 'function' ? update(state) : update), initial);
}
const count = 0; // the value this render's event handler closed over
console.log('setCount(count + 1) x3 ->', processQueue(0, [count + 1, count + 1, count + 1]));
console.log('setCount(c => c + 1) x3 ->', processQueue(0, [c => c + 1, c => c + 1, c => c + 1]));Output (Node.js 24.15.0)setCount(count + 1) x3 -> 1 setCount(c => c + 1) x3 -> 3
Basic5. Why does every item in a list need a stable key?
Keys tell React which item is which between renders, so it can keep each item's state and DOM node attached to the right data. Using the array index as a key breaks when items are inserted, removed or reordered: state stays with the position, not the item. Use a stable ID from the data. The model below shows what happens when an item is added at the top.
JavaScript model (runs in Node.js; not React itself)// A model of how list items are matched between renders (not React itself).
const before = [{ id: 'a', text: 'Ava' }, { id: 'b', text: 'Ben' }];
const after = [{ id: 'c', text: 'Cara' }, ...before]; // a new item inserted at the top
const stateByIndex = { 0: 'checked' }; // the user ticked row 0 (Ava) before the insert
const stateById = { a: 'checked' };
console.log('index keys:', after.map((it, i) => `${it.text}=${stateByIndex[i] ?? 'unchecked'}`).join(', '));
console.log('id keys: ', after.map(it => `${it.text}=${stateById[it.id] ?? 'unchecked'}`).join(', '));Output (Node.js 24.15.0)index keys: Cara=checked, Ava=unchecked, Ben=unchecked id keys: Cara=unchecked, Ava=checked, Ben=unchecked
Basic6. What is the difference between controlled and uncontrolled inputs?
A controlled input gets its value from React state and reports changes through onChange, so React is the single source of truth and you can validate or transform as the user types. An uncontrolled input keeps its own value in the DOM; you read it when needed, with a ref or from form data on submit. Controlled inputs suit live validation; uncontrolled ones are simpler for basic forms.
JSX · Example (not executed)import { useState, useRef } from 'react';
function Controlled() {
const [email, setEmail] = useState('');
return <input value={email} onChange={e => setEmail(e.target.value.trim())} />;
}
function Uncontrolled() {
const ref = useRef(null);
return (
<form onSubmit={e => { e.preventDefault(); console.log(ref.current.value); }}>
<input ref={ref} defaultValue="" />
</form>
);
}Basic7. What does lifting state up mean?
When two sibling components need to share or stay in sync on some data, move that state to their closest common parent, pass the value down as props, and pass setter callbacks down so the children can request changes. This keeps one source of truth instead of two copies drifting apart.
Intermediate react interview questions
Intermediate8. How do useEffect dependencies and cleanup work?
An effect runs after React commits a render to the screen. The dependency array controls when it re-runs: on every render with no array, once after mount with an empty array, and whenever a listed value changes otherwise. The function an effect returns is its cleanup, which runs before the effect runs again and when the component unmounts. List every reactive value the effect reads.
JSX · Example (not executed)import { useEffect, useState } from 'react';
function OnlineStatus({ roomId }) {
const [online, setOnline] = useState(false);
useEffect(() => {
const conn = connect(roomId); // connect() is your own subscription code
conn.on('status', setOnline);
return () => conn.disconnect(); // cleanup before re-run and on unmount
}, [roomId]); // re-run only when roomId changes
return <span>{online ? 'online' : 'offline'}</span>;
}Intermediate9. Why do effects run twice in development?
In development, React's StrictMode mounts each component, unmounts it and mounts it again, so effects run, clean up and run again. It is a deliberate check that your cleanup undoes what the effect did; it does not happen in production builds. If the double run causes a visible bug, the effect is usually missing a cleanup.
Intermediate10. How do you avoid race conditions when fetching data in an effect?
If the input changes while a request is in flight, an older, slower response can arrive last and overwrite the newer one. Keep an ignore flag in the effect, set it in the cleanup, and only store the response if the flag is still false (or abort the request with AbortController). The model below runs both versions with two out-of-order responses.
JavaScript model (runs in Node.js; not React itself)// A model of an effect that fetches search results (not React itself).
const fakeFetch = (q, ms) => new Promise(res => setTimeout(() => res(`results for "${q}"`), ms));
let shown;
function effect(query, ms, useIgnore) {
let ignore = false;
fakeFetch(query, ms).then(r => { if (!useIgnore || !ignore) shown = r; });
return () => { ignore = true; }; // cleanup: runs when the query changes
}
(async () => {
for (const useIgnore of [false, true]) {
shown = undefined;
const cleanup = effect('re', 50, useIgnore); // older request, slow
cleanup(); // the user kept typing
effect('react', 10, useIgnore); // newer request, fast
await new Promise(r => setTimeout(r, 80));
console.log(useIgnore ? 'with ignore flag: ' : 'without ignore flag:', shown);
}
})();Output (Node.js 24.15.0)without ignore flag: results for "re" with ignore flag: results for "react"
Intermediate11. What is the difference between useMemo, useCallback and React.memo?
useMemo caches the result of a calculation between renders until its dependencies change. useCallback caches a function definition, which matters when the function is passed to a memoized child or used as an effect dependency. React.memo wraps a component so it skips re-rendering when its props are unchanged by shallow comparison. They are performance tools: measure first, because they add their own cost.
JSX · Example (not executed)import { memo, useCallback, useMemo, useState } from 'react';
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
function List({ items, query }) {
const [selected, setSelected] = useState(null);
const visible = useMemo(() => items.filter(i => i.name.includes(query)), [items, query]);
const onSelect = useCallback(id => setSelected(id), []);
return <ul>{visible.map(i => <Row key={i.id} item={i} onSelect={onSelect} />)}</ul>;
}Intermediate12. When should you use context?
Context passes a value deep into the tree without threading props through every level: themes, the current user, locale. Every component that reads a context re-renders when its value changes, so avoid putting fast-changing values in a broad context, split unrelated values into separate contexts, and memoize the provided object. For local data, plain props are clearer.
JSX · Example (not executed)import { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext('light');
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
function ToggleButton() {
const { theme, setTheme } = useContext(ThemeContext);
return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>{theme}</button>;
}Intermediate13. What is useRef for?
useRef returns a mutable object whose .current value persists across renders without causing a re-render when it changes. Use it to hold a DOM node (for focus or measuring), a timer ID, or the previous value of something. Do not read or write ref.current during rendering for values that affect output; use state for that. In React 19, function components can also receive ref as a regular prop.
JSX · Example (not executed)import { useEffect, useRef } from 'react';
function SearchBox() {
const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus(); }, []); // focus once after mount
return <input ref={inputRef} placeholder="Search" />;
}Intermediate14. What is a custom hook?
A custom hook is a function whose name starts with use and that calls other hooks to package reusable stateful logic, such as subscribing to window size or online status. Each component that calls it gets its own independent state; custom hooks share logic, not state.
JSX · Example (not executed)import { useEffect, useState } from 'react';
export function useWindowWidth() {
const [width, setWidth] = useState(() => window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
return width;
}Advanced react interview questions
Advanced15. How does React decide what to update (reconciliation)?
After a state change React re-renders the affected components and compares the new element tree with the previous one. If an element's type changes (a div becomes a section, or one component becomes another), React tears down that subtree and builds a new one, losing its state. If the type is the same it updates props in place, and in lists it matches children by key. That is why changing a key on purpose is a way to reset a component's state.
Advanced16. What is automatic batching?
Since React 18, multiple state updates made in the same event, timeout, promise callback or native handler are batched into a single re-render. Before React 18, updates outside React event handlers were not batched. flushSync opts out when you need the DOM updated immediately, which is rarely necessary.
JSX · Example (not executed)function SaveButton() {
const [saving, setSaving] = useState(false);
const [status, setStatus] = useState('');
async function save() {
setSaving(true); setStatus('Saving'); // one render
await saveDraft();
setSaving(false); setStatus('Saved'); // also one render (batched since React 18)
}
return <button disabled={saving} onClick={save}>{status || 'Save'}</button>;
}Advanced17. What are error boundaries?
An error boundary is a component that catches errors thrown while rendering its children and shows a fallback UI instead of unmounting the whole app. It is written as a class component with static getDerivedStateFromError (to render the fallback) and componentDidCatch (to log). Error boundaries do not catch errors in event handlers, asynchronous code or the boundary itself; handle those with try/catch.
JSX · Example (not executed)import { Component } from 'react';
class ErrorBoundary extends Component {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
componentDidCatch(error, info) { logError(error, info.componentStack); }
render() { return this.state.failed ? this.props.fallback : this.props.children; }
}
// <ErrorBoundary fallback={<p>Something went wrong.</p>}><Dashboard /></ErrorBoundary>Advanced18. What do useTransition and useDeferredValue do?
Both mark some updates as non-urgent so React can keep the interface responsive. useTransition gives you startTransition to wrap a state update (such as filtering a large list) and an isPending flag; urgent updates like typing are handled first and the transition can be interrupted. useDeferredValue gives you a version of a value that lags behind during heavy rendering. They help with rendering cost, not with slow network requests by themselves.
JSX · Example (not executed)import { useState, useTransition } from 'react';
function Search({ allItems }) {
const [query, setQuery] = useState('');
const [results, setResults] = useState(allItems);
const [isPending, startTransition] = useTransition();
function onChange(e) {
setQuery(e.target.value); // urgent: keep typing snappy
startTransition(() => setResults(allItems.filter(i => i.includes(e.target.value))));
}
return (<><input value={query} onChange={onChange} />{isPending && <p>Updating</p>}<List items={results} /></>);
}Advanced19. What is the difference between server and client components?
In frameworks that support React Server Components (such as Next.js App Router), server components run on the server, can read data directly and send no JavaScript for themselves to the browser, but cannot use state, effects or browser APIs. Client components, marked with the 'use client' directive at the top of a file, run in the browser (and are pre-rendered on the server) and handle interactivity. Server components can render client components, passing serializable props.
Advanced20. How do you find and fix slow React renders?
Measure first with the React DevTools Profiler to see which components render and how long they take. Common fixes are keeping state close to where it is used, splitting large components, memoizing expensive calculations and stable callbacks for memoized children, virtualizing long lists so only visible rows render, and code-splitting rarely used screens with lazy() and Suspense.
JSX · Example (not executed)import { lazy, Suspense } from 'react';
const Reports = lazy(() => import('./Reports')); // loaded only when first rendered
function App({ showReports }) {
return (
<Suspense fallback={<p>Loading</p>}>
{showReports && <Reports />}
</Suspense>
);
}How to practice with this page
- Build each JSX example in a fresh project (for example with Vite) and change one line at a time.
- Predict what renders, and how many times, before you run it; then check with React DevTools.
- Explain one bug you fixed with a missing or wrong effect dependency.
- Front-end roles also test JavaScript itself: pair this page with the JavaScript questions.
Related interview prep
Scope, closures and the event loop, with real output.
Open →RoleWeb developer interview questionsRole-specific questions.
Open →QuestionsSystem design interview questionsFront-end and back-end design rounds.
Open →MethodSTAR methodStructure answers about projects and incidents.
Open →Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.
Questions people ask
What React questions are asked in interviews?
Which React version should I prepare for?
Were the React examples on this page run?
How do I prepare for a React coding interview?
Do I need to know JavaScript well for a React interview?
How this page is built
TryHired wrote these questions and answers. Every JavaScript model on this page was executed with Node.js 24.15.0 when the page was built, and the output shown is the real output; the models illustrate React behavior and are not React itself. Blocks marked Example (not executed) are code that could not run on the build machine (no Java runtime, no React runtime): no output is claimed for them. The question list is general practice: it does not predict what a particular employer will ask.
- Interviewers ask different questions for different roles and levels.
- Answers are short explanations, not complete references.
- No React runtime was available when this page was built: JSX blocks are examples, not executed.
- The executed JavaScript blocks are simplified models of React's behavior, written to illustrate one idea each; they are not React's implementation.
- React documentation (react.dev), Learn and API reference: https://react.dev/reference/react
- react.dev, Rules of Hooks: https://react.dev/reference/rules/rules-of-hooks
- react.dev, Synchronizing with Effects: https://react.dev/learn/synchronizing-with-effects
- react.dev, Queueing a series of state updates: https://react.dev/learn/queueing-a-series-of-state-updates
- react.dev, Preserving and resetting state: https://react.dev/learn/preserving-and-resetting-state
- react.dev, React 19 release notes: https://react.dev/blog/2024/12/05/react-19