React powers the front end of a huge share of today’s web apps, from startups to Meta, Netflix and Flipkart, so React interview questions are part of almost every front-end and full-stack interview. Freshers get asked about JSX, props and state, hooks and keys. Experienced developers get re-renders and memoization, the rendering lifecycle, concurrent features, React 19 Actions and how they would structure a large app.
This page has the 100 React interview questions asked most often, with clear answers, grouped for freshers, intermediate and experienced candidates and updated for React 19. 83 answers include code that you can run in your browser with one click: you see the live UI, can click around in it, edit the code and run it again. The output shown under each example comes from that same preview. You also get a re-render visualiser, a “guess the output” game and 20 React coding questions that test your component automatically. Prefer to study offline? Download all 100 questions as a free PDF.
What you will find on this page
- 100 questions with answers in three levels: 40 for freshers, 35 intermediate, 25 for experienced developers.
- React 19, hooks and performance: JSX, components, props and state, every common hook, lists and keys, forms, context, rendering and reconciliation, memoization, Suspense, transitions, Actions, Server Components and the React Compiler.
- 83 runnable examples with a live preview: press “Run this code”, click around in the result, change the code and run it again.
- Interactive tools: an online React editor, a re-render visualiser and a “guess the output” game.
- 20 React coding questions (counter, todo list, tabs, custom hooks, pagination and more) that check your answer automatically.
- Study tools: filters by level and topic, search, and a “Done” button on every question that remembers your progress.
- A free 95-page PDF of everything.
Also useful (each opens our own guide):
Study these 100 questions your way
Filter the React interview questions by level or topic, or search them. Press “Mark as done” under each question you have finished; your progress is saved in this browser.
No questions match these filters. Try another topic or clear the search.
How to prepare for a React interview
- Get the JavaScript basics right first. Closures, this, array methods, promises and the event loop explain most “why does React do that?” questions. Our JavaScript interview questions cover them.
- Know the classic comparisons: props vs state, controlled vs uncontrolled, useEffect vs useLayoutEffect, useMemo vs useCallback, memo vs useMemo, Context vs Redux, CSR vs SSR.
- Be able to explain rendering: what triggers a re-render, how reconciliation and keys work, and how to avoid unnecessary renders. The visualiser below makes this concrete.
- Build small components from scratch without an IDE: a counter, a todo list, tabs, a search filter and custom hooks like useDebounce. Machine coding rounds ask exactly these.
- For 2+ years of experience, revise React 18 and 19 features (transitions, Suspense, Actions, use, Server Components), performance profiling, testing with React Testing Library, and how you structured a real project.
Practise React in your browser
These three tools run real React 19 on this page, with nothing to install. React loads the first time you press Run or Start (about 250 KB), so the page itself stays fast.
Online React editor with live preview
Write a component called App (or export one as default) and press Run or Ctrl + Enter. The preview is live, so you can click buttons and type in it, and console.log output appears below it. You can import from react and react-dom; hooks such as useState are also available without an import.
Run React online
Runs in your browser with React 19. Nothing is sent to a server.
Re-render visualiser
“Why did this component re-render?” is one of the most common React interview questions. Press Start, then change the state and watch which components flash. Turn on React.memo to see which renders it skips, and then break it by passing a new object on every render.
Watch React re-render
A yellow flash means that component’s function just ran. The counter shows how many times each one has rendered.
Guess the output: 15 tricky React snippets
Interviewers love short snippets with a surprising result: batching, effect order, stale state and memo traps. Pick an answer for each one and read why. Every answer was checked by running the code in React 19.
What does this React code do?
15 snippets, about five minutes. The snippets leave out imports to stay short.
React interview questions for freshers
These 40 basic React interview questions cover what campus placements and first front-end interviews ask: JSX, components, props and state, events, forms, lists and keys, the core hooks, context and data fetching.
1. What is React and why is it so popular?
React is a JavaScript library for building user interfaces, created at Facebook (now Meta) and released as open source in 2013. You describe what the UI should look like for a given state, and React updates the page when that state changes. It handles only the view layer, so routing, data fetching and global state come from other libraries or from frameworks built on React, such as Next.js.
- Component based: the UI is split into small, reusable pieces that each manage their own logic.
- Declarative: you write what the screen should show, not the step-by-step DOM changes to get there.
- Efficient updates: React compares the new UI description with the old one and changes only what is different in the real DOM.
- One-way data flow: data moves from parent to child through props, which makes bugs easier to trace.
- Huge ecosystem: React Native for mobile apps, Next.js for full-stack apps, and thousands of component libraries.
Most front-end job listings in India mention React, which is why React interview questions come up in almost every front-end and full-stack hiring process. React builds on plain JavaScript, so revise closures, this and the event loop from our JavaScript interview questions too.
2. What is JSX?
JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. Browsers cannot run it directly: a compiler such as Babel, SWC or esbuild turns each tag into a function call that creates a React element, a plain object that describes what to show.
function App() {
const name = "Riya";
const marks = 87;
const element = <h3 className="greet">Hello, {name}!</h3>;
console.log(typeof element, element.type, element.props.className);
return (
<div>
{element}
<p>Result: {marks >= 40 ? "Pass" : "Fail"} ({marks}%)</p>
<p>{[1, 2, 3].map(n => n * 2).join(", ")}</p>
</div>
);
}Output:
On the first render:
Screen:
Hello, Riya!
Result: Pass (87%)
2, 4, 6
Console:
object h3 greet- Put any JavaScript expression inside
{ }; statements such as if and for are not allowed there (use a ternary,&&or map). - Use
classNameinstead of class andhtmlForinstead of for, and write attributes in camelCase (onClick,tabIndex). - A component must return a single root element; wrap siblings in a div or a Fragment (question 14).
- Every tag must be closed, including
<img />and<br />. - JSX escapes values before inserting them, which protects you from most XSS attacks.
3. What is the virtual DOM?
The virtual DOM is a lightweight JavaScript description of the UI, made of the plain objects that your components return. When state changes, React calls your components again to get a new description, compares it with the previous one (this is called reconciliation or diffing) and then applies only the differences to the real DOM, in one batch.
- State or props change.
- React re-renders the affected components and gets a new tree of elements.
- React diffs the new tree against the old one.
- React commits the minimal set of real DOM changes, then runs effects.
Real DOM operations, especially ones that trigger layout, are the expensive part, so batching and minimising them keeps the page fast. The virtual DOM is not magic, though: careful hand-written DOM code can be faster. Its real benefit is that you write the UI as a function of state and let React work out the updates. Question 41 covers the diffing rules.
4. What are components? What is the difference between function and class components?
A component is a reusable piece of UI: a JavaScript function (or class) that takes inputs called props and returns what should appear on the screen. Component names must start with a capital letter, otherwise React treats them as HTML tags.
import { useState, Component } from "react";
function Greeting({ name }) { // function component
const [likes, setLikes] = useState(0);
return <p>Hi {name}, likes: {likes} <button onClick={() => setLikes(likes + 1)}>Like</button></p>;
}
class OldGreeting extends Component { // class component
state = { likes: 0 };
render() {
return <p>Hello {this.props.name}, likes: {this.state.likes} <button onClick={() => this.setState({ likes: this.state.likes + 1 })}>Like</button></p>;
}
}
export default function App() {
return <div><Greeting name="Riya" /><OldGreeting name="Aman" /></div>;
}Output:
After clicking the first "Like" button twice:
Screen:
Hi Riya, likes: 2 [Like]
Hello Aman, likes: 0 [Like]| Function component | Class component | |
|---|---|---|
| State and lifecycle | Hooks (useState, useEffect…) | this.state, this.setState and lifecycle methods |
| this keyword | Not used | Needed everywhere |
| Code size | Shorter | More boilerplate |
| Status | The standard way since React 16.8 (2019) | Still supported, mostly in older code; needed only for error boundaries |
5. What are props?
Props (properties) are the inputs a parent passes to a child component, written like HTML attributes. They can be any JavaScript value: strings, numbers, arrays, objects, functions and even other elements. Props are read-only: a component must never change its own props.
function CourseCard({ title, price, tags = [], onBuy }) {
return (
<div style={{ border: "1px solid #ccc", padding: 8, marginBottom: 8, borderRadius: 8 }}>
<b>{title}</b> - Rs {price}
<div>{tags.join(" · ")}</div>
<button onClick={() => onBuy(title)}>Buy</button>
</div>
);
}
export default function App() {
const handleBuy = title => console.log("Buying", title);
return (
<>
<CourseCard title="DSA Course" price={999} tags={["Java", "C++"]} onBuy={handleBuy} />
<CourseCard title="SQL Basics" price={0} onBuy={handleBuy} />
</>
);
}Output:
After clicking the first "Buy" button:
Screen:
DSA Course - Rs 999
Java · C++
[Buy]
SQL Basics - Rs 0
[Buy]
Console:
Buying DSA CourseDestructuring the props object in the parameter list, with defaults like tags = [], is the common style. Strings can be passed in quotes; everything else needs { }. Passing a function such as onBuy is how a child talks back to its parent (question 29).
6. What is state? How does useState work?
State is data that belongs to a component and can change over time, such as a counter value, form input or whether a menu is open. useState(initial) returns a pair: the current value and a setter function. Calling the setter stores the new value and tells React to re-render the component.
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const [open, setOpen] = useState(false);
console.log("render with count =", count);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(0)}>Reset</button>
<button onClick={() => setOpen(o => !o)}>{open ? "Hide" : "Show"} details</button>
{open && <p>State changes trigger a re-render.</p>}
</div>
);
}Output:
After clicking "+1" twice and then "Show details":
Screen:
Count: 2
[+1][Reset][Hide details]
State changes trigger a re-render.
Console:
render with count = 0
render with count = 1
render with count = 2
render with count = 2Each component instance has its own state, and React keeps it between renders. Ordinary variables declared inside the component are recreated on every render, so they cannot remember anything (question 37).
7. What is the difference between props and state?
| Props | State | |
|---|---|---|
| Owned by | The parent component | The component itself |
| Can the component change it? | No, read-only | Yes, with its setter |
| Purpose | Configure a child from outside | Remember data that changes over time |
| Changing it causes | A re-render of the child (when the parent passes new props) | A re-render of the component and its children |
| Example | <Button label="Save" /> | const [saving, setSaving] = useState(false) |
The two work together: a parent keeps something in state and passes it down as a prop. When the parent updates its state, the child receives new props and re-renders. This one-way flow is the core idea behind React.
8. Why should you not modify state directly?
React decides whether to re-render by comparing the old and new state with Object.is. If you change an object or array in place and pass the same reference to the setter, React sees “no change” and skips the update. Mutating also breaks features that rely on old values, such as undo, memo and transitions.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState(["Learn JSX"]);
function addWrong() {
todos.push("Wrong way"); // mutates the same array
setTodos(todos); // same reference: React bails out
}
function addRight() {
setTodos([...todos, "Right way"]); // a new array
}
return (
<div>
<button onClick={addWrong}>Add (mutate)</button>
<button onClick={addRight}>Add (copy)</button>
<ul>{todos.map((t, i) => <li key={i}>{t}</li>)}</ul>
</div>
);
}Output:
After clicking "Add (mutate)" twice (try "Add (copy)" yourself):
Screen:
[Add (mutate)][Add (copy)]
Learn JSXCreate new arrays with spread, map and filter, and new objects with { ...obj, key: value }. When you finally click “Add (copy)”, both hidden “Wrong way” items appear at once, which is exactly the kind of confusing bug mutation causes.
9. How do you render a list? Why do lists need keys?
Render a list by mapping an array to elements. Each element needs a key prop that is unique among its siblings and stable between renders. React uses keys to match items in the old list with items in the new list, so it can reuse, move or remove the right DOM nodes and keep each item’s state attached to the right item.
const students = [
{ id: 101, name: "Riya", score: 91 },
{ id: 102, name: "Aman", score: 78 },
{ id: 103, name: "Neha", score: 85 }
];
function NoKeys() {
return <ul>{students.map(s => <li>{s.name}</li>)}</ul>;
}
export default function App() {
return (
<div>
<ol>
{students.map(s => <li key={s.id}>{s.name}: {s.score}</li>)}
</ol>
<NoKeys />
</div>
);
}Output:
On the first render:
Screen:
Riya: 91
Aman: 78
Neha: 85
Riya
Aman
Neha
Console:
Each child in a list should have a unique "key" prop. Check the render method of `NoKeys`.The missing key in NoKeys triggers a warning in development. Use an ID from your data; avoid array indexes when the list can be reordered, filtered or added to at the start (question 42). Keys are not passed to the component as a prop; if the child needs the ID, pass it separately.
10. How do you render something conditionally?
import { useState } from "react";
function Status({ loading, error, user }) {
if (loading) return <p>Loading...</p>; // early return
if (error) return <p style={{ color: "crimson" }}>Error: {error}</p>;
return <p>Welcome, {user}!</p>;
}
export default function App() {
const [cart, setCart] = useState(0);
const [admin] = useState(true);
return (
<div>
<Status loading={false} error={null} user="Riya" />
{cart > 0 && <p>{cart} items in cart</p>}
{admin ? <button>Admin panel</button> : <span>Viewer</span>}
{cart === 0 ? <p>Cart is empty</p> : null}
<button onClick={() => setCart(c => c + 1)}>Add item</button>
</div>
);
}Output:
On the first render:
Screen:
Welcome, Riya!
[Admin panel]
Cart is empty
[Add item]Use an early return for whole-component states, the ternary for either/or, and && to show something or nothing. Watch out for {count && <p>...</p>} when count is 0: React renders the 0. Write count > 0 && instead. Returning null renders nothing.
11. How do you handle events in React?
Pass a function to a camelCase prop such as onClick, onChange or onSubmit. React gives the handler a synthetic event, a cross-browser wrapper with the same interface as the native event (e.target, e.preventDefault(), e.stopPropagation()).
export default function App() {
function handleClick(e) {
console.log("clicked", e.target.textContent, "| type:", e.type);
}
function greet(name) {
console.log("Hello", name);
}
return (
<div onClick={() => console.log("div heard it too (bubbling)")}>
<button onClick={handleClick}>Save</button>
<button onClick={() => greet("Riya")}>Greet</button>
<button onClick={e => { e.stopPropagation(); console.log("stopped"); }}>Stop</button>
</div>
);
}Output:
After clicking Save, Greet and Stop:
Screen:
[Save][Greet][Stop]
Console:
clicked Save | type: click
div heard it too (bubbling)
Hello Riya
div heard it too (bubbling)
stoppedPass the function itself (onClick={handleClick}), not its result (onClick={handleClick()} calls it during render). Use an arrow function when you need to pass arguments. React attaches one listener per event type at the root and dispatches from there, which is event delegation done for you.
12. What is the difference between controlled and uncontrolled components?
In a controlled input, React state is the single source of truth: the value comes from state and every keystroke updates state through onChange. In an uncontrolled input, the DOM keeps the value and you read it when needed, through a ref or the form data.
import { useState, useRef } from "react";
export default function App() {
const [name, setName] = useState("");
const cityRef = useRef(null);
function submit(e) {
e.preventDefault();
console.log("controlled:", name, "| uncontrolled:", cityRef.current.value);
}
return (
<form onSubmit={submit}>
<input placeholder="Name" value={name} onChange={e => setName(e.target.value.toUpperCase())} />
<input placeholder="City" defaultValue="Surat" ref={cityRef} />
<button>Submit</button>
<p>Live preview: {name || "(empty)"}</p>
</form>
);
}Output:
After typing "riya" in Name and clicking Submit:
Screen:
[RIYA][Surat][Submit]
Live preview: RIYA
Console:
controlled: RIYA | uncontrolled: Surat| Controlled | Uncontrolled | |
|---|---|---|
| Value lives in | React state | The DOM |
| Read value | Any time, from state | On demand, via ref or FormData |
| Instant validation and formatting | Easy (the example upper-cases as you type) | Harder |
| Re-renders on each keystroke | Yes | No |
| Typical use | Most forms | Simple forms, file inputs, integrating non-React code |
13. How do you handle a form with several inputs?
import { useState } from "react";
export default function App() {
const [form, setForm] = useState({ email: "", course: "DSA", agree: false });
function handleChange(e) {
const { name, value, type, checked } = e.target;
setForm(f => ({ ...f, [name]: type === "checkbox" ? checked : value }));
}
return (
<form onSubmit={e => { e.preventDefault(); console.log(form); }}>
<input name="email" placeholder="Email" value={form.email} onChange={handleChange} />
<select name="course" value={form.course} onChange={handleChange}>
<option>DSA</option><option>SQL</option><option>React</option>
</select>
<label><input type="checkbox" name="agree" checked={form.agree} onChange={handleChange} /> I agree</label>
<button disabled={!form.agree}>Enroll</button>
</form>
);
}Output:
After typing an email, ticking "I agree" and clicking Enroll:
Screen:
[ri**@**il.com][DSA ▾][x] I agree[Enroll]
Console:
{ email: 'ri**@**il.com', course: 'DSA', agree: true }One handler serves every field by using the input’s name as a computed key, [name]: value. Checkboxes use checked instead of value. For large forms with validation, libraries such as React Hook Form keep inputs uncontrolled for speed, and React 19 form Actions (question 81) remove much of this boilerplate.
14. What is a Fragment?
A Fragment groups several elements without adding an extra node to the DOM. The short syntax is <>...</>; the long form <Fragment key={id}> is needed when the fragment itself needs a key in a list.
import { Fragment } from "react";
function Row({ name, marks }) {
return (
<>
<td>{name}</td>
<td>{marks}</td>
</>
);
}
const glossary = [{ id: 1, term: "JSX", def: "HTML-like syntax in JS" }, { id: 2, term: "Prop", def: "Input to a component" }];
export default function App() {
return (
<div>
<table border="1"><tbody><tr><Row name="Riya" marks={91} /></tr></tbody></table>
<dl>
{glossary.map(g => (
<Fragment key={g.id}>
<dt><b>{g.term}</b></dt>
<dd>{g.def}</dd>
</Fragment>
))}
</dl>
</div>
);
}Output:
On the first render:
Screen:
Riya 91
JSX
HTML-like syntax in JS
Prop
Input to a componentFragments matter when an extra div would break the HTML structure (table rows, definition lists) or a CSS layout such as flexbox or grid.
15. What is useEffect and when do you use it?
useEffect runs code after React has updated the screen. Use it to synchronise a component with something outside React: fetching data, subscriptions, timers, manual DOM work or third-party widgets. Code that only computes values for rendering does not need an effect.
import { useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("effect: count is now", count);
document.title = `Clicked ${count} times`;
}, [count]);
console.log("render", count);
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}Output:
After one click:
Screen:
[Clicked 1 times]
Console:
render 0
effect: count is now 0
render 1
effect: count is now 1The order is always render first, then the effect. The effect runs after the first render and again whenever a value in the dependency array changes. The next question explains the dependency array.
16. What is the dependency array in useEffect?
| Second argument | When the effect runs |
|---|---|
| Omitted | After every render |
[] | Once, after the first render (on mount) |
[a, b] | After the first render and whenever a or b changes |
import { useState, useEffect } from "react";
export default function App() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
useEffect(() => console.log("no array: every render"));
useEffect(() => console.log("[]: only on mount"), []);
useEffect(() => console.log("[a]: a changed to", a), [a]);
return (
<div>
<button onClick={() => setA(a + 1)}>a = {a}</button>
<button onClick={() => setB(b + 1)}>b = {b}</button>
</div>
);
}Output:
After clicking b, then a:
Screen:
[a = 1][b = 1]
Console:
no array: every render
[]: only on mount
[a]: a changed to 0
no array: every render
no array: every render
[a]: a changed to 1List every value from the component that the effect uses (props, state, functions defined inside the component). The ESLint rule react-hooks/exhaustive-deps checks this for you. Leaving a dependency out causes stale values (question 44); adding an object or function that is recreated every render makes the effect run every time.
17. What is the cleanup function in useEffect?
If the effect returns a function, React calls it before running the effect again and when the component unmounts. Use it to undo whatever the effect set up: clear timers, remove listeners, close connections and cancel requests. Forgetting it causes memory leaks and duplicate subscriptions.
import { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
console.log("timer started");
const id = setInterval(() => setSeconds(s => s + 1), 1000);
return () => {
clearInterval(id);
console.log("timer cleaned up");
};
}, []);
return <p>Seconds: {seconds}</p>;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setShow(s => !s)}>{show ? "Hide" : "Show"} timer</button>
{show && <Timer />}
</div>
);
}Output:
After clicking "Hide timer":
Screen:
[Show timer]
Console:
timer started
timer cleaned up18. What are hooks? What are the rules of hooks?
Hooks are functions whose names start with use that let function components use React features: state (useState, useReducer), side effects (useEffect), context (useContext), refs (useRef), performance (useMemo, useCallback) and more. They arrived in React 16.8.
- Call hooks only at the top level of a component or custom hook: not inside conditions, loops, nested functions or after an early return.
- Call hooks only from React functions: components and custom hooks, not regular JavaScript functions or class components.
React does not identify hooks by name. It remembers them by their call order: the first useState call gets slot 1, the second gets slot 2, and so on. If a condition skips a hook on one render, every later hook reads the wrong slot. Question 71 shows the error you get. The one exception is the React 19 use API, which may be called conditionally.
19. What is useRef used for?
useRef(initial) returns an object { current } that stays the same for the whole life of the component. It has two main uses: holding a reference to a DOM element, and storing a mutable value that should survive re-renders without causing one.
import { useRef, useState } from "react";
export default function App() {
const inputRef = useRef(null);
const clicks = useRef(0); // changes do not re-render
const [, force] = useState(0);
return (
<div>
<input ref={inputRef} placeholder="Search" />
<button onClick={() => { inputRef.current.focus(); inputRef.current.value = "React"; }}>Focus and fill</button>
<button onClick={() => { clicks.current++; console.log("ref is", clicks.current); }}>Count silently</button>
<button onClick={() => force(n => n + 1)}>Re-render</button>
<p>Ref value shown on screen: {clicks.current}</p>
</div>
);
}Output:
After clicking "Count silently" three times (the screen still shows 0 until something re-renders):
Screen:
[Search][Focus and fill][Count silently][Re-render]
Ref value shown on screen: 0
Console:
ref is 1
ref is 2
ref is 3Use state for anything that should appear on screen, and a ref for values the UI does not show: timer IDs, previous values, the latest props for a callback, or a flag for “is this the first render”. Do not read or write ref.current during rendering, except to initialise it.
20. What is “lifting state up”?
When two components need the same data, move the state to their closest common parent and pass it down as props, along with functions to change it. The parent becomes the single source of truth, so the two children can never disagree.
import { useState } from "react";
function TempInput({ label, value, onChange }) {
return <label>{label}: <input value={value} onChange={e => onChange(e.target.value)} /> </label>;
}
export default function App() {
const [celsius, setCelsius] = useState("25");
const fahrenheit = celsius === "" ? "" : String(Math.round((parseFloat(celsius) * 9) / 5 + 32));
return (
<div>
<TempInput label="Celsius" value={celsius} onChange={setCelsius} />
<TempInput label="Fahrenheit" value={fahrenheit}
onChange={f => setCelsius(f === "" ? "" : String(Math.round(((parseFloat(f) - 32) * 5) / 9)))} />
<p>{parseFloat(celsius) >= 100 ? "Water boils" : "Water does not boil"}</p>
</div>
);
}Output:
On the first render:
Screen:
Celsius: [25] Fahrenheit: [77]
Water does not boilOnly Celsius is stored; Fahrenheit is derived during render. Storing both would let them drift apart. Lifting state too high causes extra re-renders and prop drilling, which is where context and state libraries help.
21. What is prop drilling?
Prop drilling means passing a prop through several layers of components that do not use it, only so that a deeply nested child can receive it. It makes components harder to reuse and every intermediate layer has to know about data it does not care about.
function App() {
const user = { name: "Riya", plan: "Pro" };
return <Layout user={user} />;
}
function Layout({ user }) { // does not use user
return <Sidebar user={user} />;
}
function Sidebar({ user }) { // does not use user either
return <Avatar user={user} />;
}
function Avatar({ user }) {
return <p>{user.name} ({user.plan})</p>;
}Output:
On the first render:
Screen:
Riya (Pro)Fixes, in order of preference: restructure with composition (pass <Avatar user={user} /> as children so the middle layers never see it), use Context for truly global data such as theme, language or the logged-in user (next question), or use a state library like Redux or Zustand for complex shared state.
22. What is the Context API?
Context lets a parent make a value available to every component below it, at any depth, without passing props through each level. Create it with createContext(default), provide it with <ThemeContext value={...}> (React 19; older versions use .Provider) and read it with useContext or, in React 19, use(ThemeContext).
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext("light");
function Toolbar() { // passes nothing down
return <div><ThemedButton /></div>;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
const style = theme === "dark" ? { background: "#222", color: "#fff" } : {};
return <button style={style}>Theme: {theme}</button>;
}
export default function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext value={theme}>
<Toolbar />
<button onClick={() => setTheme(t => (t === "light" ? "dark" : "light"))}>Toggle</button>
</ThemeContext>
);
}Output:
After clicking Toggle:
Screen:
[Theme: dark]
[Toggle]Every component that reads a context re-renders when its value changes, so keep frequently changing values out of large shared contexts or split them (question 65). Context is a way to pass data, not a full state manager; combine it with useState or useReducer for that.
23. What is the children prop?
Whatever you put between a component’s opening and closing tags arrives as props.children. This is how you build wrapper components such as cards, modals and layouts that do not need to know what they contain. It is called composition, and React recommends it over inheritance.
function Card({ title, children, footer }) {
return (
<div style={{ border: "1px solid #ccc", borderRadius: 8, padding: 10, marginBottom: 8 }}>
<h4 style={{ margin: 0 }}>{title}</h4>
<div>{children}</div>
{footer && <small>{footer}</small>}
</div>
);
}
export default function App() {
return (
<>
<Card title="Course" footer="Updated today">
<p>Learn DSA in Java and C++.</p>
<button>Enroll</button>
</Card>
<Card title="Empty card" />
</>
);
}Output:
On the first render:
Screen:
Course
Learn DSA in Java and C++.
[Enroll]
Updated today
Empty cardYou can also pass elements through other props (footer above, or icon, header), which works like named slots. Children can be a single element, text, an array or a function (the render props pattern, question 58).
24. How do you set default values for props?
function Button({ label = "Click me", variant = "primary", size = 16, onClick = () => {} }) {
const bg = variant === "primary" ? "#3c3fde" : "#eee";
const color = variant === "primary" ? "#fff" : "#222";
return <button style={{ background: bg, color, fontSize: size }} onClick={onClick}>{label}</button>;
}
export default function App() {
return (
<div>
<Button />
<Button label="Cancel" variant="secondary" size={14} />
<Button label={undefined} />
<Button label={null} />
</div>
);
}Output:
On the first render:
Screen:
[Click me][Cancel][Click me][]Use default values in the destructured parameters. A default applies only when the prop is undefined, so passing null gives an empty button. The old Component.defaultProps is no longer supported for function components in React 19.
25. What are the ways to style React components?
| Approach | Example | Notes |
|---|---|---|
| CSS file with className | className="card active" | Simple; class names are global |
| Inline styles | style={{ color: "red", fontSize: 14 }} | A JS object with camelCase keys; numbers mean px; no hover or media queries |
| CSS Modules | import s from "./Card.module.css" | Class names are scoped to the file automatically |
| Utility CSS (Tailwind) | className="p-4 rounded-lg bg-white" | Very popular with React and Next.js |
| CSS-in-JS | styled-components, Emotion | Styles live in JS; adds run-time cost |
import { useState } from "react";
export default function App() {
const [active, setActive] = useState(false);
const box = {
padding: 12,
borderRadius: 8,
border: "2px solid",
borderColor: active ? "seagreen" : "#ccc",
background: active ? "#eafaf1" : "white"
};
return (
<div>
<div style={box} className={["card", active && "card-active"].filter(Boolean).join(" ")}>
{active ? "Active card" : "Inactive card"}
</div>
<button onClick={() => setActive(a => !a)}>Toggle</button>
</div>
);
}Output:
On the first render:
Screen:
Inactive card
[Toggle]26. What is the component lifecycle with hooks?
Every component goes through three phases: mounting (added to the screen), updating (re-rendered because props, state or context changed) and unmounting (removed). With hooks, useEffect covers all three.
import { useState, useEffect } from "react";
function Child({ value }) {
useEffect(() => {
console.log("mounted");
return () => console.log("unmounted");
}, []);
useEffect(() => {
console.log("value updated to", value);
}, [value]);
return <p>Child value: {value}</p>;
}
export default function App() {
const [v, setV] = useState(1);
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setV(v + 1)}>Update</button>
<button onClick={() => setShow(false)}>Unmount</button>
{show && <Child value={v} />}
</div>
);
}Output:
After clicking Update, then Unmount:
Screen:
[Update][Unmount]
Console:
mounted
value updated to 1
value updated to 2
unmountedClass components spread the same logic over componentDidMount, componentDidUpdate and componentWillUnmount (question 69). With hooks, think “synchronise with this data” rather than “run at this lifecycle moment”.
27. Why must a React component be pure?
React expects rendering to be a pure calculation: given the same props, state and context, a component returns the same JSX and does not change anything outside itself while rendering. React may render a component more than once, pause a render or throw one away (in Strict Mode and in concurrent features), and that is only safe if rendering has no side effects.
let guests = 0; // outside variable
function ImpureCup() {
guests = guests + 1; // side effect during render
return <li>Tea cup for guest #{guests}</li>;
}
function PureCup({ guest }) {
return <li>Tea cup for guest #{guest}</li>;
}
export default function App() {
return (
<div>
<ul><ImpureCup /><ImpureCup /></ul>
<ul><PureCup guest={1} /><PureCup guest={2} /></ul>
</div>
);
}Output:
On the first render:
Screen:
Tea cup for guest #1
Tea cup for guest #2
Tea cup for guest #1
Tea cup for guest #2The impure version only looks right by luck; render it twice (as Strict Mode does in development) and the numbers jump. Side effects belong in event handlers or effects, never in the render body.
28. What is StrictMode?
<StrictMode> is a development-only wrapper that helps you find bugs. It has no effect in production builds. In development it:
- renders components twice to expose impure rendering;
- runs effects twice (mount, unmount, mount) to expose missing cleanup;
- runs ref callbacks twice to check their cleanup;
- warns about deprecated APIs.
import { StrictMode, useEffect } from "react";
function Widget() {
console.log("render");
useEffect(() => {
console.log("connect");
return () => console.log("disconnect");
}, []);
return <p>Open the console: StrictMode ran things twice.</p>;
}
export default function App() {
return (
<StrictMode>
<Widget />
</StrictMode>
);
}Output:
On the first render:
Screen:
Open the console: StrictMode ran things twice.
Console:
render
render
connect
disconnect
connectIf “connect, disconnect, connect” breaks your app (for example two chat connections), your cleanup is missing. This double run is why people ask “why does my useEffect run twice?” (question 62). Vite and Next.js templates enable StrictMode by default.
29. How does a child component send data to its parent?
Data flows down through props, so a child cannot change the parent’s state directly. Instead, the parent passes a callback function as a prop, and the child calls it with the data.
import { useState } from "react";
function SearchBox({ onSearch }) {
const [text, setText] = useState("");
return (
<form onSubmit={e => { e.preventDefault(); onSearch(text.trim()); }}>
<input placeholder="Search courses" value={text} onChange={e => setText(e.target.value)} />
<button>Search</button>
</form>
);
}
export default function App() {
const [query, setQuery] = useState("");
const courses = ["DSA in Java", "SQL Basics", "React Projects", "Java Backend"];
const shown = courses.filter(c => c.toLowerCase().includes(query.toLowerCase()));
return (
<div>
<SearchBox onSearch={setQuery} />
<p>Results for "{query}": {shown.join(", ") || "none"}</p>
</div>
);
}Output:
After searching for "java":
Screen:
[java][Search]
Results for "java": DSA in Java, Java BackendName callback props after the event, starting with on (onSearch, onChange, onClose). For siblings, lift the state to the common parent (question 20).
30. Is React a library or a framework? How is it different from Angular and Vue?
| React | Angular | Vue | |
|---|---|---|---|
| Type | UI library | Full framework | Progressive framework |
| Language | JavaScript or TypeScript with JSX | TypeScript with templates | JavaScript or TypeScript with templates (JSX optional) |
| Data binding | One-way | Two-way available | Two-way with v-model |
| Routing, forms, HTTP | Separate libraries | Built in | Official add-ons |
| Backed by | Meta | Independent team |
React is called a library because it only renders UI and leaves the rest of the architecture to you. In practice, most new React projects start from a framework built on it, such as Next.js or React Router (formerly Remix), which add routing, data loading and server rendering.
31. How do you create a new React project today?
Create React App was officially deprecated in February 2025. The React team now recommends starting with a framework, or with Vite when you want a plain single-page app.
# Plain single-page app with Vite (fast dev server, small builds)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
# Full-stack framework with routing and server rendering
npx create-next-app@latest my-next-app// src/main.jsx: how a Vite app starts
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
</StrictMode>
);createRoot (React 18+) replaced the old ReactDOM.render, which was removed in React 19. It turns on concurrent features such as automatic batching and transitions.
32. What is a single-page application? How does routing work in React?
A single-page application (SPA) loads one HTML page and then updates the content with JavaScript as the user navigates, instead of asking the server for a new page each time. Client-side routing maps the URL to components using the History API, so the back button and bookmarks still work.
import { BrowserRouter, Routes, Route, Link, useParams } from "react-router";
function Course() {
const { slug } = useParams();
return <h2>Course: {slug}</h2>;
}
export default function App() {
return (
<BrowserRouter>
<nav><Link to="/">Home</Link> | <Link to="/courses/dsa">DSA</Link></nav>
<Routes>
<Route path="/" element={<h2>Home</h2>} />
<Route path="/courses/:slug" element={<Course />} />
<Route path="*" element={<h2>Not found</h2>} />
</Routes>
</BrowserRouter>
);
}React Router is the most used routing library; Next.js uses file-based routing instead. Link changes the URL without a full page reload. A plain SPA sends an almost empty HTML page, which hurts first load time and SEO; server rendering (question 86) solves that.
33. What are React Developer Tools?
React Developer Tools is a browser extension for Chrome, Firefox and Edge that adds two tabs to DevTools:
- Components: the component tree with each component’s props, state, hooks and context. You can edit values live and jump to the source.
- Profiler: records renders and shows which components rendered, why, and how long each took. Turn on “Highlight updates when components render” to see re-renders on the page, like the visualiser on this page.
In interviews, mention that you use the Profiler before optimising: measure, find the slow component, fix, and measure again.
34. What is dangerouslySetInnerHTML?
React escapes everything you put in JSX, so a string containing HTML is shown as text. dangerouslySetInnerHTML={{ __html: html }} tells React to insert raw HTML instead. The long name is a warning: if the HTML contains user input, it can run an attacker’s script (XSS).
const comment = "<b>Great course!</b> <img src=\"data:,\" onerror=\"console.log('XSS ran')\">";
export default function App() {
return (
<div>
<p>Escaped by default: {comment}</p>
<p dangerouslySetInnerHTML={{ __html: "Trusted HTML: <i>from our own CMS</i>" }} />
<p dangerouslySetInnerHTML={{ __html: "Untrusted: " + comment }} />
</div>
);
}Output:
On the first render:
Screen:
Escaped by default: <b>Great course!</b> <img src="data:," onerror="console.log('XSS ran')">
Trusted HTML: from our own CMS
Untrusted: Great course!
Console:
XSS ranOnly use it with HTML you trust, such as content from your own CMS, or after sanitising it with a library like DOMPurify. Question 95 covers other ways XSS can sneak into React apps.
35. What happens when you set state to the same value?
React compares the new value with the current one using Object.is. If they are the same, React bails out: it skips re-rendering the children and does not run effects. (It may still call the component function once to be sure, but throws the result away.)
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const [user, setUser] = useState({ name: "Riya" });
console.log("render");
return (
<div>
<button onClick={() => setCount(0)}>Set count to 0</button>
<button onClick={() => setUser({ name: "Riya" })}>Set an equal new object</button>
<p>{count} {user.name}</p>
</div>
);
}Output:
After clicking "Set count to 0" twice, then "Set an equal new object":
Screen:
[Set count to 0][Set an equal new object]
0 Riya
Console:
render
renderSetting 0 again causes no re-render. A new object with the same contents is a different reference, so React re-renders. So do not create new objects in state when nothing actually changed.
36. How do you fetch data in a React component?
The classic pattern fetches inside useEffect and keeps three pieces of state: the data, a loading flag and an error. The example uses a fake API that returns after 300 ms, so it runs anywhere.
import { useState, useEffect } from "react";
const fakeApi = () => new Promise(resolve =>
setTimeout(() => resolve([{ id: 1, title: "DSA" }, { id: 2, title: "SQL" }, { id: 3, title: "React" }]), 300));
export default function App() {
const [courses, setCourses] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false; // avoids setting state after unmount or a newer request
fakeApi()
.then(data => { if (!ignore) setCourses(data); })
.catch(err => { if (!ignore) setError(err.message); })
.finally(() => { if (!ignore) setLoading(false); });
return () => { ignore = true; };
}, []);
if (loading) return <p>Loading courses...</p>;
if (error) return <p>Error: {error}</p>;
return <ul>{courses.map(c => <li key={c.id}>{c.title}</li>)}</ul>;
}Output:
After the fake request finishes (about 300 ms):
Screen:
DSA
SQL
ReactIn real apps, libraries such as TanStack Query (React Query) or SWR handle caching, retries, refetching and race conditions for you, and frameworks like Next.js fetch on the server. React 19 also adds use(promise) with Suspense (question 80).
37. Why can’t a normal variable replace state?
import { useState } from "react";
export default function App() {
let plain = 0;
const [stateful, setStateful] = useState(0);
return (
<div>
<button onClick={() => { plain++; console.log("plain is", plain); }}>plain++</button>
<button onClick={() => setStateful(s => s + 1)}>state++</button>
<p>plain: {plain} | state: {stateful}</p>
</div>
);
}Output:
After clicking "plain++" twice and then "state++":
Screen:
[plain++][state++]
plain: 0 | state: 1
Console:
plain is 1
plain is 2Two problems. Changing a normal variable does not tell React to re-render, so the screen does not update. And every render runs the function again from the top, so plain is reset to 0: when state++ caused a re-render, the two earlier increments were lost. State is kept by React between renders and triggers a re-render when it changes.
38. How do you show a list of components from data with filtering and sorting?
import { useState } from "react";
const products = [
{ id: 1, name: "Keyboard", price: 1299, inStock: true },
{ id: 2, name: "Mouse", price: 499, inStock: false },
{ id: 3, name: "Monitor", price: 8999, inStock: true },
{ id: 4, name: "Webcam", price: 2199, inStock: true }
];
export default function App() {
const [onlyInStock, setOnlyInStock] = useState(false);
const [sortBy, setSortBy] = useState("name");
const visible = products
.filter(p => !onlyInStock || p.inStock)
.toSorted((a, b) => sortBy === "price" ? a.price - b.price : a.name.localeCompare(b.name));
return (
<div>
<label><input type="checkbox" checked={onlyInStock} onChange={e => setOnlyInStock(e.target.checked)} /> In stock only</label>
<select value={sortBy} onChange={e => setSortBy(e.target.value)}>
<option value="name">Sort by name</option>
<option value="price">Sort by price</option>
</select>
<ul>{visible.map(p => <li key={p.id}>{p.name}: Rs {p.price}</li>)}</ul>
</div>
);
}Output:
After ticking "In stock only" and sorting by price:
Screen:
[x] In stock only[Sort by price ▾]
Keyboard: Rs 1299
Webcam: Rs 2199
Monitor: Rs 8999Do not store the filtered list in state. Compute it during render from the source data and the filter state, so it can never get out of sync. If the computation becomes slow, wrap it in useMemo (question 46). toSorted returns a new array, so the original data is never mutated.
39. What is the difference between a React element and a component?
A component is the function (or class) you write. A React element is the plain, immutable object that describes one piece of UI, which is what JSX produces. A component is called with props and returns elements; React then turns elements into DOM nodes.
function Welcome({ name }) { // a component
return <h4>Welcome, {name}</h4>;
}
export default function App() {
const el = <Welcome name="Riya" />; // an element: a description, not yet rendered
console.log(typeof Welcome, typeof el);
console.log(el.type === Welcome, el.props);
return <div>{el}{el}</div>; // the same element can be rendered twice
}Output:
On the first render:
Screen:
Welcome, Riya
Welcome, Riya
Console:
function object
true { name: 'Riya' }Creating an element does not call the component; React calls it later, when it renders that element. So write <Welcome /> instead of calling Welcome() directly: a direct call skips React, so hooks inside it would break the rules of hooks.
40. How do you update objects and arrays in state?
Always build a new object or array and pass it to the setter. Copy the levels you change with spread; untouched nested objects can be reused.
import { useState } from "react";
export default function App() {
const [user, setUser] = useState({ name: "Riya", address: { city: "Surat", pin: "395007" } });
const [todos, setTodos] = useState([{ id: 1, text: "JSX", done: false }, { id: 2, text: "Hooks", done: false }]);
const moveCity = () => setUser(u => ({ ...u, address: { ...u.address, city: "Pune" } }));
const add = () => setTodos(t => [...t, { id: Date.now(), text: "Context", done: false }]);
const toggle = id => setTodos(t => t.map(x => (x.id === id ? { ...x, done: !x.done } : x)));
const remove = id => setTodos(t => t.filter(x => x.id !== id));
return (
<div>
<p>{user.name} lives in {user.address.city}</p>
<button onClick={moveCity}>Move to Pune</button>
<button onClick={add}>Add todo</button>
<ul>
{todos.map(t => (
<li key={t.id}>
<label><input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} /> {t.text}</label>
<button onClick={() => remove(t.id)}>x</button>
</li>
))}
</ul>
</div>
);
}Output:
After clicking "Move to Pune" and ticking "JSX":
Screen:
Riya lives in Pune
[Move to Pune][Add todo]
[x] JSX[x]
[ ] Hooks[x]| Task | Pattern |
|---|---|
| Add | [...arr, item] |
| Remove | arr.filter(x => x.id !== id) |
| Update one item | arr.map(x => x.id === id ? { ...x, done: true } : x) |
| Change a nested field | { ...obj, address: { ...obj.address, city } } |
| Sort without mutating | arr.toSorted(...) |
Deeply nested updates get tedious; flatten your state where you can, or use Immer (useImmer), which lets you write “mutating” code that produces a new copy.
Intermediate React interview questions
These 35 questions are for developers with one to three years of experience: reconciliation and keys, batching and stale closures, useMemo, useCallback and memo, useReducer, custom hooks, refs, portals, error boundaries, code splitting and common component patterns.
41. How does reconciliation (the diffing algorithm) work?
Comparing two arbitrary trees exactly would take O(n³) time, so React uses two assumptions that make diffing O(n):
- Elements of different types produce different trees. If a
<div>becomes a<section>, or<Profile>becomes<Settings>, React destroys the old subtree, including all its state, and builds a new one. - Keys identify children across renders. In a list, React matches old and new children by key, so it can move, insert and delete items instead of rewriting every one.
import { useState } from "react";
function Counter({ label }) {
const [n, setN] = useState(0);
return <p>{label}: {n} <button onClick={() => setN(n + 1)}>+1</button></p>;
}
export default function App() {
const [fancy, setFancy] = useState(false);
return (
<div>
{fancy ? <section><Counter label="A" /></section> : <div><Counter label="A" /></div>}
<Counter label="B" key={fancy ? "b1" : "b2"} />
<button onClick={() => setFancy(f => !f)}>Switch wrapper</button>
</div>
);
}Output:
After clicking A's "+1" twice and then "Switch wrapper":
Screen:
A: 0 [+1]
B: 0 [+1]
[Switch wrapper]Changing the wrapper from div to section, or changing a key, throws the counter’s state away. If the type and key stay the same, React keeps the component instance and only updates the props that changed. Question 60 uses this on purpose to reset a form.
42. Why is using the array index as a key a problem?
With index keys, the key belongs to a position, not to an item. When you add an item at the start, remove one, or reorder the list, every item after the change gets a different index. React then reuses the wrong component instance for each position, so any state inside the items (input text, checkboxes, animations) stays at the old position while the data moves.
import { useState } from "react";
function Row({ name }) {
return <li>{name} <input placeholder={"note for " + name} /></li>;
}
export default function App() {
const [people, setPeople] = useState([{ id: 1, name: "Riya" }, { id: 2, name: "Aman" }]);
const addFirst = () => setPeople(p => [{ id: Date.now(), name: "Neha" }, ...p]);
return (
<div>
<button onClick={addFirst}>Add Neha at the top</button>
<p>index keys:</p>
<ul>{people.map((p, i) => <Row key={i} name={p.name} />)}</ul>
<p>id keys:</p>
<ul>{people.map(p => <Row key={p.id} name={p.name} />)}</ul>
</div>
);
}Output:
After typing in the first "note for Riya" box (index keys list) and adding Neha:
Screen:
[Add Neha at the top]
index keys:
Neha [Riya's note]
Riya [note for Riya]
Aman [note for Aman]
id keys:
Neha [note for Neha]
Riya [note for Riya]
Aman [note for Aman]In the index-key list, Riya’s note is now next to Neha, because the input at position 0 kept its DOM state. With id keys, everything stays attached to the right person. Index keys are fine only for static lists that never change order and have no item state.
43. Why does calling setCount(count + 1) three times only add 1?
State updates are batched and the count variable is a snapshot of this render. All three calls compute 0 + 1 from the same snapshot, so React ends up with 1. To build on the latest value, pass an updater function: React queues them and runs each with the result of the previous one.
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
console.log("render", count);
function addThreeWrong() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log("inside the handler count is still", count);
}
function addThreeRight() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<div>
<p>{count}</p>
<button onClick={addThreeWrong}>+3 (snapshot)</button>
<button onClick={addThreeRight}>+3 (updater)</button>
</div>
);
}Output:
After clicking "+3 (snapshot)" once and "+3 (updater)" once:
Screen:
4
[+3 (snapshot)][+3 (updater)]
Console:
render 0
inside the handler count is still 0
render 1
render 4Notice there was only one re-render per click: React 18+ batches every update in the same event, including updates in timeouts and promises (question 79). The value you read after calling the setter is still the old one; the new value only exists in the next render.
44. What is a stale closure in React?
Every render creates new functions that “close over” that render’s props and state. If something keeps an old function around, such as an interval created in an effect with an empty dependency array, it keeps seeing the old values forever. That is a stale closure.
import { useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(0);
const [fixed, setFixed] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // count is always 0 here
setFixed(f => f + 1); // updater reads the latest value
}, 100);
return () => clearInterval(id);
}, []); // runs once, so it keeps the first closure
return <p>stale: {count} | fixed: {fixed}</p>;
}Output:
After about 0.6 seconds:
Screen:
stale: 1 | fixed: 8Fixes: use the updater form, add the value to the dependency array (which restarts the interval each time), or keep the latest value in a ref. The React 19.2 useEffectEvent hook was added for exactly this case: a function called from an effect that always sees the latest props and state.
45. What is the difference between useEffect and useLayoutEffect?
| useEffect | useLayoutEffect | |
|---|---|---|
| Runs | After the browser paints | After DOM changes, before the browser paints |
| Blocks painting | No | Yes |
| Use for | Almost everything: data fetching, subscriptions, logging | Measuring layout (sizes, positions) and adjusting before the user sees it, to avoid flicker |
import { useState, useEffect, useLayoutEffect, useRef } from "react";
export default function App() {
const box = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => console.log("useEffect (after paint)"), []);
useLayoutEffect(() => {
console.log("useLayoutEffect (before paint), width =", box.current.offsetWidth);
setWidth(box.current.offsetWidth);
}, []);
console.log("render");
return <div ref={box} style={{ width: 240, border: "1px solid #999", padding: 6 }}>Measured width: {width}px</div>;
}Output:
On the first render:
Screen:
Measured width: 254px
Console:
render
useLayoutEffect (before paint), width = 254
useEffect (after paint)
renderLayout effects always run before normal effects. Because useLayoutEffect blocks painting, heavy work in it makes the page feel slow. It also does nothing during server rendering, so use it only when you really must measure before paint.
46. What is useMemo and when should you use it?
useMemo(compute, deps) caches the result of a calculation between renders and recalculates only when a dependency changes. Use it for expensive calculations, or to keep an object or array reference stable when it is passed to a memoised child or used as an effect dependency.
import { useState, useMemo } from "react";
function slowFilter(items, query) {
console.log("filtering", items.length, "items for", JSON.stringify(query));
return items.filter(i => i.includes(query));
}
const ITEMS = Array.from({ length: 5000 }, (_, i) => "course-" + i);
export default function App() {
const [query, setQuery] = useState("99");
const [dark, setDark] = useState(false);
const results = useMemo(() => slowFilter(ITEMS, query), [query]);
return (
<div style={{ background: dark ? "#222" : "#fff", color: dark ? "#fff" : "#000", padding: 8 }}>
<input placeholder="Filter" value={query} onChange={e => setQuery(e.target.value)} />
<button onClick={() => setDark(d => !d)}>Toggle theme</button>
<p>{results.length} matches</p>
</div>
);
}Output:
After toggling the theme twice and then typing "999":
Screen:
[999][Toggle theme]
5 matches
Console:
filtering 5000 items for "99"
filtering 5000 items for "999"Toggling the theme re-renders without re-filtering; only a new query recalculates. Do not wrap every value in useMemo: the cache has its own cost, and most calculations are fast. Measure first. The React Compiler (question 85) adds this memoization automatically.
47. What is useCallback?
useCallback(fn, deps) returns the same function reference between renders until a dependency changes. It is useMemo(() => fn, deps) for functions. It only helps when the function’s identity matters: a child wrapped in React.memo, or a function used in a dependency array.
import { useState, useCallback, memo } from "react";
const Button = memo(function Button({ onClick, children }) {
console.log("render", children);
return <button onClick={onClick}>{children}</button>;
});
export default function App() {
const [count, setCount] = useState(0);
const [other, setOther] = useState(0);
const stable = useCallback(() => setCount(c => c + 1), []);
const unstable = () => setCount(c => c + 1);
return (
<div>
<p>count {count}, other {other}</p>
<Button onClick={stable}>stable</Button>
<Button onClick={unstable}>unstable</Button>
<button onClick={() => setOther(o => o + 1)}>Change other state</button>
</div>
);
}Output:
After clicking "Change other state" twice:
Screen:
count 0, other 2
[stable][unstable][Change other state]
Console:
render stable
render unstable
render unstable
render unstableThe memoised button with the stable callback renders once; the one receiving a new arrow function every render re-renders every time. useCallback without memo on the child does nothing useful.
48. What is React.memo?
memo(Component) makes a component skip re-rendering when its props are shallowly equal to the previous props. It is useful for components that render often with the same props and are expensive to render. You can step through this in the re-render visualiser above.
import { useState, memo } from "react";
function Price({ amount }) {
console.log("Price rendered");
return <p>Price: Rs {amount}</p>;
}
const MemoPrice = memo(Price);
export default function App() {
const [qty, setQty] = useState(1);
const [note, setNote] = useState("");
return (
<div>
<input placeholder="Note" value={note} onChange={e => setNote(e.target.value)} />
<button onClick={() => setQty(q => q + 1)}>qty {qty}</button>
<MemoPrice amount={499 * qty} />
</div>
);
}Output:
After typing a note and then changing the quantity:
Screen:
[gift][qty 2]
Price: Rs 998
Console:
Price rendered
Price renderedTyping the note re-renders App but not MemoPrice, because its amount prop did not change. Memo is broken by props that are new objects, arrays or functions on every render, which is where useMemo and useCallback come in. It also does not stop re-renders caused by the component’s own state or context.
49. What is useReducer and when should you use it over useState?
useReducer(reducer, initialState) moves state update logic into a pure function, (state, action) => newState. Components call dispatch({ type: "..." }) to describe what happened, and the reducer decides how the state changes. It suits state with many related fields or many kinds of updates.
import { useReducer } from "react";
function cartReducer(state, action) {
switch (action.type) {
case "add": {
const found = state.items.find(i => i.id === action.item.id);
const items = found
? state.items.map(i => (i.id === action.item.id ? { ...i, qty: i.qty + 1 } : i))
: [...state.items, { ...action.item, qty: 1 }];
return { ...state, items };
}
case "clear":
return { ...state, items: [] };
default:
throw new Error("Unknown action " + action.type);
}
}
export default function App() {
const [cart, dispatch] = useReducer(cartReducer, { items: [] });
const total = cart.items.reduce((s, i) => s + i.price * i.qty, 0);
return (
<div>
<button onClick={() => dispatch({ type: "add", item: { id: 1, name: "DSA", price: 999 } })}>Add DSA</button>
<button onClick={() => dispatch({ type: "add", item: { id: 2, name: "SQL", price: 499 } })}>Add SQL</button>
<button onClick={() => dispatch({ type: "clear" })}>Clear</button>
<ul>{cart.items.map(i => <li key={i.id}>{i.name} x {i.qty}</li>)}</ul>
<p>Total: Rs {total}</p>
</div>
);
}Output:
After adding DSA, SQL and DSA again:
Screen:
[Add DSA][Add SQL][Clear]
DSA x 2
SQL x 1
Total: Rs 2497Reducers are easy to test on their own and make the update logic readable in one place. This is the same idea as Redux, at component scope. Use useState for a few independent values.
50. How do you build simple global state with useContext and useReducer?
import { createContext, useContext, useReducer } from "react";
const AuthContext = createContext(null);
function authReducer(state, action) {
if (action.type === "login") return { user: action.name };
if (action.type === "logout") return { user: null };
return state;
}
function AuthProvider({ children }) {
const [state, dispatch] = useReducer(authReducer, { user: null });
return <AuthContext value={{ state, dispatch }}>{children}</AuthContext>;
}
function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used inside AuthProvider");
return ctx;
}
function Navbar() {
const { state, dispatch } = useAuth();
return state.user
? <p>Hi {state.user} <button onClick={() => dispatch({ type: "logout" })}>Logout</button></p>
: <button onClick={() => dispatch({ type: "login", name: "Riya" })}>Login</button>;
}
function Page() {
const { state } = useAuth();
return <p>{state.user ? "Your dashboard" : "Please log in"}</p>;
}
export default function App() {
return <AuthProvider><Navbar /><Page /></AuthProvider>;
}Output:
After clicking Login:
Screen:
Hi Riya [Logout]
Your dashboardThe custom useAuth hook hides the context and throws a helpful error if it is used outside the provider. This pattern works well for small apps. For large or frequently changing state, libraries like Zustand or Redux Toolkit add selectors so components re-render only for the slice they use.
51. What are custom hooks? Write one.
A custom hook is a function whose name starts with use and that calls other hooks. It lets you reuse stateful logic between components. Each component that calls it gets its own independent state; hooks share logic, not state.
import { useState, useEffect } from "react";
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn(o => !o);
return [on, toggle];
}
function useCountdown(seconds) {
const [left, setLeft] = useState(seconds);
useEffect(() => {
if (left <= 0) return;
const id = setTimeout(() => setLeft(l => l - 1), 100); // 100 ms per tick for the demo
return () => clearTimeout(id);
}, [left]);
return left;
}
export default function App() {
const [open, toggleOpen] = useToggle();
const [dark, toggleDark] = useToggle(true);
const left = useCountdown(3);
return (
<div>
<button onClick={toggleOpen}>Menu: {open ? "open" : "closed"}</button>
<button onClick={toggleDark}>Theme: {dark ? "dark" : "light"}</button>
<p>{left > 0 ? `Offer ends in ${left}...` : "Offer ended"}</p>
</div>
);
}Output:
After clicking the menu button and waiting half a second:
Screen:
[Menu: open][Theme: dark]
Offer endedGood candidates: data fetching (useFetch), form handling, debounced values (one of the practice questions below), media queries, keyboard shortcuts, and the browser APIs you use in several places.
52. How do you pass a ref to a child component? (forwardRef and React 19)
In React 19, ref is a normal prop for function components: the child accepts ref in its props and attaches it to a DOM element. Before React 19 you had to wrap the child in forwardRef, which still works but is no longer needed.
import { useRef, forwardRef } from "react";
function TextInput({ label, ref }) { // React 19: ref is a prop
return <label>{label} <input ref={ref} /></label>;
}
const OldInput = forwardRef(function OldInput({ label }, ref) { // before React 19
return <label>{label} <input ref={ref} /></label>;
});
export default function App() {
const a = useRef(null), b = useRef(null);
return (
<div>
<TextInput label="New:" ref={a} />
<OldInput label="Old:" ref={b} />
<button onClick={() => { a.current.value = "focused"; a.current.focus(); console.log(document.activeElement === a.current); }}>Focus new</button>
<button onClick={() => { b.current.value = "focused"; b.current.focus(); console.log(document.activeElement === b.current); }}>Focus old</button>
</div>
);
}Output:
After clicking both buttons:
Screen:
New: [focused]Old: [focused][Focus new][Focus old]
Console:
true
true53. What is useImperativeHandle?
useImperativeHandle(ref, () => api) lets a child decide what the parent gets through its ref. Instead of exposing the whole DOM node, you expose a small set of methods, such as focus, clear or scrollToBottom. Use it rarely; props are the normal way to control children.
import { useRef, useImperativeHandle, useState } from "react";
function OtpInput({ ref }) {
const [code, setCode] = useState("");
const input = useRef(null);
useImperativeHandle(ref, () => ({
clear() { setCode(""); input.current.focus(); },
get value() { return code; }
}), [code]);
return <input ref={input} placeholder="OTP" value={code} maxLength={6} onChange={e => setCode(e.target.value.replace(/\D/g, ""))} />;
}
export default function App() {
const otp = useRef(null);
return (
<div>
<OtpInput ref={otp} />
<button onClick={() => console.log("OTP is", otp.current.value)}>Read</button>
<button onClick={() => otp.current.clear()}>Clear</button>
</div>
);
}Output:
After typing "12ab34", clicking Read and then Clear:
Screen:
[OTP][Read][Clear]
Console:
OTP is 123454. What are portals?
createPortal(children, domNode) renders children into a different DOM node, usually document.body, while keeping them in the same place in the React tree. Use it for modals, tooltips, dropdowns and toasts that must escape a parent with overflow: hidden or a low z-index.
import { useState } from "react";
import { createPortal } from "react-dom";
function Modal({ onClose, children }) {
return createPortal(
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.4)", display: "grid", placeItems: "center" }}>
<div style={{ background: "#fff", padding: 16, borderRadius: 8 }}>
{children} <button onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
}
export default function App() {
const [open, setOpen] = useState(false);
return (
<div style={{ overflow: "hidden", height: 40 }} onClick={() => console.log("click bubbled to App")}>
<button onClick={() => setOpen(true)}>Open modal</button>
{open && <Modal onClose={() => setOpen(false)}>Modal lives in document.body</Modal>}
</div>
);
}Output:
After clicking "Open modal":
Screen:
[Open modal]
Modal lives in document.body [Close]
Console:
click bubbled to AppEvents from inside a portal bubble through the React tree, not the DOM tree, so App’s onClick still hears clicks in the modal (watch the console when you click Close). Context also flows into portals normally. For accessible modals, also handle focus, Escape and aria-modal, or use the native <dialog> element.
55. What is an error boundary?
An error boundary is a component that catches errors thrown while rendering its children, shows a fallback UI, and keeps the rest of the app running. Without one, a render error unmounts the whole app. Error boundaries must still be class components with static getDerivedStateFromError (and optionally componentDidCatch for logging); the react-error-boundary package wraps this for you.
import { Component, useState } from "react";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) { return { error }; }
componentDidCatch(error) { console.log("logged to monitoring:", error.message); }
render() {
if (this.state.error) return <p style={{ color: "crimson" }}>Something went wrong: {this.state.error.message} <button onClick={() => this.setState({ error: null })}>Retry</button></p>;
return this.props.children;
}
}
function Profile({ user }) {
return <p>Name: {user.name.toUpperCase()}</p>;
}
export default function App() {
const [user, setUser] = useState({ name: "riya" });
return (
<div>
<ErrorBoundary><Profile user={user} /></ErrorBoundary>
<button onClick={() => setUser({})}>Break profile</button>
<p>The rest of the page still works.</p>
</div>
);
}Output:
After clicking "Break profile":
Screen:
Something went wrong: Cannot read properties of undefined (reading 'toUpperCase') [Retry]
[Break profile]
The rest of the page still works.
Console:
Caught by an error boundary: TypeError: Cannot read properties of undefined (reading 'toUpperCase')
logged to monitoring: Cannot read properties of undefined (reading 'toUpperCase')Error boundaries do not catch errors in event handlers, async code (setTimeout, promises) or the boundary itself; use try/catch there. Place boundaries around independent sections (a widget, a route) rather than one at the top.
56. What are React.lazy and Suspense?
lazy(() => import("./Chart")) loads a component’s code only when it is first rendered, splitting it into its own bundle chunk. <Suspense fallback={...}> shows the fallback while the code (or data, with use) is loading.
import { lazy, Suspense, useState } from "react";
// Simulates import("./Chart"), which normally loads a separate file
const Chart = lazy(() => new Promise(resolve =>
setTimeout(() => resolve({ default: () => <p>Chart loaded: ▁▃▅▇</p> }), 400)));
export default function App() {
const [show, setShow] = useState(false);
return (
<div>
<button onClick={() => setShow(true)}>Show chart</button>
{show && (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
)}
</div>
);
}Output:
After clicking "Show chart" ("Loading chart..." shows for about 0.4 s first):
Screen:
[Show chart]
Chart loaded: ▁▃▅▇Split by route and by heavy widgets that are not needed at first (charts, editors, maps). The lazy component must be a default export, and lazy must be called outside components, otherwise state is lost on every render.
57. What is a higher-order component (HOC)?
A higher-order component is a function that takes a component and returns a new component with extra behaviour, such as withAuth(Page) or React Redux’s old connect(). It is the decorator pattern applied to components.
function withLoading(Wrapped) {
return function WithLoading({ loading, ...props }) {
if (loading) return <p>Loading...</p>;
return <Wrapped {...props} />;
};
}
function CourseList({ courses }) {
return <ul>{courses.map(c => <li key={c}>{c}</li>)}</ul>;
}
const CourseListWithLoading = withLoading(CourseList);
export default function App() {
return (
<div>
<CourseListWithLoading loading={true} courses={[]} />
<CourseListWithLoading loading={false} courses={["DSA", "React"]} />
</div>
);
}Output:
On the first render:
Screen:
Loading...
DSA
ReactHOCs are less common today because custom hooks share logic without extra wrapper components, prop name clashes or “wrapper hell” in DevTools. You still meet them in older codebases and some libraries.
58. What is the render props pattern?
With render props, a component receives a function as a prop (or as children) and calls it to decide what to render, passing its internal state as arguments. The component owns the logic; the caller owns the markup.
import { useState } from "react";
function Toggle({ children }) {
const [on, setOn] = useState(false);
return children({ on, toggle: () => setOn(o => !o) });
}
export default function App() {
return (
<div>
<Toggle>
{({ on, toggle }) => <button onClick={toggle}>FAQ is {on ? "open" : "closed"}</button>}
</Toggle>
<Toggle>
{({ on, toggle }) => (
<label><input type="checkbox" checked={on} onChange={toggle} /> {on ? "Subscribed" : "Subscribe"}</label>
)}
</Toggle>
</div>
);
}Output:
After clicking the first toggle:
Screen:
[FAQ is open][ ] SubscribeLike HOCs, render props have mostly been replaced by custom hooks (const { on, toggle } = useToggle()), but the pattern is still used by libraries such as Formik and some list virtualisers.
59. How do you validate a form in React?
import { useState } from "react";
function validate({ email, password }) {
const errors = {};
if (!/^\S+@\S+\.\S+$/.test(email)) errors.email = "Enter a valid email";
if (password.length < 8) errors.password = "At least 8 characters";
return errors;
}
export default function App() {
const [values, setValues] = useState({ email: "", password: "" });
const [touched, setTouched] = useState({});
const errors = validate(values); // derived, not stored
const show = name => touched[name] && errors[name];
const change = e => setValues(v => ({ ...v, [e.target.name]: e.target.value }));
const blur = e => setTouched(t => ({ ...t, [e.target.name]: true }));
function submit(e) {
e.preventDefault();
setTouched({ email: true, password: true });
if (Object.keys(errors).length === 0) console.log("submitted", values.email);
}
return (
<form onSubmit={submit} noValidate>
<input name="email" placeholder="Email" value={values.email} onChange={change} onBlur={blur} />
{show("email") && <small style={{ color: "crimson" }}> {errors.email}</small>}
<br />
<input name="password" type="password" placeholder="Password" value={values.password} onChange={change} onBlur={blur} />
{show("password") && <small style={{ color: "crimson" }}> {errors.password}</small>}
<br />
<button>Sign up</button>
</form>
);
}Output:
After typing "riya@" and clicking "Sign up":
Screen:
[riya@] Enter a valid email
[Password]
[Sign up]Errors are derived from the values on every render, and shown only after a field is touched or the form is submitted. For bigger forms, React Hook Form with a schema library such as Zod is the common choice. Always validate again on the server.
60. How can you reset a component’s state with a key?
Giving a component a different key makes React treat it as a brand-new component: the old one unmounts and a fresh one mounts with initial state. It is the clean way to reset a form when the thing it edits changes.
import { useState } from "react";
function ChatInput({ contact }) {
const [draft, setDraft] = useState("");
return <input placeholder={"Message " + contact} value={draft} onChange={e => setDraft(e.target.value)} />;
}
export default function App() {
const [to, setTo] = useState("Riya");
return (
<div>
<button onClick={() => setTo("Riya")}>Riya</button>
<button onClick={() => setTo("Aman")}>Aman</button>
<p>Without key: <ChatInput contact={to} /></p>
<p>With key: <ChatInput key={to} contact={to} /></p>
</div>
);
}Output:
After typing "Hi Riya!" in both boxes and switching to Aman:
Screen:
[Riya][Aman]
Without key: [Hi Riya!]
With key: [Message Aman]Without the key, the draft meant for Riya stays in the box when you switch to Aman, which could send it to the wrong person. With the key, switching contacts gives a clean input.
61. Why should you avoid copying props into state?
Initialising state from a prop (useState(props.value)) only uses the prop on the first render. Later changes to the prop are ignored, so the component shows stale data. If a value can be calculated from props or state, calculate it during render instead of storing it.
import { useState } from "react";
function PriceTagBug({ price }) {
const [shown] = useState(price); // copied once, never updated
return <p>Bug: Rs {shown}</p>;
}
function PriceTag({ price, discount }) {
const final = price - (price * discount) / 100; // derived during render
return <p>Correct: Rs {final}</p>;
}
export default function App() {
const [price, setPrice] = useState(1000);
return (
<div>
<button onClick={() => setPrice(p => p + 500)}>Increase price</button>
<PriceTagBug price={price} />
<PriceTag price={price} discount={10} />
</div>
);
}Output:
After clicking "Increase price":
Screen:
[Increase price]
Bug: Rs 1000
Correct: Rs 1350Copying a prop into state is fine when you intend it as an initial value, for example initialColor for an editable colour picker; name the prop initial... or default... to make that clear. Use a key to reset the state when the source changes.
62. Why does my useEffect run twice in development?
Because the app is wrapped in <StrictMode>, which deliberately mounts, unmounts and remounts every component once in development. The goal is to prove that your effect cleans up after itself. It does not happen in production.
import { StrictMode, useEffect, useState } from "react";
function ChatRoom({ room }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
console.log("connecting to", room);
const id = setInterval(() => setMessages(m => [...m, "ping"]), 150);
return () => {
console.log("disconnecting from", room);
clearInterval(id);
};
}, [room]);
return <p>{room}: {messages.length} messages</p>;
}
export default function App() {
return <StrictMode><ChatRoom room="general" /></StrictMode>;
}Output:
After about 0.4 seconds:
Screen:
general: 3 messages
Console:
connecting to general
disconnecting from general
connecting to generalWith the cleanup, the double mount is harmless: the first interval is cleared, and you see the message count rise at the normal speed. Remove the cleanup and two intervals run, doubling the speed, which is the bug StrictMode is trying to show you. Do not “fix” it by removing StrictMode or adding a ref flag.
63. How do you avoid race conditions when fetching data?
If the input changes quickly (a search box, a tab switch), several requests can be in flight at once, and an older, slower response can arrive last and overwrite the newer one. Ignore or abort outdated requests in the effect cleanup.
import { useState, useEffect } from "react";
const delays = { a: 500, ab: 100 }; // the first request is the slowest
const search = q => new Promise(r => setTimeout(() => r(`results for "${q}"`), delays[q] ?? 50));
function Results({ query, safe }) {
const [text, setText] = useState("...");
useEffect(() => {
let stale = false;
search(query).then(res => {
if (safe && stale) return console.log("ignored old response:", res);
setText(res);
});
return () => { stale = true; };
}, [query, safe]);
return <p>{safe ? "With cleanup" : "Without cleanup"}: {text}</p>;
}
export default function App() {
const [q, setQ] = useState("a");
return (
<div>
<button onClick={() => setQ("ab")}>Type one more letter</button>
<Results query={q} safe={false} />
<Results query={q} safe={true} />
</div>
);
}Output:
After clicking the button and waiting for both requests:
Screen:
[Type one more letter]
Without cleanup: results for "a"
With cleanup: results for "ab"
Console:
ignored old response: results for "a"The unsafe version ends up showing results for “a” while the query is “ab”. With real fetch, pass an AbortController signal and call abort() in the cleanup, which also cancels the network request. Libraries like TanStack Query handle this automatically.
64. What is useId used for?
useId() generates a unique ID that stays stable across renders and matches between server and client rendering. Use it to connect labels and inputs, or aria-describedby, in reusable components that may appear many times on a page.
import { useId } from "react";
function Field({ label, hint }) {
const id = useId();
return (
<div>
<label htmlFor={id}>{label}</label>{" "}
<input id={id} aria-describedby={id + "-hint"} />
<small id={id + "-hint"}> {hint}</small>
</div>
);
}
export default function App() {
return (
<form>
<Field label="Email" hint="We never share it" />
<Field label="Phone" hint="10 digits" />
<button type="button" onClick={() => console.log([...document.querySelectorAll("input")].map(i => i.id))}>Show ids</button>
</form>
);
}Output:
After clicking "Show ids":
Screen:
Email [] We never share it
Phone [] 10 digits
[Show ids]
Console:
[ '_r_0_', '_r_1_' ]Do not use useId for list keys; keys should come from your data. Math.random or a global counter would differ between server and client and cause hydration mismatches.
65. How do you prevent unnecessary re-renders with Context?
Every component that reads a context re-renders when the provider’s value changes, and a value written as {{ user, setUser }} is a new object on every render of the provider. Three fixes:
- Memoise the value with useMemo so it only changes when its contents do.
- Split contexts by how often they change: a stable dispatch or settings context, and a separate fast-changing state context.
- Move state down or use a store with selectors (Zustand, Redux, or useSyncExternalStore) when many components need small slices of a big object.
import { createContext, useContext, useState, useMemo, memo } from "react";
const ThemeCtx = createContext(null);
const Header = memo(function Header() {
const { theme } = useContext(ThemeCtx);
console.log("Header rendered with", theme);
return <h4>Header ({theme})</h4>;
});
export default function App() {
const [theme, setTheme] = useState("light");
const [typing, setTyping] = useState("");
const value = useMemo(() => ({ theme, setTheme }), [theme]); // stable unless theme changes
return (
<ThemeCtx value={value}>
<Header />
<input placeholder="Type here" value={typing} onChange={e => setTyping(e.target.value)} />
<button onClick={() => setTheme(t => (t === "light" ? "dark" : "light"))}>Toggle theme</button>
</ThemeCtx>
);
}Output:
After typing "abc" and toggling the theme:
Screen:
Header (dark)
[abc][Toggle theme]
Console:
Header rendered with light
Header rendered with darkTyping re-renders App, but the memoised Header does not re-render because the context value object stayed the same. Remove the useMemo and the Header logs on every keystroke.
66. How do you render a very long list efficiently?
Rendering 10,000 rows creates 10,000 DOM nodes, which is slow to mount, slow to update and heavy on memory. Virtualisation (windowing) renders only the rows visible in the viewport, plus a few extra, and positions them inside a tall container so scrolling still feels normal.
import { useState } from "react";
const ROWS = Array.from({ length: 10000 }, (_, i) => "Student #" + (i + 1));
const ROW_H = 24, VIEW_H = 120;
export default function App() {
const [top, setTop] = useState(0);
const first = Math.floor(top / ROW_H);
const visible = ROWS.slice(first, first + Math.ceil(VIEW_H / ROW_H) + 1);
return (
<div>
<div style={{ height: VIEW_H, overflowY: "auto", border: "1px solid #ccc" }} onScroll={e => setTop(e.currentTarget.scrollTop)}>
<div style={{ height: ROWS.length * ROW_H, position: "relative" }}>
{visible.map((r, i) => (
<div key={first + i} style={{ position: "absolute", top: (first + i) * ROW_H, height: ROW_H }}>{r}</div>
))}
</div>
</div>
<p>Rendering {visible.length} of {ROWS.length} rows. Scroll the box.</p>
</div>
);
}Output:
On the first render:
Screen:
Student #1
Student #2
Student #3
Student #4
Student #5
Student #6
Rendering 6 of 10000 rows. Scroll the box.In production use a library: TanStack Virtual or react-window. Also consider pagination or “load more”, and CSS content-visibility: auto for long, mostly static pages.
67. What are synthetic events, and how does React attach event listeners?
React wraps native browser events in SyntheticEvent objects that behave the same in every browser. Instead of adding a listener to each element, React 17+ attaches one listener per event type to the root container and dispatches events through the component tree itself. This is event delegation.
export default function App() {
return (
<div onClickCapture={() => console.log("1. capture: div")} onClick={() => console.log("4. bubble: div")}>
<button
onClickCapture={() => console.log("2. capture: button")}
onClick={e => {
console.log("3. button | synthetic:", e.constructor.name !== "MouseEvent", "| native:", e.nativeEvent.constructor.name);
}}>
Click
</button>
</div>
);
}Output:
After clicking the button:
Screen:
[Click]
Console:
1. capture: div
2. capture: button
3. button | synthetic: true | native: PointerEvent
4. bubble: divAdd Capture to a handler name to listen during the capture phase. Event pooling (reusing event objects) was removed in React 17, so you can read e.target inside async code without calling e.persist(). Use e.nativeEvent when you need the browser’s original event.
68. How do you read form values without controlled inputs?
export default function App() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
const values = Object.fromEntries(data);
values.topics = data.getAll("topics");
console.log(values);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" defaultValue="Riya" />
<select name="level" defaultValue="Intermediate"><option>Beginner</option><option>Intermediate</option></select>
<label><input type="checkbox" name="topics" value="hooks" defaultChecked /> Hooks</label>
<label><input type="checkbox" name="topics" value="context" /> Context</label>
<button>Save</button>
</form>
);
}Output:
After ticking "Context" and clicking Save:
Screen:
[Riya][Intermediate ▾][x] Hooks[x] Context[Save]
Console:
{ name: 'Riya', level: 'Intermediate', topics: [ 'hooks', 'context' ] }Uncontrolled inputs use defaultValue and defaultChecked for their starting value, and FormData collects everything at submit time. There is no re-render on each keystroke, which is why React Hook Form takes this approach, and React 19 form Actions pass the FormData to your function directly (question 81).
69. How do class component lifecycle methods map to hooks?
| Class component | With hooks |
|---|---|
constructor / this.state = ... | useState(initial) or useState(() => expensive()) |
componentDidMount | useEffect(() => {...}, []) |
componentDidUpdate(prevProps) | useEffect(() => {...}, [dep]) |
componentWillUnmount | The cleanup function returned from useEffect |
shouldComponentUpdate / PureComponent | React.memo |
getDerivedStateFromProps | Compute during render, or reset with a key |
getSnapshotBeforeUpdate | useLayoutEffect with a ref (no exact equivalent) |
componentDidCatch / getDerivedStateFromError | No hook yet; keep a class error boundary |
import { Component, useState } from "react";
class Clock extends Component {
state = { ticks: 0 };
componentDidMount() { console.log("didMount"); this.id = setInterval(() => this.setState(s => ({ ticks: s.ticks + 1 })), 100); }
componentDidUpdate(prevProps) { if (prevProps.label !== this.props.label) console.log("didUpdate: label changed to", this.props.label); }
componentWillUnmount() { clearInterval(this.id); console.log("willUnmount"); }
render() { return <p>{this.props.label}: {this.state.ticks > 0 ? "ticking" : "starting"}</p>; }
}
export default function App() {
const [label, setLabel] = useState("Clock");
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setLabel("Timer")}>Rename</button>
<button onClick={() => setShow(false)}>Remove</button>
{show && <Clock label={label} />}
</div>
);
}Output:
After clicking Rename and then Remove:
Screen:
[Rename][Remove]
Console:
didMount
didUpdate: label changed to Timer
willUnmount70. What are PureComponent and shouldComponentUpdate?
shouldComponentUpdate(nextProps, nextState) lets a class component return false to skip a re-render. PureComponent implements it for you with a shallow comparison of props and state, which is the class equivalent of React.memo.
import { Component, PureComponent, useState } from "react";
class Plain extends Component {
render() { console.log("Plain rendered"); return <p>Plain: {this.props.score}</p>; }
}
class Pure extends PureComponent {
render() { console.log("Pure rendered"); return <p>Pure: {this.props.score}</p>; }
}
export default function App() {
const [tick, setTick] = useState(0);
return (
<div>
<button onClick={() => setTick(t => t + 1)}>Re-render parent ({tick})</button>
<Plain score={90} />
<Pure score={90} />
</div>
);
}Output:
After re-rendering the parent once:
Screen:
[Re-render parent (1)]
Plain: 90
Pure: 90
Console:
Plain rendered
Pure rendered
Plain renderedA shallow comparison compares references, so passing a new object or array prop every render defeats it, the same trap as with memo.
71. What happens if you call a hook inside a condition?
import { useState } from "react";
function Profile({ showAge }) {
const [name] = useState("Riya");
if (showAge) {
const [age] = useState(22); // breaks the rules of hooks
return <p>{name}, {age}</p>;
}
return <p>{name}</p>;
}
export default function App() {
const [showAge, setShowAge] = useState(false);
return (
<div>
<button onClick={() => setShowAge(true)}>Show age</button>
<Profile showAge={showAge} />
</div>
);
}Output:
After clicking "Show age":
Screen:
(nothing is shown)
Console:
React has detected a change in the order of Hooks called by Profile. This will lead to bugs and errors if not fixed.
Uncaught Error: Rendered more hooks than during the previous render.React stores hook values in a list ordered by call order. The first render called one hook; the second calls two, so React cannot match them and throws “Rendered more hooks than during the previous render”. The whole tree unmounts because there is no error boundary. Keep hooks unconditional at the top, and put the condition inside the hook or in the JSX. The ESLint plugin eslint-plugin-react-hooks catches this before you run the code.
72. What are compound components?
Compound components are a group of components that work together and share state implicitly through context, like <select> and <option>. The parent manages the state; the children read it. The result is a flexible API where the user arranges the pieces.
import { createContext, useContext, useState } from "react";
const TabsCtx = createContext(null);
function Tabs({ defaultTab, children }) {
const [active, setActive] = useState(defaultTab);
return <TabsCtx value={{ active, setActive }}>{children}</TabsCtx>;
}
function Tab({ id, children }) {
const { active, setActive } = useContext(TabsCtx);
return <button onClick={() => setActive(id)} style={{ fontWeight: active === id ? 700 : 400 }}>{children}</button>;
}
function Panel({ id, children }) {
const { active } = useContext(TabsCtx);
return active === id ? <div>{children}</div> : null;
}
Tabs.Tab = Tab;
Tabs.Panel = Panel;
export default function App() {
return (
<Tabs defaultTab="java">
<Tabs.Tab id="java">Java</Tabs.Tab>
<Tabs.Tab id="py">Python</Tabs.Tab>
<Tabs.Panel id="java"><p>Java DSA course</p></Tabs.Panel>
<Tabs.Panel id="py"><p>Python full course</p></Tabs.Panel>
</Tabs>
);
}Output:
After clicking the Python tab:
Screen:
[Java][Python]
Python full courseHeadless UI libraries such as Radix UI and Headless UI use this pattern for tabs, menus, accordions and dialogs.
73. How do you test React components?
The standard stack is Vitest or Jest as the test runner and React Testing Library for rendering and querying. Testing Library encourages testing what the user sees and does (text, roles, labels, clicks), not implementation details like state variable names.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { test, expect } from "vitest";
import Counter from "./Counter";
test("increments when the button is clicked", async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.getByText("Count: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /add/i }));
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});- Prefer
getByRoleandgetByLabelText: they also check accessibility. - Use
findBy...(async) for content that appears after data loads, and mock the network with MSW. - Test custom hooks with
renderHook. - Use Playwright or Cypress for end-to-end tests of full user flows.
The practice section below works the same way: it renders your component in a hidden page, clicks buttons and checks the text.
74. How do you add type checking to React components?
Most professional React code today uses TypeScript. Props become an interface or type, and the editor and compiler catch wrong or missing props before the code runs. The older prop-types package checked props at run time in development, but React 19 removed propTypes support for function components.
type ButtonProps = {
label: string;
variant?: "primary" | "secondary";
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
children?: React.ReactNode;
};
export function Button({ label, variant = "primary", onClick }: ButtonProps) {
return <button className={variant} onClick={onClick}>{label}</button>;
}
const [items, setItems] = useState<string[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
<Button label="Save" onClick={() => save()} />
// <Button label={42} /> error: number is not assignable to string75. When should you use Context, Redux or Zustand?
| Option | Best for | Trade-off |
|---|---|---|
| useState / useReducer | State used by one component or a small subtree | Prop drilling if it spreads far |
| Context | Rarely changing global values: theme, locale, logged-in user | Every consumer re-renders on change; no selectors |
| Zustand | Shared client state with little boilerplate | Fewer conventions than Redux on large teams |
| Redux Toolkit | Large apps with complex shared state, strict patterns, time-travel debugging | More concepts and code |
| TanStack Query / SWR | Server state: cached API data | Not for purely client UI state |
A strong interview answer separates server state (data from an API, which needs caching and refetching) from client state (UI state such as modals and form drafts). Much of what used to go into Redux is better handled by a query library, leaving very little truly global client state.
React interview questions for experienced developers
These 25 questions are for senior front-end and full-stack developers: Fiber and concurrent rendering, transitions, React 19 Actions and the new hooks, Server Components, the React Compiler, SSR and hydration, profiling, custom hooks you may be asked to write, security, accessibility and architecture.
76. What is React Fiber?
Fiber is React’s reconciliation engine, introduced in React 16. Each element in the tree gets a “fiber”, a JavaScript object that holds the component type, props, state, effects and links to its parent, first child and next sibling. Because the tree is a linked structure that React walks itself instead of using the JavaScript call stack, rendering can be split into small units of work.
- Render phase (interruptible): React walks the fibers, calls components and works out what changed. In concurrent rendering it can pause, yield to the browser, resume or throw the work away.
- Commit phase (synchronous): React applies the changes to the DOM, runs layout effects, then schedules passive effects. This phase is never interrupted, so the user never sees a half-updated UI.
- Lanes assign priorities: a click or keystroke is urgent; a transition or a deferred value can wait.
- Double buffering: React builds a “work in progress” tree next to the current one and swaps them at commit.
This architecture is what makes concurrent features (transitions, Suspense, useDeferredValue) and time slicing possible. It is also why components must be pure: a render may run and be discarded.
77. What is useTransition?
const [isPending, startTransition] = useTransition() marks a state update as non-urgent. React keeps the current UI responsive, renders the transition in the background, and can interrupt it if a more urgent update (like typing) arrives. isPending lets you show a subtle loading state instead of freezing.
import { useState, useTransition } from "react";
function SlowList({ tab }) {
const start = performance.now();
while (performance.now() - start < 120) {} // simulate a slow render
return <p>{tab} content rendered</p>;
}
export default function App() {
const [tab, setTab] = useState("About");
const [isPending, startTransition] = useTransition();
function select(next) {
startTransition(() => setTab(next));
}
return (
<div>
{["About", "Courses", "Reviews"].map(t => (
<button key={t} onClick={() => select(t)} style={{ fontWeight: tab === t ? 700 : 400 }}>{t}</button>
))}
{isPending && <span> loading...</span>}
<SlowList tab={tab} />
</div>
);
}Output:
After clicking Courses and waiting for the slow render:
Screen:
[About][Courses][Reviews]
Courses content renderedWithout the transition, the click blocks the page for the whole slow render. In React 19, startTransition also accepts an async function (an Action), and isPending stays true until it finishes (question 81).
78. What is useDeferredValue?
useDeferredValue(value) returns a copy of a value that is allowed to “lag behind”. During urgent updates, React first re-renders with the old deferred value, then renders again in the background with the new one. It is useful when you do not control the state update, for example a value that arrives as a prop.
import { useState, useDeferredValue, memo } from "react";
const Results = memo(function Results({ query }) {
const items = [];
for (let i = 0; i < 2000; i++) if (("item " + i).includes(query)) items.push(i);
return <p>{items.length} results for "{query}"</p>;
});
export default function App() {
const [text, setText] = useState("");
const deferred = useDeferredValue(text);
const stale = text !== deferred;
return (
<div>
<input placeholder="Search" value={text} onChange={e => setText(e.target.value)} />
<div style={{ opacity: stale ? 0.5 : 1 }}><Results query={deferred} /></div>
</div>
);
}Output:
After typing "19":
Screen:
[19]
139 results for "19"The input stays responsive because it uses the urgent value, while the memoised Results component uses the deferred one. useDeferredValue only helps if the slow part is wrapped in memo. Unlike debouncing, it has no fixed delay: on a fast device the lag is barely visible.
79. What is automatic batching in React 18 and later?
Batching groups several state updates into one re-render. React 17 batched only inside React event handlers. Since React 18 with createRoot, updates are batched everywhere: in timeouts, promises, native event listeners and async functions.
import { useState } from "react";
import { flushSync } from "react-dom";
export default function App() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
console.log("render", a, b);
function later() {
setTimeout(() => {
setA(x => x + 1);
setB(x => x + 1); // one render for both, even in a timeout
}, 0);
}
function separately() {
flushSync(() => setA(x => x + 1)); // forces an immediate render
setB(x => x + 1);
}
return (
<div>
<button onClick={later}>Update in timeout</button>
<button onClick={separately}>Update with flushSync</button>
</div>
);
}Output:
After clicking both buttons:
Screen:
[Update in timeout][Update with flushSync]
Console:
render 0 0
render 1 1
render 2 1
render 2 2flushSync opts out of batching when you must read the DOM right after an update, for example to scroll to a newly added item. Use it rarely, because it hurts performance.
80. What is the use() API in React 19?
use(resource) reads a value from a promise or a context during render. With a promise, the component suspends until it resolves, the nearest <Suspense> shows its fallback, and a rejection goes to the nearest error boundary. Unlike hooks, use can be called inside conditions and loops.
import { use, Suspense, useState } from "react";
const cache = new Map();
function fetchCourse(id) { // the promise must be cached, not created during render
if (!cache.has(id)) cache.set(id, new Promise(r => setTimeout(() => r({ id, title: "Course " + id, lessons: id * 10 }), 300)));
return cache.get(id);
}
function Course({ id }) {
const course = use(fetchCourse(id));
return <p>{course.title}: {course.lessons} lessons</p>;
}
export default function App() {
const [id, setId] = useState(1);
return (
<div>
<button onClick={() => setId(i => i + 1)}>Next course</button>
<Suspense fallback={<p>Loading course...</p>}>
<Course id={id} />
</Suspense>
</div>
);
}Output:
After the first course loads (about 0.3 s):
Screen:
[Next course]
Course 1: 10 lessonsThe promise must be stable: creating a new one inside the component on every render would suspend forever. In real apps it comes from a framework (a Server Component passing a promise down), a data library, or a cache like the one above.
81. What are Actions and useActionState in React 19?
An Action is an async function used in a transition, typically passed to a form’s action prop. React handles the pending state, errors and form reset for you. useActionState(fn, initialState) wraps an action and returns [state, formAction, isPending], where state is whatever the action last returned.
import { useActionState } from "react";
const fakeApi = name => new Promise(r => setTimeout(() => r(name.length >= 3), 200));
async function subscribe(prevState, formData) {
const name = formData.get("name").trim();
const ok = await fakeApi(name);
if (!ok) return { error: "Name must have at least 3 letters", count: prevState.count };
return { error: null, message: "Subscribed " + name, count: prevState.count + 1 };
}
export default function App() {
const [state, formAction, isPending] = useActionState(subscribe, { error: null, count: 0 });
return (
<form action={formAction}>
<input name="name" placeholder="Your name" />
<button disabled={isPending}>{isPending ? "Saving..." : "Subscribe"}</button>
{state.error && <p style={{ color: "crimson" }}>{state.error}</p>}
{state.message && <p>{state.message} (total {state.count})</p>}
</form>
);
}Output:
After typing "Riya" and clicking Subscribe:
Screen:
[Your name][Subscribe]
Subscribed Riya (total 1)There is no onSubmit, no preventDefault and no useState for loading or errors. After a successful action, React resets uncontrolled form fields automatically. With a framework such as Next.js, the same function can be a Server Function marked "use server", and the form works even before JavaScript loads.
82. What is useOptimistic?
useOptimistic(state, updateFn) shows a temporary, optimistic version of state while an async action is running, for example a like or a new message appearing instantly. When the action finishes, React switches back to the real state; if it failed, the optimistic change disappears.
import { useState, useOptimistic, startTransition } from "react";
const save = text => new Promise((ok, fail) => setTimeout(() => (text.includes("fail") ? fail(new Error("Server error")) : ok(text)), 400));
export default function App() {
const [messages, setMessages] = useState(["Welcome!"]);
const [optimistic, addOptimistic] = useOptimistic(messages, (cur, text) => [...cur, text + " (sending...)"]);
function send(text) {
startTransition(async () => {
addOptimistic(text);
try {
const saved = await save(text);
startTransition(() => setMessages(m => [...m, saved]));
} catch (e) {
console.log("rolled back:", e.message);
}
});
}
return (
<div>
<button onClick={() => send("Hello")}>Send Hello</button>
<button onClick={() => send("this will fail")}>Send failing</button>
<ul>{optimistic.map((m, i) => <li key={i}>{m}</li>)}</ul>
</div>
);
}Output:
Right after clicking "Send Hello" (it changes to the saved message about 0.4 s later):
Screen:
[Send Hello][Send failing]
Welcome!
Hello (sending...)Optimistic updates make apps feel instant, but always show the real result from the server in the end, and tell the user when something failed.
83. What is useFormStatus?
useFormStatus() (from react-dom) gives a component information about the form it is rendered inside: pending, data, method and action. It lets a reusable submit button show a loading state without passing props down.
import { useFormStatus } from "react-dom";
import { useState } from "react";
function SubmitButton({ children }) {
const { pending, data } = useFormStatus();
return <button disabled={pending}>{pending ? "Sending " + data.get("email") + "..." : children}</button>;
}
export default function App() {
const [done, setDone] = useState("");
async function join(formData) {
await new Promise(r => setTimeout(r, 300));
setDone("Joined with " + formData.get("email"));
}
return (
<form action={join}>
<input name="email" placeholder="Email" />
<SubmitButton>Join waitlist</SubmitButton>
<p>{done}</p>
</form>
);
}Output:
Right after clicking "Join waitlist" (it says "Joined" about 0.3 s later):
Screen:
[ri**@**il.com][Sending ri**@**il.com...]useFormStatus must be called from a component rendered inside the form, not the component that renders the form.
84. What are React Server Components?
Server Components run only on the server (at request time or build time) and send their rendered result to the browser, not their code. They can read databases or files directly and never add to the JavaScript bundle. Client Components, marked with "use client" at the top of the file, are the usual interactive components that run in the browser too.
// app/courses/page.jsx: a Server Component (the default in Next.js App Router)
import { db } from "@/lib/db";
import EnrollButton from "./EnrollButton";
export default async function CoursesPage() {
const courses = await db.course.findMany(); // runs on the server only
return (
<ul>
{courses.map(c => (
<li key={c.id}>{c.title} <EnrollButton courseId={c.id} /></li>
))}
</ul>
);
}
// app/courses/EnrollButton.jsx: a Client Component
"use client";
import { useState } from "react";
export default function EnrollButton({ courseId }) {
const [done, setDone] = useState(false);
return <button onClick={() => setDone(true)}>{done ? "Enrolled" : "Enroll"}</button>;
}- Server Components cannot use state, effects, event handlers or browser APIs.
- They can render Client Components and pass them serialisable props (not functions, except Server Functions).
- Client Components cannot import Server Components, but can receive them as
children. - They are different from SSR: SSR renders Client Components to HTML for the first load; Server Components never ship their code to the client at all.
85. What is the React Compiler?
The React Compiler (version 1.0 released in October 2025) is a build-time tool that analyses your components and hooks and inserts memoization automatically, at a finer level than you would by hand. In most code it makes manual useMemo, useCallback and React.memo unnecessary.
- It works as a Babel plugin, with support in Vite, Next.js and Expo.
- It relies on your code following the Rules of React (pure render, no mutation of props and state, hooks rules). Components that break the rules are skipped, and the ESLint plugin reports them.
- It works with React 17, 18 and 19 (older versions need a small runtime package).
- You can adopt it gradually, directory by directory, or opt out a component with
"use no memo".
In an interview, say you would still understand memoization (when a re-render happens and why) because you will read code without the compiler, and because the compiler cannot fix slow algorithms or huge lists.
86. What are SSR, SSG and hydration?
| What happens | Good for | |
|---|---|---|
| CSR (client-side rendering) | The server sends an empty HTML shell; the browser downloads JS and renders | Dashboards behind a login |
| SSR (server-side rendering) | The server renders HTML for each request; the browser shows it at once, then hydrates | Personalised or fast-changing pages that need SEO |
| SSG (static generation) | HTML is rendered once at build time and served from a CDN | Blogs, docs, marketing pages |
| ISR / revalidation | Static pages regenerated in the background after a time or on demand | Large catalogues that change sometimes |
| Streaming SSR | HTML is sent in chunks as Suspense boundaries resolve | Pages with slow data sections |
Hydration is React attaching event listeners and state to server-rendered HTML, using hydrateRoot. The first client render must produce exactly the same output as the server; otherwise you get a hydration mismatch. Common causes: reading window or localStorage during render, dates and random numbers, and invalid HTML nesting such as a div inside a p. Move browser-only values into useEffect, or use suppressHydrationWarning for unavoidable cases like timestamps.
87. How do you measure React performance? What is the Profiler API?
Start with the React DevTools Profiler to see which components rendered, why, and how long they took. In code, the <Profiler> component reports render timings for a subtree, which you can send to monitoring in production.
import { Profiler, useState } from "react";
function Expensive({ n }) {
let s = 0;
for (let i = 0; i < 2e5; i++) s += i % (n + 1);
return <p>Computed {s > 0 ? "a big sum" : "nothing"} for n = {n}</p>;
}
function onRender(id, phase, actualDuration, baseDuration) {
console.log(id, phase, "| actualDuration is a number:", typeof actualDuration === "number");
}
export default function App() {
const [n, setN] = useState(1);
return (
<Profiler id="ExpensiveSection" onRender={onRender}>
<Expensive n={n} />
<button onClick={() => setN(x => x + 1)}>Re-render</button>
</Profiler>
);
}Output:
After clicking Re-render once (real code would log actualDuration in milliseconds):
Screen:
Computed a big sum for n = 2
[Re-render]
Console:
ExpensiveSection mount | actualDuration is a number: true
ExpensiveSection update | actualDuration is a number: true- Also use the browser Performance panel for long tasks, and Lighthouse or real-user Core Web Vitals (LCP, INP, CLS).
- Fix the biggest cost first: unnecessary re-renders of big trees, expensive calculations in render, huge lists, large bundles and slow network waterfalls.
- Profile a production build; development builds are much slower and include extra checks.
88. What causes memory leaks in React apps?
A leak happens when something keeps a reference to a component’s data after the component is gone. In React the usual causes are effects without cleanup: intervals, subscriptions, WebSocket or EventSource connections, window listeners and pending async work.
import { useEffect, useState } from "react";
function OnlineBadge() {
const [online, setOnline] = useState(true);
useEffect(() => {
const on = () => setOnline(true), off = () => setOnline(false);
window.addEventListener("online", on);
window.addEventListener("offline", off);
console.log("listeners added");
return () => { // without this, every mount adds two more listeners
window.removeEventListener("online", on);
window.removeEventListener("offline", off);
console.log("listeners removed");
};
}, []);
return <span>{online ? "Online" : "Offline"}</span>;
}
export default function App() {
const [show, setShow] = useState(true);
return <div><button onClick={() => setShow(s => !s)}>Toggle badge</button> {show && <OnlineBadge />}</div>;
}Output:
After toggling the badge off and on:
Screen:
[Toggle badge] Online
Console:
listeners added
listeners removed
listeners addedOther sources: global caches or stores that grow without limits, closures in long-lived callbacks that hold large data, and third-party widgets that are not destroyed. Find them with the Chrome Memory panel (heap snapshots before and after repeating an action) and look for detached DOM nodes.
89. What is useSyncExternalStore?
useSyncExternalStore(subscribe, getSnapshot) subscribes a component to a store that lives outside React: a state library, browser APIs such as navigator.onLine or matchMedia, or a WebSocket feed. It is safe with concurrent rendering (no “tearing”, where parts of the UI show different versions of the same data). Zustand and Redux use it internally.
import { useSyncExternalStore } from "react";
function createStore(initial) {
let state = initial;
const listeners = new Set();
return {
get: () => state,
set: fn => { state = fn(state); listeners.forEach(l => l()); },
subscribe: l => { listeners.add(l); return () => listeners.delete(l); }
};
}
const cart = createStore({ items: 0 });
function useCartItems() {
return useSyncExternalStore(cart.subscribe, () => cart.get().items);
}
function Badge() { return <b>Cart ({useCartItems()})</b>; }
function AddButton() { return <button onClick={() => cart.set(s => ({ ...s, items: s.items + 1 }))}>Add item</button>; }
export default function App() {
return <div><Badge /> <AddButton /></div>;
}Output:
After clicking "Add item" twice:
Screen:
Cart (2) [Add item]getSnapshot must return the same value when nothing changed (return primitives or cached objects), otherwise React re-renders in an endless loop.
90. How do you avoid unnecessary re-renders without memo?
When a component’s state changes, React re-renders it and all its children. Before reaching for memo, change the structure:
- Move state down into the smallest component that needs it, so fewer components re-render.
- Lift content up and pass it as
children: elements created by the parent are the same objects on every render of the wrapper, so React skips them. - Keep state local and derived values computed, instead of syncing extra state in effects.
import { useState } from "react";
function SlowTree() {
console.log("SlowTree rendered");
return <p>Pretend this is a big, slow part of the page.</p>;
}
function ColorPicker({ children }) { // owns the fast-changing state
const [color, setColor] = useState("#ff0000");
return (
<div style={{ borderLeft: "6px solid " + color, paddingLeft: 8 }}>
<button onClick={() => setColor(c => (c === "#ff0000" ? "#0000ff" : "#ff0000"))}>Change colour</button>
{children}
</div>
);
}
export default function App() {
return (
<ColorPicker>
<SlowTree />
</ColorPicker>
);
}Output:
After changing the colour twice:
Screen:
[Change colour]
Pretend this is a big, slow part of the page.
Console:
SlowTree renderedSlowTree rendered only once, even though its wrapper re-rendered twice, because it was created by App, which did not re-render. This “children as props” trick is free and often better than memo.
91. Implement a useDebounce hook.
import { useState, useEffect } from "react";
function useDebounce(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id); // restart the timer on every change
}, [value, delay]);
return debounced;
}
export default function App() {
const [text, setText] = useState("");
const query = useDebounce(text, 300);
useEffect(() => {
if (query) console.log("API call for:", query);
}, [query]);
return (
<div>
<input placeholder="Search courses" value={text} onChange={e => setText(e.target.value)} />
<p>Typed: {text} | Debounced: {query}</p>
</div>
);
}Output:
After typing "react" quickly and waiting:
Screen:
[react]
Typed: react | Debounced: react
Console:
API call for: reactThe cleanup cancels the previous timer, so only the value that stays unchanged for 300 ms gets through: one API call instead of one per keystroke. A follow-up is a useDebouncedCallback that debounces a function instead of a value; keep the timer in a ref and clear it on unmount.
92. Implement a usePrevious hook.
import { useState, useRef, useEffect } from "react";
function usePrevious(value) {
const ref = useRef(undefined);
useEffect(() => {
ref.current = value; // runs after render, so the render sees the old value
}, [value]);
return ref.current;
}
export default function App() {
const [price, setPrice] = useState(500);
const prev = usePrevious(price);
const trend = prev === undefined ? "" : price > prev ? "up" : price < prev ? "down" : "same";
return (
<div>
<p>Price: Rs {price} (previous: {prev ?? "none"}) {trend}</p>
<button onClick={() => setPrice(p => p + 100)}>+100</button>
<button onClick={() => setPrice(p => p - 50)}>-50</button>
</div>
);
}Output:
After clicking +100 and then -50:
Screen:
Price: Rs 550 (previous: 600) down
[+100][-50]This classic version reads a ref during render, which the React docs discourage because it can be wrong in concurrent rendering. The pattern the docs recommend stores the previous value in state and updates it during render when the value changes: if (value !== prevValue) { setPrevValue(value); ... }.
93. How do you build an accessible modal in React?
An accessible modal needs: focus moved into the dialog when it opens and back to the trigger when it closes, focus kept inside while open, Escape to close, role="dialog" with aria-modal and a label, and the page behind made inert. The native <dialog> element with showModal() gives you most of this for free.
import { useRef, useEffect } from "react";
import { useState } from "react";
function Modal({ open, onClose, title, children }) {
const ref = useRef(null);
useEffect(() => {
const d = ref.current;
if (open && !d.open) d.showModal(); // focus trap, Escape and backdrop built in
if (!open && d.open) d.close();
}, [open]);
return (
<dialog ref={ref} onClose={onClose} aria-labelledby="modal-title">
<h3 id="modal-title">{title}</h3>
{children}
<button onClick={onClose}>Close</button>
</dialog>
);
}
export default function App() {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(true)}>Delete account</button>
<Modal open={open} onClose={() => { setOpen(false); console.log("closed, focus returns to the trigger"); }} title="Are you sure?">
<p>This cannot be undone.</p>
</Modal>
</div>
);
}Output:
After clicking "Delete account":
Screen:
[Delete account]
Are you sure?
This cannot be undone.
[Close]Test with the keyboard only and with a screen reader. Libraries such as Radix UI, React Aria and Headless UI handle the hard parts of accessible dialogs, menus and comboboxes.
94. How do you handle errors in a large React app?
- Error boundaries around routes and independent widgets, with a retry button, so one broken section does not blank the whole page.
- Root-level handlers in React 19:
createRoot(el, { onUncaughtError, onCaughtError, onRecoverableError })to log every error to a service such as Sentry, with the component stack. - Async and event handler errors are not caught by boundaries: use try/catch in handlers and Actions, and the error state of your data library.
- User-facing messages that say what happened and what to do, not raw stack traces; keep technical details in logs.
- Prevention: TypeScript, validation of API responses (for example with Zod), and tests for the error paths.
With React 19 Actions, a thrown error inside a transition is sent to the nearest error boundary, and useActionState lets you return errors as state for expected failures like validation.
95. What security issues should you watch for in React apps?
React escapes text in JSX, which prevents most XSS, but several paths bypass that protection:
dangerouslySetInnerHTMLwith unsanitised user content (question 34).- URLs from users:
<a href={userUrl}>can containjavascript:code. React 19 blocks javascript: URLs, but you should still validate links and only allow http and https. - Directly using refs to set
innerHTML, or passing user input toevalor third-party widgets that render HTML. - Spreading untrusted objects onto elements (
{...userProps}) can inject event handlers or styles. - Secrets in front-end code: anything in the bundle (API keys, env variables prefixed for the client) is public.
- Tokens in localStorage are readable by any injected script; prefer HttpOnly cookies, plus CSRF protection.
function SafeLink({ url, children }) {
let safe = "#";
try {
const u = new URL(url, "https://codeanddebug.in");
if (u.protocol === "http:" || u.protocol === "https:") safe = u.href;
} catch {}
return <a href={safe} target="_blank" rel="noopener noreferrer">{children} ({safe})</a>;
}
export default function App() {
return (
<ul>
<li><SafeLink url="https://react.dev">React docs</SafeLink></li>
<li><SafeLink url="javascript:alert(1)">Bad link</SafeLink></li>
<li><SafeLink url="/blog">Relative link</SafeLink></li>
</ul>
);
}Output:
On the first render:
Screen:
React docs (https://react.dev/)
Bad link (#)
Relative link (https://codeanddebug.in/blog)96. Why should you never define a component inside another component?
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
function Inner() { // a brand-new component type on every render
const [text, setText] = useState("");
return <input placeholder="Inner input" value={text} onChange={e => setText(e.target.value)} />;
}
return (
<div>
<Inner />
<button onClick={() => setCount(c => c + 1)}>Parent re-render ({count})</button>
</div>
);
}Output:
After typing "hello" and re-rendering the parent:
Screen:
[Inner input][Parent re-render (1)]Each render of App creates a new Inner function, so React sees a different component type and unmounts the old one, losing its state and DOM (the input is cleared and loses focus). It also hurts performance. Define components at the top level and pass what they need as props.
97. What are ref callbacks, and what changed in React 19?
Instead of a ref object, you can pass a function to ref. React calls it with the DOM node when the element mounts. In React 19 the callback can return a cleanup function, which React calls when the element is removed, so you no longer get a null call to handle.
import { useState } from "react";
export default function App() {
const [items, setItems] = useState(["Intro", "Hooks"]);
return (
<div>
<button onClick={() => setItems(i => [...i, "Context"])}>Add</button>
<button onClick={() => setItems(i => i.slice(1))}>Remove first</button>
<ul>
{items.map(item => (
<li key={item} ref={node => {
console.log("attached", node.textContent);
return () => console.log("detached", item);
}}>{item}</li>
))}
</ul>
</div>
);
}Output:
After clicking Add and then "Remove first":
Screen:
[Add][Remove first]
Hooks
Context
Console:
attached Intro
attached Hooks
detached Intro
detached Hooks
attached Intro
attached Hooks
attached Context
detached Intro
detached Hooks
detached Context
attached Hooks
attached ContextRef callbacks are handy for measuring elements, attaching observers (ResizeObserver, IntersectionObserver) and keeping a Map of refs for a dynamic list. An inline callback is a new function each render, so React detaches and re-attaches it on every render; wrap it in useCallback if that matters.
98. How does React 19 handle document metadata and stylesheets?
React 19 lets components render <title>, <meta> and <link> tags anywhere in the tree, and hoists them into the document <head>. Stylesheets with a precedence prop are de-duplicated and ordered, and Suspense waits for them, so a component can bring its own CSS. New APIs such as preload, preinit and prefetchDNS from react-dom give hints for loading resources early.
import { useState } from "react";
function CoursePage({ title }) {
return (
<article>
<title>{title + " | Code and Debug"}</title>
<meta name="description" content={"Learn " + title + " with examples"} />
<h3>{title}</h3>
</article>
);
}
export default function App() {
const [title, setTitle] = useState("React Hooks");
return (
<div>
<button onClick={() => setTitle("React 19 Actions")}>Next page</button>
<CoursePage title={title} />
<button onClick={() => console.log("head title:", document.title, "| meta:", document.querySelector("meta[name=description]").content)}>Check head</button>
</div>
);
}Output:
After clicking "Next page" and "Check head":
Screen:
[Next page]
React 19 Actions
[Check head]
Console:
head title: React 19 Actions | Code and Debug | meta: Learn React 19 Actions with examplesThis replaces libraries like react-helmet for simple cases. Frameworks such as Next.js still offer their own metadata APIs, which work with server rendering and streaming.
99. How would you structure a large React application?
- Organise by feature, not by file type:
features/cart/holds its components, hooks, API calls, tests and types together; shared UI goes incomponents/ui. - Separate server state from client state: a query library for API data, local state first, and a small global store only for truly shared client state.
- A design system of accessible base components (buttons, inputs, dialogs), often built on a headless library, so features do not reinvent them.
- Clear boundaries: route-level code splitting, error boundaries and Suspense boundaries per section.
- Type safety and contracts: TypeScript everywhere, generated API types, and validated responses.
- Quality gates: ESLint (including the hooks and compiler rules), tests at the right level, a performance budget in CI, and monitoring in production.
Interviewers care less about a perfect folder tree than about the reasons: how the structure keeps features independent, makes changes local, and lets a growing team work without stepping on each other.
100. How do controlled and uncontrolled patterns apply to reusable components?
A reusable component such as an accordion, tabs or a date picker should usually support both modes: uncontrolled (it keeps its own state, with an optional defaultValue) and controlled (the parent passes value and onChange). If value is provided, the component uses it; otherwise it uses internal state.
import { useState } from "react";
function useControllable(value, defaultValue, onChange) {
const [inner, setInner] = useState(defaultValue);
const controlled = value !== undefined;
const current = controlled ? value : inner;
const set = next => {
if (!controlled) setInner(next);
onChange?.(next);
};
return [current, set];
}
function Stepper({ value, defaultValue = 1, onChange, max = 5 }) {
const [n, setN] = useControllable(value, defaultValue, onChange);
return <span><button onClick={() => setN(Math.max(0, n - 1))}>-</button> {n} <button onClick={() => setN(Math.min(max, n + 1))}>+</button></span>;
}
export default function App() {
const [qty, setQty] = useState(2);
return (
<div>
<p>Uncontrolled: <Stepper defaultValue={1} /></p>
<p>Controlled: <Stepper value={qty} onChange={setQty} /> (parent sees {qty})</p>
</div>
);
}Output:
On the first render:
Screen:
Uncontrolled: [-] 1 [+]
Controlled: [-] 2 [+] (parent sees 2)Never switch a component between controlled and uncontrolled during its life; React warns about this for inputs too (“A component is changing an uncontrolled input to be controlled”). Headless libraries use exactly this pattern.
React coding interview questions: 20 problems with tests
React machine coding rounds ask you to build small components and hooks quickly. These 20 problems are the ones asked most often, from a counter to useDebounce and a cart reducer. Write your code in the editor and press Run tests: the page renders your component in a hidden test page, clicks and types like a user, and shows which tests passed. Your code and your progress are saved in this browser.
Hooks such as useState, useEffect and useRef are already available, so you do not need imports. Keep the component name from the starter code. Try each problem before you open “Show solution”.
Your progress
Easy React coding questions
State, props, lists and controlled inputs: the warm-up tasks in most rounds.
1. Counter with reset
Build Counter. It shows Count: N in a <p> and three buttons labelled +, - and Reset. The count starts at the start prop (default 0).
Show solution
function Counter({ start = 0 }) {
const [count, setCount] = useState(start);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>+</button>
<button onClick={() => setCount(c => c - 1)}>-</button>
<button onClick={() => setCount(start)}>Reset</button>
</div>
);
}2. Show and hide text
Build Spoiler. It shows a button Show. Clicking it reveals a <p> with the text prop and changes the button to Hide; clicking again hides it.
Show solution
function Spoiler({ text }) {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(o => !o)}>{open ? "Hide" : "Show"}</button>
{open && <p>{text}</p>}
</div>
);
}3. Greeting with a default
Build Greeting that renders an <h2> with Hello, NAME!. If the name prop is missing or empty, use Guest.
Show solution
function Greeting({ name }) {
return <h2>Hello, {name || "Guest"}!</h2>;
}4. Render a list
Build FruitList. Given a fruits array of strings, render a <ul> with one <li> per fruit (use proper keys). If the array is empty, render <p>No fruits</p> instead.
Show solution
function FruitList({ fruits }) {
if (fruits.length === 0) return <p>No fruits</p>;
return <ul>{fruits.map(f => <li key={f}>{f}</li>)}</ul>;
}5. Controlled input
Build NameInput: an input with placeholder Name and a <p> that shows You typed: TEXT, updating as the user types.
Show solution
function NameInput() {
const [name, setName] = useState("");
return (
<div>
<input placeholder="Name" value={name} onChange={e => setName(e.target.value)} />
<p>You typed: {name}</p>
</div>
);
}6. Character counter
Build TweetBox: a <textarea>, a <p> showing N characters left (limit 20), and a Post button that is disabled when the text is empty or over the limit.
Show solution
function TweetBox() {
const [text, setText] = useState("");
const left = 20 - text.length;
return (
<div>
<textarea value={text} onChange={e => setText(e.target.value)} />
<p>{left} characters left</p>
<button disabled={text.length === 0 || left < 0}>Post</button>
</div>
);
}7. Grade badge
Build Grade that receives marks and renders a <span> with Distinction (75 or more), Pass (40 to 74) or Fail (below 40).
Show solution
function Grade({ marks }) {
const label = marks >= 75 ? "Distinction" : marks >= 40 ? "Pass" : "Fail";
return <span>{label}</span>;
}Medium React coding questions
Todo lists, tabs, filters, accordions, forms and your first custom hooks.
8. Todo list
Build TodoApp: an input with placeholder New todo, an Add button, and a <ul> of todos. Adding clears the input and ignores empty text. Each <li> has a Delete button that removes it.
Show solution
function TodoApp() {
const [text, setText] = useState("");
const [todos, setTodos] = useState([]);
function add() {
if (!text.trim()) return;
setTodos(t => [...t, { id: Date.now() + Math.random(), text: text.trim() }]);
setText("");
}
return (
<div>
<input placeholder="New todo" value={text} onChange={e => setText(e.target.value)} />
<button onClick={add}>Add</button>
<ul>
{todos.map(t => (
<li key={t.id}>{t.text} <button onClick={() => setTodos(all => all.filter(x => x.id !== t.id))}>Delete</button></li>
))}
</ul>
</div>
);
}9. useToggle hook
Write a custom hook useToggle(initial = false) that returns [value, toggle]. Calling toggle() flips the value; toggle(true) or toggle(false) sets it.
Show solution
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(next => setOn(v => (typeof next === "boolean" ? next : !v)), []);
return [on, toggle];
}10. useCounter with limits
Write useCounter(initial = 0, { min = -Infinity, max = Infinity } = {}) returning { count, inc, dec, reset }. The count must stay between min and max.
Show solution
function useCounter(initial = 0, { min = -Infinity, max = Infinity } = {}) {
const [count, setCount] = useState(initial);
const inc = () => setCount(c => Math.min(max, c + 1));
const dec = () => setCount(c => Math.max(min, c - 1));
const reset = () => setCount(initial);
return { count, inc, dec, reset };
}11. Tabs
Build Tabs. It receives tabs, an array of { label, content }. Render one button per tab and, below them, a <div className="panel"> with the active tab’s content. The first tab is active at the start.
Show solution
function Tabs({ tabs }) {
const [active, setActive] = useState(0);
return (
<div>
{tabs.map((t, i) => <button key={t.label} onClick={() => setActive(i)}>{t.label}</button>)}
<div className="panel">{tabs[active]?.content}</div>
</div>
);
}12. Search filter
Build FilterList. It receives items (strings) and renders an input with placeholder Search and a <ul> of the items that contain the search text, ignoring case. If nothing matches, show <p>No results</p> instead of the list.
Show solution
function FilterList({ items }) {
const [query, setQuery] = useState("");
const shown = items.filter(i => i.toLowerCase().includes(query.trim().toLowerCase()));
return (
<div>
<input placeholder="Search" value={query} onChange={e => setQuery(e.target.value)} />
{shown.length ? <ul>{shown.map(i => <li key={i}>{i}</li>)}</ul> : <p>No results</p>}
</div>
);
}13. Accordion
Build Accordion. It receives items, an array of { title, body }. Each title is a button; clicking it shows that item’s body in a <p>. Only one body is open at a time, and clicking the open title closes it.
Show solution
function Accordion({ items }) {
const [open, setOpen] = useState(null);
return (
<div>
{items.map((it, i) => (
<div key={it.title}>
<button onClick={() => setOpen(o => (o === i ? null : i))}>{it.title}</button>
{open === i && <p>{it.body}</p>}
</div>
))}
</div>
);
}14. usePrevious hook
Write usePrevious(value) that returns the value from the previous render (undefined on the first render).
Show solution
function usePrevious(value) {
const ref = useRef(undefined);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}15. Signup form validation
Build SignupForm: a <form> with an input placeholder Email and a Submit button. On submit, if the email does not match so*******@*******ng.something, show <p>Invalid email</p>; otherwise show <p>Welcome, EMAIL</p>. Prevent the page reload.
Show solution
function SignupForm() {
const [email, setEmail] = useState("");
const [msg, setMsg] = useState("");
function submit(e) {
e.preventDefault();
setMsg(/^\S+@\S+\.\S+$/.test(email) ? "Welcome, " + email : "Invalid email");
}
return (
<form onSubmit={submit}>
<input placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} />
<button>Submit</button>
{msg && <p>{msg}</p>}
</form>
);
}Hard React coding questions
Async hooks, pagination, a rating widget and a reducer.
16. useDebounce hook
Write useDebounce(value, delay). It returns value, but only after value has stopped changing for delay milliseconds.
Show solution
function useDebounce(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}17. useAsync hook
Write useAsync(asyncFn) that calls asyncFn once on mount and returns { loading, data, error }. loading is true until the promise settles; on failure, error holds the error message.
Show solution
function useAsync(asyncFn) {
const [state, setState] = useState({ loading: true, data: null, error: null });
useEffect(() => {
let ignore = false;
asyncFn().then(
data => { if (!ignore) setState({ loading: false, data, error: null }); },
err => { if (!ignore) setState({ loading: false, data: null, error: err.message }); }
);
return () => { ignore = true; };
}, []);
return state;
}18. Pagination
Build Paginated. It receives items and pageSize, renders the current page in a <ul>, a <span> with Page X of Y, and Prev and Next buttons that are disabled on the first and last page.
Show solution
function Paginated({ items, pageSize }) {
const [page, setPage] = useState(1);
const pages = Math.max(1, Math.ceil(items.length / pageSize));
const shown = items.slice((page - 1) * pageSize, page * pageSize);
return (
<div>
<ul>{shown.map(i => <li key={i}>{i}</li>)}</ul>
<button disabled={page === 1} onClick={() => setPage(p => p - 1)}>Prev</button>
<span>Page {page} of {pages}</span>
<button disabled={page === pages} onClick={() => setPage(p => p + 1)}>Next</button>
</div>
);
}19. Star rating
Build StarRating with props max (default 5) and onChange. Render max buttons, each showing ★ if it is at or below the current rating and ☆ otherwise, plus a <p> with N of MAX. Clicking star number k sets the rating to k and calls onChange(k).
Show solution
function StarRating({ max = 5, onChange }) {
const [rating, setRating] = useState(0);
return (
<div>
{Array.from({ length: max }, (_, i) => (
<button key={i} onClick={() => { setRating(i + 1); onChange?.(i + 1); }}>{i < rating ? "★" : "☆"}</button>
))}
<p>{rating} of {max}</p>
</div>
);
}20. Cart reducer
Write a pure reducer cartReducer(state, action) for state { items: [{ id, qty }] }. Support { type: "add", id } (add with qty 1, or increase qty), { type: "remove", id } (decrease qty, removing the item at 0) and { type: "clear" }. Never mutate the old state.
Show solution
function cartReducer(state, action) {
switch (action.type) {
case "add": {
const found = state.items.some(i => i.id === action.id);
return { ...state, items: found ? state.items.map(i => (i.id === action.id ? { ...i, qty: i.qty + 1 } : i)) : [...state.items, { id: action.id, qty: 1 }] };
}
case "remove":
return { ...state, items: state.items.map(i => (i.id === action.id ? { ...i, qty: i.qty - 1 } : i)).filter(i => i.qty > 0) };
case "clear":
return { ...state, items: [] };
default:
return state;
}
}Download all 100 React interview questions as a PDF
The PDF has the same 100 React interview questions and answers, with every code example and what it shows, plus the 20 coding questions with solutions, in 95 printable pages with a clickable table of contents. Use it to revise offline, on your phone, or on paper before the interview. It is free, with no sign-up.
100 React Interview Questions and Answers
95 pages · Freshers, intermediate and experienced · 89 code examples
Frequently asked questions
What React questions are asked in interviews for freshers?
Freshers are most often asked about JSX, components, props vs state, useState and useEffect, lists and keys, controlled inputs, conditional rendering, lifting state up and the Context API. Questions 1 to 40 on this page cover them.
Which React topics are most important for interviews?
Hooks (especially useState, useEffect, useMemo, useCallback and custom hooks), re-rendering and reconciliation, keys, state management with Context or a library, and performance. For senior roles add React 18 and 19 features such as transitions, Suspense and Actions, plus server rendering.
What React coding questions are asked in machine coding rounds?
Common tasks are a counter, a todo list, a search filter, tabs, an accordion, a form with validation, pagination, a star rating and custom hooks such as useDebounce or useFetch. The 20 coding questions on this page cover these and check your component automatically.
How should I prepare for a React interview with 2 to 5 years of experience?
Expect deep questions on rendering, memoization and stale closures, plus React 18 and 19 features, testing, performance profiling and state management choices. Be ready to explain the architecture of a real project, a performance problem you fixed, and to build a component with hooks without an IDE.
Do I need to learn JavaScript before React?
Yes. React questions often turn into JavaScript questions about closures, this, array methods, promises and the event loop. Our JavaScript interview questions page covers those with runnable examples.
Can I download these React interview questions as a PDF?
Yes. All 100 questions and answers, with every code example and what it shows, plus the coding questions with solutions, are in a free 95-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.
Next steps
Work through one level at a time and press “Mark as done” on each of the React interview questions once you can answer it out loud without looking. Run the examples and change them: predicting what the preview will show before you press Run is the fastest way to learn React. Then build the coding questions without looking at the solutions. Most front-end interviews also test JavaScript and DSA, so continue with our JavaScript interview questions, the DSA interview cheat sheet and computer networks interview questions. All the best for your interview!
