Skip to content

React JS Interview Questions & Answers

All 200 unique questions in one place — 60 easy, 96 medium, 44 hard — grouped by topic.

Practise by topic

Solved overallStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is React and why is it so widely used for building web interfaces?

Save to ▾
Show answer
React is an open-source JavaScript library for building user interfaces from reusable components. You describe what the UI should look like for a given state and React updates the DOM efficiently when that state changes. It is popular because of its component model, huge ecosystem, strong job market, React Native for mobile, and frameworks like Next.js that add routing and server rendering on top.
02

What is JSX and how does the browser understand it?

Save to ▾
Show answer
JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. Browsers cannot run JSX directly, so a compiler such as Babel, SWC or esbuild (used by Vite) transforms it into calls like jsx('div', props) from react/jsx-runtime. JSX is just expressions, so you can embed values with curly braces, but attributes use camelCase names like className and onClick.
03

Explain the Virtual DOM and reconciliation in React.

Save to ▾
Show answer
The Virtual DOM is a lightweight JavaScript tree describing the UI. When state changes, React renders a new tree, compares it with the previous one (reconciliation, or diffing) and applies only the minimal real DOM changes. It assumes elements of different types produce different trees and uses keys to match list items, which makes the diff roughly linear instead of very expensive full tree comparison.
04

What is the difference between functional components and class components?

Save to ▾
Show answer
Class components extend React.Component, use this.state and lifecycle methods like componentDidMount. Functional components are plain functions that return JSX and use hooks such as useState and useEffect for state and side effects. Modern React code is written almost entirely with functional components because they are shorter, easier to test and reuse logic through custom hooks. Class components are still needed only for error boundaries.
05

What are keys in React lists and why are they required?

Save to ▾
Show answer
A key is a stable, unique identifier given to each element in a list so React can tell which items were added, removed or moved between renders. Without good keys React may reuse the wrong DOM nodes or component state. Use an id from your data, for example key={user.id}. Keys only need to be unique among siblings, not across the whole app.
06

How do you return multiple elements from a component without adding an extra div?

Save to ▾
Show answer
Use a Fragment. The short syntax <>...</> groups children without adding a DOM node. Use the long form when you need a key, for example inside a map. function Row({ item }) { return ( <> <td>{item.name}</td> <td>{item.price}</td> </> ); } items.map(i => <React.Fragment key={i.id}>...</React.Fragment>)
07

Show the common ways to do conditional rendering in React.

Save to ▾
Show answer
You can use if statements before return, the ternary operator, or logical AND. Be careful with && and numbers, because 0 is rendered. function Status({ user, count }) { if (!user) return <Login />; return ( <div> {user.isAdmin ? <AdminPanel /> : <Dashboard />} {count > 0 && <Badge count={count} />} </div> ); }
08

What does one-way data flow mean in React?

Save to ▾
Show answer
Data in React flows down from parent to child through props. A child cannot directly change its parent's data; instead the parent passes a callback function, and the child calls it to request a change. This makes the app predictable because you can trace where every value comes from. Two-way binding, as in some other frameworks, is done manually with value and onChange.
09

Your manager asks you to set up a new React project in 2026 and suggests Create React App. What would you recommend?

Save to ▾
Show answer
The React team deprecated Create React App in 2025. For a single-page app, use Vite (npm create vite@latest, choose React with TypeScript), which gives very fast dev server and builds. For full-stack apps with routing, SSR and server components, the React docs recommend a framework such as Next.js or React Router in framework mode. Choose based on whether you need server rendering and SEO.
10

You import a component and get the error 'Element type is invalid: expected a string or a class/function but got undefined'. How do you debug it?

Save to ▾
Show answer
This almost always means the import does not match the export. If the file uses export default Header, import it as import Header from './Header'. If it uses export function Header, import it as import { Header } from './Header'. Also check the file path, circular imports and that the component name starts with a capital letter. Logging the imported value quickly confirms it is undefined.
11

Write a simple counter component with increment, decrement and reset buttons.

Save to ▾
Show answer
A counter is the classic useState example. Use the functional updater so each click works on the latest value. import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <h2>{count}</h2> <button onClick={() => setCount(c => c + 1)}>+</button> <button onClick={() => setCount(c => c - 1)}>-</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); }
12

Tell me about a React project you built and the hardest problem you solved in it.

Save to ▾
Show answer
Situation: in my final year I built a hostel complaint portal with React, Vite and a Node API. Task: the complaint list became slow and buggy when filters changed. Action: I found I was storing filtered data in state and syncing it with effects, so I derived it during render with useMemo and fixed missing keys. Result: bugs disappeared, the page felt instant, and I learned to keep state minimal.
13

React changes fast. How do you keep your skills current?

Save to ▾
Show answer
I follow the official react.dev blog and docs, read release notes for React, Next.js and the libraries we use, and try new features in a small side project before using them at work. For example, when React 19 introduced Actions and useOptimistic, I rebuilt a form in my practice app first, noted pitfalls, and then shared a short demo with my team before we adopted it.
14

Your team uses the array index as key in a todo list and users report that checkboxes get ticked on the wrong item after deleting a row. What is happening?

Save to ▾
Show answer
When an item is deleted, every later item shifts to a new index, so React matches old state and DOM nodes to the wrong items. Uncontrolled inputs and component state stay attached to the index, not the data. The fix is to use a stable unique id from the data as the key. Index keys are only safe for static lists that never reorder, filter or delete.
15

What changed with createRoot in React 18 and later compared to ReactDOM.render?

Save to ▾
Show answer
createRoot from react-dom/client replaces the legacy ReactDOM.render, which was removed in React 19. createRoot enables the concurrent renderer, automatic batching of all updates, and features like useTransition and Suspense for data. You call const root = createRoot(document.getElementById('root')) and then root.render(<App />). For server-rendered HTML you use hydrateRoot instead.
16

What are synthetic events in React?

Save to ▾
Show answer
React wraps native browser events in a SyntheticEvent object that has the same interface (preventDefault, stopPropagation, target) across browsers. Since React 17, listeners are attached to the root container instead of document, which makes it safer to mix multiple React versions. Event pooling was removed, so you can read event properties asynchronously. Handlers are passed as functions, like onClick={handleClick}.
17

In development your API call inside useEffect fires twice, but only once in production. Why does this happen, and what does StrictMode do?

Save to ▾
Show answer
StrictMode is a development-only wrapper that helps find bugs. It renders components twice to catch impure rendering, and mounts, unmounts and remounts components to check that effects clean up properly. This is why a fetch in useEffect may appear to fire twice locally. It does not happen in production. The fix is to write proper cleanup, not to remove StrictMode.
18

Why does React prefer composition over inheritance?

Save to ▾
Show answer
React reuses UI by combining components, not by extending classes. You pass components or JSX as props or children, so a generic Card or Modal can wrap any content. Specialisation is done by configuring a general component with props, like <Button variant='danger'>. The React team found no use cases where inheritance hierarchies were better, and composition keeps components flexible and loosely coupled.
19

What is a Higher-Order Component and is it still used?

Save to ▾
Show answer
A Higher-Order Component is a function that takes a component and returns a new component with extra behaviour, for example withAuth(Profile) that redirects unauthenticated users. HOCs were common for sharing logic like routing or Redux connect. Today custom hooks are preferred because they avoid wrapper nesting, prop name collisions and confusing component trees. You will still see HOCs in older codebases.
20

What is the render props pattern?

Save to ▾
Show answer
Render props means passing a function as a prop that the component calls to decide what to render, for example <MouseTracker render={pos => <Cursor pos={pos} />} />. It lets a component share its state or behaviour while the caller controls the UI. Like HOCs, it has mostly been replaced by custom hooks, but libraries for forms and virtualised lists still expose render-prop or children-as-function APIs.
21

How do you create an error boundary in React?

Save to ▾
Show answer
An error boundary catches errors thrown while rendering its children and shows a fallback UI. It must be a class component (or use the react-error-boundary package). class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { logError(error, info.componentStack); } render() { return this.state.hasError ? <p>Something went wrong</p> : this.props.children; } } It does not catch errors in event handlers or async code.
22

What are portals and when would you use them?

Save to ▾
Show answer
A portal renders children into a DOM node outside the parent component's DOM hierarchy while keeping them in the same React tree, so context and event bubbling still work. import { createPortal } from 'react-dom'; function Modal({ children }) { return createPortal( <div className="modal">{children}</div>, document.getElementById('modal-root') ); } They are used for modals, tooltips and dropdowns that must escape overflow hidden or z-index issues.
23

A user types into an input inside a list row, then sorts the list, and the typed text appears in a different row. How would you fix this?

Save to ▾
Show answer
The rows are probably keyed by index or by a value that changes after sorting, so React keeps the DOM input in the same position while the data moves. Give each row a stable key from the data, such as the record id. Better still, make the input controlled and store its value in state keyed by id, so the text always follows the correct record.
24

What is automatic batching in React 18 and later?

Save to ▾
Show answer
Batching means React groups several state updates into one re-render. Before React 18 this only happened inside React event handlers. With createRoot, updates inside promises, setTimeout and native event handlers are also batched automatically. This reduces unnecessary renders. If you truly need a synchronous DOM update in between, you can use flushSync from react-dom, but that is rarely needed.
25

What is React Fiber?

Save to ▾
Show answer
Fiber is the reconciliation engine introduced in React 16. It represents each component as a unit of work (a fiber node) so rendering can be split into chunks, paused, prioritised and resumed. This makes concurrent features possible: urgent updates like typing can interrupt less urgent renders. Rendering happens in an interruptible render phase, then changes are applied in a synchronous commit phase.
26

What is the difference between props and state?

Save to ▾
Show answer
Props are inputs passed from a parent component and are read-only inside the child. State is data owned and managed by the component itself with useState or useReducer, and changing it triggers a re-render. A simple rule: if a value comes from outside and the component does not change it, it is a prop; if it changes over time due to user action or data loading, it is state.
27

Can a child component modify its props?

Save to ▾
Show answer
No. Props are read-only, and a component must behave like a pure function with respect to its props. Mutating a prop object would not trigger a re-render and would cause confusing bugs in the parent. If a child needs to change something, the parent should own that state and pass down a callback such as onChange, which the child calls with the new value.
28

What does lifting state up mean?

Save to ▾
Show answer
Lifting state up means moving shared state to the closest common parent of the components that need it. The parent holds the state and passes the value and a setter callback down as props. For example, a temperature input and a converter display both read from state kept in their parent. This keeps a single source of truth instead of two components trying to stay in sync.
29

What is prop drilling and how can you avoid it?

Save to ▾
Show answer
Prop drilling is passing props through several layers of components that do not use them, only to reach a deeply nested child. It makes code noisy and hard to refactor. Solutions include component composition (passing JSX as children so intermediate layers do not need the data), the Context API for app-wide values like theme or user, and state libraries such as Zustand or Redux Toolkit for complex shared state.
30

How do you update objects and arrays in state without mutating them?

Save to ▾
Show answer
Always create new copies so React detects the change by reference. // object setUser(u => ({ ...u, city: 'Pune' })); // add to array setItems(list => [...list, newItem]); // remove setItems(list => list.filter(i => i.id !== id)); // update one item setItems(list => list.map(i => i.id === id ? { ...i, done: true } : i));
31

How do you give default values to props in a function component?

Save to ▾
Show answer
Use JavaScript default parameters while destructuring props. defaultProps for function components was removed in React 19, so this is the standard way. function Button({ label = 'Submit', variant = 'primary', onClick }) { return ( <button className={`btn btn-${variant}`} onClick={onClick}> {label} </button> ); }
32

What is the children prop?

Save to ▾
Show answer
children is a special prop containing whatever JSX you place between a component's opening and closing tags. For example, in <Card><h3>Title</h3></Card>, the h3 is passed as props.children. It lets you build wrapper components like layouts, modals and cards that do not need to know their content in advance. It is the foundation of composition in React.
33

What is the difference between controlled and uncontrolled components?

Save to ▾
Show answer
In a controlled component, the form value lives in React state and the input gets value and onChange props, so React is the single source of truth. In an uncontrolled component the DOM keeps the value and you read it with a ref or FormData when needed. Controlled inputs make validation and conditional UI easy; uncontrolled inputs are simpler and can perform better for large forms.
34

How does a child component send data back to its parent?

Save to ▾
Show answer
The parent passes a callback function as a prop, and the child calls it with the data. function Parent() { const [city, setCity] = useState(''); return <CityPicker onSelect={setCity} />; } function CityPicker({ onSelect }) { return ( <select onChange={e => onSelect(e.target.value)}> <option>Delhi</option> <option>Noida</option> </select> ); }
35

A teammate writes user.name = 'Ravi' inside a click handler and the screen does not update. Why?

Save to ▾
Show answer
React decides to re-render when you call the state setter with a new value. Mutating the existing object does not call the setter, and even if you call setUser(user) with the same mutated object, React compares by reference with Object.is, sees no change and may skip rendering. Always create a new object, like setUser({ ...user, name: 'Ravi' }).
36

Why should you use the functional form of setState? Show an example.

Save to ▾
Show answer
State updates are scheduled, and each render sees a snapshot of state. If you call setCount(count + 1) several times in one handler, all calls read the same old value. The updater function receives the latest pending value. function addThree() { setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); } // count increases by 3, not 1
37

A developer stores fullName in state and updates it in a useEffect whenever firstName or lastName changes. What would you suggest?

Save to ▾
Show answer
This is redundant derived state. It causes an extra render and risks the values going out of sync. Compute it during render instead: const fullName = firstName + ' ' + lastName. If the calculation is expensive, wrap it in useMemo. As a rule, if a value can be calculated from existing props or state, do not store it in state and do not sync it with an effect.
38

On a profile edit page, when you switch from one user to another the form still shows the old user's typed values. How can you reset it cleanly?

Save to ▾
Show answer
React preserves state when the same component stays at the same position in the tree. Give the form a key tied to the user, like <ProfileForm key={user.id} user={user} />. When the key changes, React unmounts the old form and mounts a fresh one with new initial state. This is cleaner than writing an effect that manually resets every field when the user prop changes.
39

Your team's old codebase uses PropTypes and is upgrading to React 19. What would you recommend for checking prop types?

Save to ▾
Show answer
PropTypes checks props at runtime in development and was removed from the React package in React 19, so it now needs the separate prop-types library and is ignored silently. TypeScript checks types at compile time, gives editor autocompletion, and catches errors before code runs. Most new React projects in India and abroad use TypeScript, and many job descriptions now list it as required.
40

How do you type props for a component in TypeScript?

Save to ▾
Show answer
Define a type or interface and annotate the destructured props. type ProductCardProps = { title: string; price: number; tags?: string[]; onAdd: (id: string) => void; children?: React.ReactNode; }; function ProductCard({ title, price, tags = [], onAdd, children }: ProductCardProps) { return <div onClick={() => onAdd(title)}>{title} - Rs {price}{children}</div>; }
41

A teammate writes setCount(count + 1) three times in a click handler and is surprised that the count increases by only one. Explain why.

Save to ▾
Show answer
Inside one render, count is a constant snapshot, say 0. Each call schedules setCount(0 + 1), so all three set the same value 1, and React batches them into one render. State does not change immediately after calling the setter. To increment three times, use the updater form setCount(c => c + 1), which queues functions that each receive the latest pending value.
42

Should you keep related values in one state object or several useState calls?

Save to ▾
Show answer
Group values that always change together, like x and y coordinates, into one object. Keep unrelated values in separate useState calls, which makes updates simpler and avoids accidentally overwriting fields. Avoid contradictory or duplicated state, such as isLoading and isError both being true. When many values change together through clear events, useReducer is often a cleaner choice than a big object.
43

A cart page keeps the selected item object in state and also the items array. After editing the item's quantity, the details panel shows the old quantity. Why?

Save to ▾
Show answer
The selected item is a copy duplicated from the array, so updating the array does not update the copy. This breaks the single source of truth. Store only selectedId in state and derive the item during render: const selected = items.find(i => i.id === selectedId). Now there is one place where each item lives, and every view stays in sync automatically.
44

What are the risks of spreading all props like <Input {...props} />?

Save to ▾
Show answer
Spreading is convenient for wrapper components, but it can pass unknown attributes to DOM elements, causing console warnings, and it hides what the component actually accepts. It can also override props you set explicitly, depending on order. Prefer destructuring the props you use and spreading only the rest onto the underlying element, for example const { label, ...inputProps } = props.
45

A junior notices that every child component re-renders when the parent's state changes, even when their props did not change. How do you explain this?

Save to ▾
Show answer
By default, when a component renders, React re-renders all of its children, because it cannot know whether they depend on something else. Re-rendering is usually cheap since only real changes reach the DOM. If a child is expensive, wrap it in React.memo and keep its props stable with useCallback or useMemo, or let the React Compiler memoise automatically. Moving state down also helps.
46

Describe a time you disagreed with a teammate about how a component should be designed.

Save to ▾
Show answer
Situation: a teammate wanted one large Table component with over twenty boolean props. Task: we needed a design that both of us and future developers could maintain. Action: I built a quick prototype using composition with Table.Header and Table.Row, and we compared both on two real screens. Result: the team chose composition, prop count dropped sharply, and we agreed to prototype before arguing in future.
47

How does React decide whether to keep or reset a component's state?

Save to ▾
Show answer
State is tied to a component's position in the render tree, not to the variable or JSX line. If the same component type renders at the same position, its state is kept. If the type at that position changes, or its key changes, React destroys the subtree and its state. That is why defining a component inside another component causes state loss on every render.
48

A timer using setInterval inside useEffect always shows 1 and never goes higher. What is the bug?

Save to ▾
Show answer
The effect probably runs once with an empty dependency array and calls setCount(count + 1). The interval callback closes over the count from the first render, which is 0 forever, a stale closure. Fix it with the updater form setCount(c => c + 1), so the callback never needs the current value, and return a cleanup that calls clearInterval to avoid leaks.
49

What is state colocation and why does it matter for performance and maintainability?

Save to ▾
Show answer
State colocation means keeping state as close as possible to the components that use it. Global or high-level state causes large parts of the tree to re-render on every change and makes ownership unclear. If only a dropdown needs isOpen, keep it in the dropdown. Lift state only when siblings must share it. Good colocation often removes the need for memoisation entirely.
50

How would you update deeply nested state cleanly? Show with Immer.

Save to ▾
Show answer
Manual spreading of nested objects is error prone. Immer lets you write mutating code on a draft and produces an immutable copy. Redux Toolkit uses it internally. import { useImmer } from 'use-immer'; const [form, updateForm] = useImmer({ address: { city: '', pin: '' } }); updateForm(draft => { draft.address.city = 'Noida'; }); Also consider flattening state to avoid deep nesting.
51

What are React hooks and what are the rules of hooks?

Save to ▾
Show answer
Hooks are functions like useState and useEffect that let function components use state, side effects, context and other React features. Two rules apply: call hooks only at the top level of a component or custom hook, never inside loops, conditions or nested functions, and call them only from React functions. React relies on the call order being the same on every render to match state to each hook.
52

How does the dependency array of useEffect control when the effect runs?

Save to ▾
Show answer
With no array, the effect runs after every render. With an empty array [], it runs once after the first mount (and twice in development StrictMode to test cleanup). With values like [userId], it runs after mount and again whenever any listed value changes, compared using Object.is. Every reactive value the effect reads, such as props and state, should be included in the array.
53

What is useRef used for?

Save to ▾
Show answer
useRef returns a mutable object { current } that persists across renders without causing a re-render when changed. It has two main uses: holding a reference to a DOM node, for example to focus an input, and storing mutable values like timer ids, previous values or flags that should not trigger rendering. Do not read or write ref.current during rendering, except for lazy initialisation.
54

What does useContext do?

Save to ▾
Show answer
useContext reads the current value of a context created with createContext. React finds the nearest matching Provider above the component and returns its value; if none exists, it returns the default value. Whenever the provider value changes, every component using that context re-renders. In React 19 you can render <ThemeContext value={theme}> directly instead of ThemeContext.Provider, and use(ThemeContext) also works.
55

You see the error 'Rendered more hooks than during the previous render'. What is wrong?

Save to ▾
Show answer
A hook is being called conditionally or after an early return, so the number of hooks changes between renders. For example, if (!user) return null; placed before a useState call. React matches hooks by call order, so this breaks. Move all hook calls to the top of the component before any condition or early return, and put the condition inside the hook logic instead.
56

What is lazy initialisation in useState and when should you use it?

Save to ▾
Show answer
If the initial value is expensive to compute, pass a function instead of the value. React calls it only on the first render. // runs on every render (wasteful) const [data, setData] = useState(JSON.parse(localStorage.getItem('cart'))); // runs once const [data, setData] = useState(() => JSON.parse(localStorage.getItem('cart') ?? '[]') );
57

What is an effect cleanup function and why is it important?

Save to ▾
Show answer
The function you return from useEffect is the cleanup. React runs it before the effect runs again and when the component unmounts. Use it to clear timers, remove event listeners, close WebSocket connections, unsubscribe from stores or abort fetch requests. Without cleanup you get memory leaks, duplicate listeners and state updates on components that are no longer on the screen.
58

What is the difference between useMemo and useCallback?

Save to ▾
Show answer
useMemo caches the result of a calculation between renders, like a filtered list: useMemo(() => filter(items, q), [items, q]). useCallback caches a function definition itself: useCallback(fn, deps), which equals useMemo(() => fn, deps). Both are performance tools, useful when passing values to React.memo children or effect dependencies. With the React Compiler enabled, much of this manual memoisation becomes unnecessary.
59

When should you choose useReducer over useState? Show a small example.

Save to ▾
Show answer
Use useReducer when state has several related fields or many update types, so logic lives in one pure, testable function. function reducer(state, action) { switch (action.type) { case 'added': return [...state, action.item]; case 'removed': return state.filter(i => i.id !== action.id); default: return state; } } const [cart, dispatch] = useReducer(reducer, []); dispatch({ type: 'added', item });
60

Write a custom hook to fetch data with loading and error states.

Save to ▾
Show answer
A custom hook is a function starting with use that combines other hooks. function useFetch(url) { const [state, setState] = useState({ data: null, loading: true, error: null }); useEffect(() => { const ctrl = new AbortController(); setState(s => ({ ...s, loading: true })); fetch(url, { signal: ctrl.signal }) .then(r => { if (!r.ok) throw new Error(r.status); return r.json(); }) .then(data => setState({ data, loading: false, error: null })) .catch(err => { if (err.name !== 'AbortError') setState({ data: null, loading: false, error: err }); }); return () => ctrl.abort(); }, [url]); return state; }
61

What is useId and why not use Math.random for ids?

Save to ▾
Show answer
useId generates a unique, stable id for a component instance that matches between server and client rendering. It is used for accessibility attributes, like linking a label's htmlFor to an input's id. Math.random or a global counter would produce different values on the server and the browser, causing hydration mismatches, and would change on every render. useId should not be used as list keys.
62

What do useActionState and useFormStatus do in React 19?

Save to ▾
Show answer
useActionState wraps an action function and returns [state, formAction, isPending]; you pass formAction to a form's action prop and the returned state holds the result, like a validation error. useFormStatus, from react-dom, lets a child component such as a submit button read the pending status of the parent form without prop drilling. Together they remove a lot of manual loading and error state code.
63

Your component fetches data in useEffect and the network tab shows thousands of requests in a loop. What could cause it?

Save to ▾
Show answer
Common causes are a missing dependency array, so the effect runs after every render and its setState triggers another render, or a dependency that is a new object or array each render, like options={{ page: 1 }}. Since Object.is compares by reference, the effect always sees a change. Fix by adding correct dependencies, depending on primitive values, or memoising the object with useMemo.
64

The linter shows a react-hooks/exhaustive-deps warning and a teammate wants to disable the rule. What do you advise?

Save to ▾
Show answer
Disabling it usually hides a stale closure bug. The rule tells you the effect reads a value that can change. Instead, include the dependency, move a function inside the effect, use the updater form of setState so state is not needed, or move non-reactive logic into useEffectEvent. If an object dependency changes every render, create it inside the effect or memoise it. Suppress only with a clear comment.
65

A developer sends an analytics event inside a useEffect that watches a 'submitted' state flag. Is this a good pattern?

Save to ▾
Show answer
No. Logic caused by a specific user action belongs in the event handler, not in an effect. Setting a flag and reacting in an effect adds an extra render, is harder to follow and can fire again on remount in StrictMode. Call sendAnalytics directly in handleSubmit. Effects are for synchronising with external systems because the component is displayed, not for responding to events.
66

Write a useDebounce custom hook.

Save to ▾
Show answer
Debouncing delays a value until the user stops typing, which reduces API calls. function useDebounce(value, delay = 400) { const [debounced, setDebounced] = useState(value); useEffect(() => { const t = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(t); }, [value, delay]); return debounced; } const q = useDebounce(searchText); // fetch when q changes
67

A junior developer is confused about when to use useEffect. How would you explain it and help them?

Save to ▾
Show answer
Situation: a new joiner was putting almost all logic into effects, causing bugs. Task: help them build the right mental model. Action: I explained that effects sync with outside systems, while calculations go in render and user actions go in handlers. We refactored one of their components together and I shared the react.dev article on avoiding effects. Result: their next PR had no unnecessary effects.
68

When would you use useLayoutEffect instead of useEffect?

Save to ▾
Show answer
useEffect runs after the browser paints, which is fine for most side effects. useLayoutEffect runs synchronously after DOM changes but before paint, so it is used when you must measure layout and update immediately, for example positioning a tooltip based on its size, to avoid a visible flicker. It blocks painting, so overusing it hurts performance, and it does not run during server rendering.
69

A search box fetches results on every keystroke and sometimes shows results for an older query. How do you fix this race condition?

Save to ▾
Show answer
Responses can arrive out of order, so a slow old request overwrites newer results. Cancel or ignore stale requests in the effect cleanup. useEffect(() => { const ctrl = new AbortController(); fetch(`/api/search?q=${q}`, { signal: ctrl.signal }) .then(r => r.json()) .then(setResults) .catch(() => {}); return () => ctrl.abort(); }, [q]); Also debounce the input, or use TanStack Query which handles this for you.
70

Explain useTransition and useDeferredValue.

Save to ▾
Show answer
Both are concurrent features that keep the UI responsive. useTransition gives you startTransition to mark a state update as non-urgent, plus an isPending flag, so typing stays smooth while a heavy list re-renders. useDeferredValue takes a value and returns a lagging copy that React updates in the background. Use useTransition when you control the setter, and useDeferredValue when you only receive the value as a prop.
71

What is the use() API introduced in React 19?

Save to ▾
Show answer
use is a React 19 API that reads the value of a promise or a context during render. With a promise, the component suspends until it resolves, showing the nearest Suspense fallback, and errors go to the nearest error boundary. Unlike other hooks, use can be called inside conditions and loops. Promises should come from a framework, cache or server component, not be created fresh on every render.
72

What is useOptimistic and when would you use it?

Save to ▾
Show answer
useOptimistic shows a temporary optimistic state while an async action is running. For example, when a user likes a post, you immediately show the like count increased, call the server, and React automatically reverts to the real state when the action finishes or fails. It makes interfaces feel instant for actions that usually succeed, like sending a chat message or adding to a wishlist.
73

What is useEffectEvent?

Save to ▾
Show answer
useEffectEvent, stable since React 19.2, creates a function that always sees the latest props and state but is not reactive, so it does not need to be in the effect's dependency array. Example: a chat effect reconnects when roomId changes, and an onConnected event shows a notification using the current theme. Wrapping the notification in useEffectEvent stops theme changes from reconnecting the socket.
74

How do you expose a custom method like focus() from a child to a parent in React 19?

Save to ▾
Show answer
In React 19, function components receive ref as a normal prop, so forwardRef is no longer needed. Use useImperativeHandle to expose only selected methods. function SearchInput({ ref }) { const inputRef = useRef(null); useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus(), clear: () => { inputRef.current.value = ''; } })); return <input ref={inputRef} />; } // parent: const r = useRef(); <SearchInput ref={r} />; r.current.focus();
75

What is useSyncExternalStore?

Save to ▾
Show answer
useSyncExternalStore subscribes a component to an external, non-React data source, like a browser API or a custom store, in a way that is safe with concurrent rendering. You give it a subscribe function and a getSnapshot function, and optionally getServerSnapshot. It prevents tearing, where parts of the UI show different values of the same store. Libraries like Redux and Zustand use it internally.
76

What is the Context API and when should you use it?

Save to ▾
Show answer
Context lets a parent provide a value to any component below it without passing props through every level. You create it with createContext, provide a value high in the tree and read it with useContext. It is ideal for values that many components need and that change rarely, such as theme, language, logged-in user or feature flags. It is not a full replacement for a state management library.
77

Explain the core concepts of Redux.

Save to ▾
Show answer
Redux keeps global state in a single store. The UI dispatches actions, which are plain objects describing what happened, like { type: 'cart/added', payload }. Reducers are pure functions that take the current state and an action and return new state. Components read state with selectors. This strict one-way flow makes state changes predictable, traceable in DevTools and easy to test.
78

How do you set up a Redux store and use it in components?

Save to ▾
Show answer
Use configureStore, wrap the app with Provider and use hooks. const store = configureStore({ reducer: { counter: counterReducer } }); createRoot(el).render( <Provider store={store}><App /></Provider> ); function Counter() { const value = useSelector(state => state.counter.value); const dispatch = useDispatch(); return <button onClick={() => dispatch(increment())}>{value}</button>; }
79

Why must Redux reducers be pure functions?

Save to ▾
Show answer
A pure reducer returns new state based only on its inputs and has no side effects: no API calls, no random values, no mutation of arguments. This makes state changes predictable, testable and replayable, which is what enables time-travel debugging in Redux DevTools. Side effects belong in thunks, listeners or RTK Query. Redux Toolkit uses Immer, so draft mutations inside createSlice are still safe.
80

How do you debug Redux state changes?

Save to ▾
Show answer
Install the Redux DevTools browser extension; configureStore enables it automatically in development. You can see every dispatched action, the state before and after, the diff, and jump back in time to earlier states. Check whether the expected action was dispatched, whether its payload is correct and whether the reducer updated the right slice. For selectors, log their output or use the React DevTools profiler.
81

What is the Flux architecture?

Save to ▾
Show answer
Flux is the unidirectional data flow pattern that inspired Redux. Actions describe events, a dispatcher sends them to stores, stores update data and notify views, and views render and trigger new actions. Data never flows backward directly. Redux simplified Flux into a single store with pure reducers. Understanding Flux explains why React state management favours one-way flow over two-way binding.
82

What is the main performance pitfall of React Context and how do you avoid it?

Save to ▾
Show answer
Every component that reads a context re-renders when the provider value changes. If you pass a new object like value={{ user, setUser }} on each render, all consumers re-render even if nothing changed. Memoise the value with useMemo, split one big context into smaller ones (for example state and dispatch separately), and keep fast-changing data in a dedicated store like Zustand that supports selectors.
83

Create a Redux Toolkit slice for a counter.

Save to ▾
Show answer
createSlice generates action creators and the reducer. Immer lets you write mutating syntax safely. import { createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: state => { state.value += 1; }, addBy: (state, action) => { state.value += action.payload; } } }); export const { increment, addBy } = counterSlice.actions; export default counterSlice.reducer;
84

How do you handle async API calls with createAsyncThunk?

Save to ▾
Show answer
createAsyncThunk creates pending, fulfilled and rejected actions around an async function, and you handle them in extraReducers. export const fetchOrders = createAsyncThunk('orders/fetch', async () => { const res = await fetch('/api/orders'); return res.json(); }); extraReducers: builder => { builder .addCase(fetchOrders.pending, s => { s.status = 'loading'; }) .addCase(fetchOrders.fulfilled, (s, a) => { s.status = 'idle'; s.list = a.payload; }) .addCase(fetchOrders.rejected, (s, a) => { s.status = 'failed'; s.error = a.error.message; }); }
85

What is RTK Query?

Save to ▾
Show answer
RTK Query is the data fetching and caching tool included in Redux Toolkit. You define an API with createApi and endpoints, and it auto-generates hooks like useGetProductsQuery and useAddProductMutation. It handles loading states, caching, deduplicating requests, refetching and cache invalidation through tags. It removes most hand-written thunks and reducers for server data in Redux-based apps.
86

What is the difference between server state and client state?

Save to ▾
Show answer
Client state is owned by the browser, like whether a modal is open, form input or theme. Server state lives on a backend and is only cached on the client, like products or orders; it can become stale, be changed by other users and needs refetching. Tools like TanStack Query or RTK Query manage server state, while useState, Context or Zustand handle client state.
87

Show how to fetch data with TanStack Query.

Save to ▾
Show answer
TanStack Query caches by query key and handles loading, errors, retries and background refetching. const queryClient = new QueryClient(); // wrap app: <QueryClientProvider client={queryClient}> function Orders({ userId }) { const { data, isPending, error } = useQuery({ queryKey: ['orders', userId], queryFn: () => fetch(`/api/users/${userId}/orders`).then(r => r.json()), staleTime: 60_000 }); if (isPending) return <Spinner />; if (error) return <p>Error</p>; return <OrderList orders={data} />; }
88

What is Zustand and how do you use it?

Save to ▾
Show answer
Zustand is a small state library with a hook-based API and no Provider. import { create } from 'zustand'; const useCart = create(set => ({ items: [], add: item => set(s => ({ items: [...s.items, item] })), clear: () => set({ items: [] }) })); const count = useCart(s => s.items.length); Components subscribe with selectors, so they re-render only when the selected slice changes.
89

A new mid-sized dashboard project is starting. How would you decide between Context, Redux Toolkit and Zustand?

Save to ▾
Show answer
First separate server state, which I would handle with TanStack Query or RTK Query. For remaining client state, local useState covers most needs. Context suits rarely changing values like theme or auth. If there is complex shared state with many actions, strict patterns, large teams and need for DevTools time travel, Redux Toolkit fits. For simpler shared state with less boilerplate, Zustand is a good choice.
90

Five components on one page each fetch the same user profile, causing duplicate API calls. How would you fix this?

Save to ▾
Show answer
Lift the data fetching into a shared cache instead of each component fetching on its own. With TanStack Query or RTK Query, all components using the same query key share one request and one cached result, and get updates together. Alternatively, fetch once in a parent or route loader and pass data down. This also removes inconsistent loading spinners across the page.
91

How do you persist part of your state, like the cart, across page reloads?

Save to ▾
Show answer
Save it to localStorage and read it on startup. With Zustand, the persist middleware does this. import { persist } from 'zustand/middleware'; const useCart = create(persist( set => ({ items: [], add: i => set(s => ({ items: [...s.items, i] })) }), { name: 'cart-storage' } )); With Redux, use redux-persist or a store.subscribe that writes a throttled snapshot. Never store secrets like tokens in localStorage.
92

Where should you store the logged-in user's auth token in a React app?

Save to ▾
Show answer
The safest common choice is an httpOnly, Secure, SameSite cookie set by the server, because JavaScript cannot read it, which protects it from XSS theft. Keep only non-sensitive user info, such as name and role, in React state or context. If you must use tokens in JavaScript, keep the access token in memory, use short expiry and refresh tokens via cookies. Avoid localStorage for tokens.
93

What is atomic state management, as in Jotai or Recoil-style libraries?

Save to ▾
Show answer
Atomic state splits state into small independent units called atoms. Components subscribe to only the atoms they use, and derived atoms compute values from others, similar to a spreadsheet. This gives fine-grained re-renders without selectors or a big central store. Jotai is the popular option today; Recoil is no longer maintained. It suits apps with many independent pieces of interactive state.
94

Tell me about a time you pushed back on adding a new library to the project.

Save to ▾
Show answer
Situation: a teammate proposed adding Redux to a small admin app. Task: decide whether it was worth the added complexity. Action: I listed our actual shared state, which was just the user and a few filters, and showed a prototype using TanStack Query for API data and one small context. Result: we shipped faster with less code, and agreed to revisit if requirements grew.
95

What is Redux middleware?

Save to ▾
Show answer
Middleware sits between dispatching an action and the reducer, letting you intercept actions for side effects. Signature: store => next => action => {...}. Common uses are async logic (redux-thunk, included by default in Redux Toolkit), logging, analytics, error reporting and the RTK Query cache middleware. Redux Toolkit also provides listenerMiddleware for reacting to actions, a lighter alternative to redux-saga for most cases.
96

Why normalise state in Redux and what does createEntityAdapter do?

Save to ▾
Show answer
Normalising means storing items in a lookup like { ids: [...], entities: { id: item } } instead of nested arrays. Each item exists once, updates are O(1) and you avoid duplicated data getting out of sync. createEntityAdapter in Redux Toolkit generates this structure plus reducers like addOne, upsertMany and removeOne, and memoised selectors such as selectAll and selectById.
97

What are memoised selectors and why use createSelector?

Save to ▾
Show answer
A selector reads or derives data from the store. If a selector returns a new array each time, such as state.todos.filter(t => t.done), useSelector sees a new reference and re-renders on every store update. createSelector from Reselect, included in Redux Toolkit, caches the result and recomputes only when its input selectors return changed values, avoiding wasted renders and repeated expensive calculations.
98

After adding an AuthContext at the root, profiling shows the whole app re-rendering every few seconds. What would you check?

Save to ▾
Show answer
Check what the provider value is and what updates it. Likely the value is a new object each render, or it includes fast-changing data such as a token refresh timer or a clock. Memoise the value with useMemo, move frequently changing data out of the context, and split it into separate contexts, so components reading only the user do not re-render when unrelated fields change.
99

How would you implement an optimistic update with TanStack Query and roll back on failure?

Save to ▾
Show answer
In useMutation, use onMutate to cancel ongoing queries, save the previous cache data and update the cache with the expected result. In onError, restore the saved snapshot and show an error toast. In onSettled, invalidate the query so the cache syncs with the server. This makes actions like toggling a favourite feel instant while keeping data correct if the server rejects the change.
100

You inherit an old Redux codebase with connect, hand-written action types and switch reducers. How would you modernise it?

Save to ▾
Show answer
I would migrate gradually, not in one big rewrite. First replace createStore with configureStore, which keeps old reducers working. Then convert one feature at a time to createSlice, switch components from connect to useSelector and useDispatch, and move data fetching to RTK Query. Add tests around each feature before migrating, and remove dead actions. Each step ships independently and reduces risk.
101

What is client-side routing and how does React Router provide it?

Save to ▾
Show answer
In client-side routing, the browser loads one HTML page and JavaScript swaps components when the URL changes, without a full page reload. React Router uses the History API to listen to URL changes, matches the path against your route definitions and renders the matching component. Navigation feels instant, state can be kept between pages and only data needs to be fetched from the server.
102

Show a basic React Router setup with a home page, a product page and a 404 page.

Save to ▾
Show answer
In React Router v7 (library mode) you can use declarative routes. import { BrowserRouter, Routes, Route } from 'react-router'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/products/:id" element={<Product />} /> <Route path="*" element={<NotFound />} /> </Routes> </BrowserRouter> ); } The * path catches any unmatched URL.
103

How do you read a dynamic URL parameter like a product id?

Save to ▾
Show answer
Define the segment with a colon and read it with useParams. // route: <Route path="/products/:id" element={<Product />} /> import { useParams } from 'react-router'; function Product() { const { id } = useParams(); const { data } = useQuery({ queryKey: ['product', id], queryFn: () => getProduct(id) }); return <h1>{data?.name}</h1>; } Params are always strings, so convert with Number(id) if needed.
104

How do you navigate programmatically after a form submits?

Save to ▾
Show answer
Use the useNavigate hook. import { useNavigate } from 'react-router'; function CheckoutForm() { const navigate = useNavigate(); async function handleSubmit(e) { e.preventDefault(); const order = await placeOrder(); navigate(`/orders/${order.id}`, { replace: true }); } return <form onSubmit={handleSubmit}>...</form>; } replace: true stops the user from going back to the submitted form; navigate(-1) goes back.
105

Why use Link instead of a normal anchor tag in a React app?

Save to ▾
Show answer
A normal <a href> causes a full page reload, which throws away all React state and re-downloads the app. <Link to="/cart"> intercepts the click, updates the URL with the History API and lets the router render the new route instantly. It still renders a real anchor, so accessibility, middle-click and right-click open in new tab work. NavLink adds active styling for menus.
106

How do you read and update query parameters like ?page=2&sort=price?

Save to ▾
Show answer
Use useSearchParams, which works like useState for the query string. import { useSearchParams } from 'react-router'; function ProductList() { const [params, setParams] = useSearchParams(); const page = Number(params.get('page') ?? 1); const sort = params.get('sort') ?? 'popular'; const next = () => setParams({ page: String(page + 1), sort }); return <Pagination page={page} onNext={next} />; } Keeping filters in the URL makes them shareable and bookmarkable.
107

What is the difference between BrowserRouter and HashRouter?

Save to ▾
Show answer
BrowserRouter uses clean URLs like /products/5 with the HTML5 History API, but the server must be configured to serve index.html for every route. HashRouter puts the route after a hash, like /#/products/5; the server never sees the hash part, so it works on any static host without configuration. BrowserRouter is preferred for SEO and clean URLs; HashRouter suits simple static hosting or embedded apps.
108

How do you handle a form with multiple controlled inputs using one change handler?

Save to ▾
Show answer
Use the input's name attribute to update the right field. function SignupForm() { const [form, setForm] = useState({ name: '', email: '', city: '' }); const handleChange = e => { const { name, value } = e.target; setForm(f => ({ ...f, [name]: value })); }; const handleSubmit = e => { e.preventDefault(); console.log(form); }; return ( <form onSubmit={handleSubmit}> <input name="name" value={form.name} onChange={handleChange} /> <input name="email" value={form.email} onChange={handleChange} /> <button>Submit</button> </form> ); }
109

What are the common approaches to form validation in React?

Save to ▾
Show answer
You can validate manually in onChange or onSubmit and store errors in state, use HTML attributes like required and pattern for basic checks, or use a form library such as React Hook Form with a schema library like Zod or Yup. Schema validation keeps rules in one place and can be shared with the backend in TypeScript. Always validate again on the server, because client checks can be bypassed.
110

What are nested routes and what is the role of Outlet?

Save to ▾
Show answer
Nested routes let a parent route render a shared layout, like a dashboard sidebar, while child routes render inside it. The parent component places <Outlet /> where the matching child should appear. For example, /dashboard renders DashboardLayout, and /dashboard/orders renders Orders inside its Outlet. This keeps layouts consistent, avoids repeating headers and lets each section load its own data.
111

How do you create a protected route that redirects users who are not logged in?

Save to ▾
Show answer
Create a wrapper that checks auth and either renders the child routes or redirects. import { Navigate, Outlet, useLocation } from 'react-router'; function RequireAuth() { const { user } = useAuth(); const location = useLocation(); if (!user) return <Navigate to="/login" replace state={{ from: location }} />; return <Outlet />; } <Route element={<RequireAuth />}> <Route path="/account" element={<Account />} /> </Route> The server must still enforce authorisation.
112

What are loaders and actions in React Router?

Save to ▾
Show answer
In data or framework mode, a route can define a loader that fetches data before the route renders, and an action that handles form submissions or mutations for that route. Components read data with useLoaderData. After an action runs, the router automatically revalidates loaders so the UI shows fresh data. This moves data fetching out of effects and avoids request waterfalls between parent and child components.
113

How do you lazy load route components to reduce the initial bundle?

Save to ▾
Show answer
Use React.lazy with dynamic import and wrap routes in Suspense, so each page becomes a separate chunk downloaded only when visited. In React Router data mode you can also use the route's lazy property to load the component and loader together. This greatly reduces the first load size for big apps like admin panels. Show a lightweight fallback, such as a skeleton, while chunks load.
114

Your React app works locally, but after deployment refreshing /dashboard gives a 404 from the server. Why, and how do you fix it?

Save to ▾
Show answer
The server looks for a real file at /dashboard, which does not exist because routing happens in the browser. Configure the server to return index.html for all unknown paths: a rewrite rule in Nginx (try_files $uri /index.html), a _redirects or rewrites setting on static hosts, or a fallback in Express. Alternatively, use a framework with server routing. HashRouter also avoids it but gives ugly URLs.
115

Why is React Hook Form popular?

Save to ▾
Show answer
React Hook Form registers inputs as uncontrolled by default and reads values through refs, so typing does not re-render the whole form. This makes large forms fast. It provides validation, error messages, field arrays for dynamic rows, and integrates with Zod or Yup through resolvers. It has a small bundle and works with UI libraries through a Controller component for custom controlled inputs.
116

Show a login form using React Hook Form with Zod validation.

Save to ▾
Show answer
Define a schema and pass it through zodResolver. const schema = z.object({ email: z.string().email('Invalid email'), password: z.string().min(8, 'Min 8 characters') }); function Login() { const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm({ resolver: zodResolver(schema) }); return ( <form onSubmit={handleSubmit(data => login(data))}> <input {...register('email')} /> {errors.email && <p>{errors.email.message}</p>} <input type="password" {...register('password')} /> <button disabled={isSubmitting}>Login</button> </form> ); }
117

How do form Actions work in React 19?

Save to ▾
Show answer
In React 19 you can pass a function to a form's action prop: <form action={saveAddress}>. React calls it with the FormData when the form submits, runs it inside a transition, tracks pending state and resets uncontrolled fields after success. Combined with useActionState for results and useFormStatus for button state, this removes manual onSubmit, preventDefault and loading flags. In Next.js the action can be a Server Function.
118

You are building a 4-step onboarding wizard. How do you keep data when users move back and forth between steps?

Save to ▾
Show answer
Store the wizard data in a parent component, a reducer, or a small store, not inside each step, because step components unmount when hidden. Each step receives its slice and an update callback. Validate each step before moving forward, and optionally save drafts to sessionStorage or the server so a refresh does not lose progress. The current step can also live in the URL for back-button support.
119

How do you upload a file with a preview in React?

Save to ▾
Show answer
Use a file input, create a preview URL and send FormData. function AvatarUpload() { const [file, setFile] = useState(null); const preview = useMemo(() => file && URL.createObjectURL(file), [file]); useEffect(() => () => preview && URL.revokeObjectURL(preview), [preview]); async function upload() { const fd = new FormData(); fd.append('avatar', file); await fetch('/api/avatar', { method: 'POST', body: fd }); } return (<> <input type="file" accept="image/*" onChange={e => setFile(e.target.files[0])} /> {preview && <img src={preview} alt="preview" />} <button onClick={upload}>Upload</button> </>); }
120

An accessibility audit says your signup form fails screen reader checks. What would you fix to make the form accessible?

Save to ▾
Show answer
Link every input to a visible label using htmlFor and id (useId helps), use correct input types, and mark required fields. Show errors as text, connect them with aria-describedby and set aria-invalid on failing fields. Move focus to the first error on submit, keep everything keyboard operable and do not rely on colour alone. Use native button and form elements instead of clickable divs.
121

Tell me about a time a requirement changed late in a sprint. How did you handle it?

Save to ▾
Show answer
Situation: two days before release, the product owner asked to add a GST number field with validation to our checkout form. Task: deliver it without risking the release. Action: I estimated the impact, proposed shipping the field with basic format validation first and the full verification API in the next sprint, and added tests. Result: we released on time and the follow-up shipped a week later.
122

How would you explain to a non-technical manager why our marketing pages need server rendering?

Save to ▾
Show answer
I would keep it simple: a pure client-side React page sends an almost empty HTML file, so some crawlers and social previews see little content and users on slow phones see a blank screen longer. Server rendering sends ready HTML, improving SEO and first load. I would back this with a Lighthouse comparison and search console data, and suggest a framework like Next.js only for pages that need it.
123

Describe a time you found and fixed a bug reported by a real user.

Save to ▾
Show answer
Situation: customers reported that the address form sometimes submitted an empty PIN code. Task: find the root cause quickly. Action: I reproduced it with browser autofill, which changed the DOM value without firing our onChange in a custom input. I switched to a native controlled input, added a schema check before submit and wrote a regression test. Result: the issue stopped and support tickets dropped.
124

A 60-field insurance form becomes laggy while typing because every keystroke re-renders the whole form. How would you fix it?

Save to ▾
Show answer
The state for all fields probably lives in one top-level useState, so each change re-renders every input. Options: switch to React Hook Form so inputs are uncontrolled and only error messages re-render, split the form into memoised sections that own their own state, and debounce expensive validation or derived calculations. Profile first with React DevTools to confirm which components take the most time.
125

Users lose their typed data when they accidentally click another menu link. How would you warn them about unsaved changes?

Save to ▾
Show answer
Track a dirty flag, for example formState.isDirty from React Hook Form. For in-app navigation, use React Router's useBlocker to block the transition and show a confirm dialog. For tab close or refresh, add a beforeunload listener while the form is dirty, and remove it in the effect cleanup. Also consider autosaving drafts, which is often a better user experience than blocking.
126

What does React.memo do?

Save to ▾
Show answer
React.memo wraps a component so React skips re-rendering it 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, like rows in a big table. It only works if props stay referentially stable, so objects and callbacks passed to it are usually memoised with useMemo and useCallback.
127

How do you implement code splitting with React.lazy and Suspense?

Save to ▾
Show answer
Load a component only when it is needed with a dynamic import. import { lazy, Suspense } from 'react'; const Reports = lazy(() => import('./Reports')); function App() { return ( <Suspense fallback={<Spinner />}> {showReports && <Reports />} </Suspense> ); } The bundler creates a separate chunk for Reports, reducing the initial JavaScript download.
128

How do you optimise images in a React app?

Save to ▾
Show answer
Serve modern formats like WebP or AVIF, resize images to their display size and use srcset with sizes for responsive images. Add loading="lazy" for images below the fold and fetchpriority="high" for the main hero image. Always set width and height or aspect-ratio to prevent layout shift. In Next.js, the next/image component automates resizing, formats and lazy loading.
129

A developer says the app is too slow, based on testing it with the development server. What do you tell them?

Save to ▾
Show answer
The development build includes extra warnings, StrictMode double rendering, checks and unminified code, so it is much slower and can mislead you. Production builds created with npm run build are minified, tree-shaken and optimised. Test performance on the production build, ideally on a mid-range Android phone with throttled network, because many Indian users browse on such devices and slower connections.
130

Tell me about a mistake you made that reached production and what you learned.

Save to ▾
Show answer
Situation: I removed what looked like an unused prop in a shared Button component. Task: after release, the payment page's disabled state broke. Action: I owned it immediately, rolled back, then fixed it and added a test plus a TypeScript type so the prop could not be removed silently. Result: the issue was live for under an hour, and I now search all usages and rely on types before deleting code.
131

What is the React Compiler?

Save to ▾
Show answer
The React Compiler, released as stable version 1.0 in late 2025, is a build-time tool (Babel plugin, also integrated in Vite and Next.js setups) that automatically memoises components and values. It analyses your code and inserts caching similar to useMemo, useCallback and React.memo, so developers write plain code. It requires following the rules of React, such as pure rendering, and can be adopted gradually per directory.
132

How do you find what is making a React page slow?

Save to ▾
Show answer
Use the React DevTools Profiler: record an interaction, then check the flame chart for components with long render times and the reason each one re-rendered (enable 'record why each component rendered'). Pair it with the Chrome Performance panel for long tasks, layout and network. Enable highlight updates to spot unnecessary renders. Measure first, fix the biggest cost, then measure again in a production build.
133

What is list virtualisation?

Save to ▾
Show answer
Virtualisation, or windowing, renders only the rows visible in the viewport plus a small buffer, instead of thousands of DOM nodes. As the user scrolls, rows are recycled with new data. Libraries such as TanStack Virtual and react-window implement it. It dramatically cuts render time and memory for long lists, chat histories and data grids, but needs care with variable row heights and browser find-in-page.
134

An orders table renders 10,000 rows and the page freezes on load and scroll. What would you do?

Save to ▾
Show answer
First question whether users need all rows at once: server-side pagination or infinite scroll with cursor-based loading may solve it. If a long scrollable list is required, virtualise it with TanStack Virtual so only around 30 rows exist in the DOM. Also memoise row components, avoid heavy formatting in render by precomputing, and move sorting or filtering off the main thread if it is expensive.
135

You wrapped a row component in React.memo, but the profiler shows it still re-renders every time. The parent passes onClick={() => remove(id)}. Why?

Save to ▾
Show answer
An inline function like onClick={() => remove(id)} creates a new function object on every render. React.memo compares props by reference, sees a different function and re-renders the child every time, so memo has no effect. Wrap the handler with useCallback and correct dependencies, or let the React Compiler handle it. If the child is not memoised, inline functions are fine and cheap.
136

How do you analyse and reduce JavaScript bundle size?

Save to ▾
Show answer
Generate a visual report with rollup-plugin-visualizer in Vite or @next/bundle-analyzer in Next.js. Look for large dependencies, duplicate packages and code that loads on every page. Fixes include importing only what you need, replacing heavy libraries such as moment with date-fns or dayjs, lazy loading routes and rarely used components, and checking that libraries support tree shaking. Track size in CI to prevent regressions.
137

What are Core Web Vitals and how do React apps affect them?

Save to ▾
Show answer
Core Web Vitals are Google's user experience metrics: LCP (Largest Contentful Paint, loading, target under 2.5s), INP (Interaction to Next Paint, responsiveness, under 200ms, which replaced FID in 2024) and CLS (Cumulative Layout Shift, visual stability, under 0.1). Large React bundles hurt LCP and INP, heavy renders on clicks hurt INP, and images or content without reserved space hurt CLS. SSR, code splitting and transitions help.
138

What is tree shaking?

Save to ▾
Show answer
Tree shaking is dead code elimination done by bundlers like Rollup (used by Vite), esbuild and webpack. They analyse ES module import and export statements and drop exports that are never used. It works only with static ESM syntax, not CommonJS require, and can be blocked by modules with side effects. Importing import { debounce } from 'lodash-es' instead of the whole lodash library keeps the bundle small.
139

A developer writes key={Math.random()} to silence the missing key warning. What problem does this create?

Save to ▾
Show answer
A new random key on every render tells React each item is brand new, so it unmounts and remounts every row each time. This destroys component state such as typed input and focus, re-runs effects and is very slow for large lists. Keys must be stable and unique, ideally an id from the data. If items have no id, generate ids once when the data is created.
140

Tell me about a time you improved the performance of an application.

Save to ▾
Show answer
Situation: our admin dashboard took about eight seconds to become usable on office laptops. Task: bring it under three seconds. Action: I profiled it, found a 2 MB bundle and a chart library loaded on every page, lazy loaded routes and charts, replaced moment with dayjs and virtualised a large table. Result: load time dropped to around 2.5 seconds and support complaints about slowness stopped.
141

How do you handle a tight deadline when you know the code is not perfect?

Save to ▾
Show answer
Situation: a festive sale banner feature had to go live in two days. Task: ship safely without gold-plating. Action: I listed must-haves with the product owner, wrote tests for the critical checkout path, kept a simple implementation and logged clear tech-debt tickets for refactoring. Result: we launched on time with no incidents, and I cleaned up the code in the next sprint as planned.
142

Typing in a search box feels laggy because a big product list is filtered on every keystroke. How do you fix it?

Save to ▾
Show answer
Keep the input state urgent and make the expensive part deferred. Use const deferredQuery = useDeferredValue(query) and filter with deferredQuery inside useMemo, and wrap the list in React.memo. The input updates instantly while React renders the list in the background and can interrupt it. If filtering is still heavy, debounce it, move it to a Web Worker or filter on the server.
143

A teammate wraps every function in useCallback and every value in useMemo for performance. When should you not memoise, and what feedback would you give?

Save to ▾
Show answer
Memoisation has costs: extra memory, comparisons on every render and more complex code. Skip it for cheap calculations, components that rarely re-render, and props that change every render anyway. Memoising everything by default also hides design problems like state placed too high. Use the profiler to find real bottlenecks first. With the React Compiler, manual memoisation is mostly needed only as an escape hatch.
144

Without using memo, what structural techniques reduce unnecessary re-renders?

Save to ▾
Show answer
Move state down into the smallest component that needs it, so changes do not re-render siblings. Lift content up by passing expensive parts as children: a component that changes state does not re-render JSX it receives as children, because that JSX was created by the parent. Split large components, and avoid putting fast-changing values in widely used context. These often fix performance more cleanly than memoisation.
145

After navigating between pages for a while, the app's memory keeps growing and it slows down. How do you investigate a memory leak?

Save to ▾
Show answer
Take heap snapshots in Chrome DevTools Memory panel before and after repeated navigation and compare retained objects, especially detached DOM nodes. Common React causes are effects without cleanup: intervals, event listeners on window, WebSocket subscriptions and third-party chart instances not destroyed. Also check global caches growing without limits. Add cleanups in useEffect returns and verify the heap stabilises.
146

When would you use a Web Worker in a React application?

Save to ▾
Show answer
Use a Web Worker for CPU-heavy work that would block the main thread, such as parsing a large CSV, image processing, complex calculations or searching big datasets in the browser. The worker runs in a separate thread and communicates through postMessage, so the UI stays responsive. Libraries like Comlink simplify the messaging. Workers cannot touch the DOM, so results are sent back and set in state.
147

How do Suspense and streaming server rendering improve performance?

Save to ▾
Show answer
With streaming SSR, the server sends HTML in chunks: the page shell is sent immediately and slower sections wrapped in Suspense are streamed later as their data resolves, replacing the fallback. Users see content sooner and hydration of parts can happen selectively, prioritising what the user interacts with. Frameworks like Next.js App Router use this with server components and loading.js boundaries.
148

What resource preloading APIs did React 19 add?

Save to ▾
Show answer
React 19 added functions in react-dom such as preload, preinit, prefetchDNS and preconnect. They tell the browser to load fonts, stylesheets, scripts or connect to API origins early, and React places the hints in the document head, including during server rendering. React 19 also supports rendering <title>, <meta> and <link> tags inside components, hoisting them to the head automatically.
149

Field data shows poor INP on the 'Add to cart' button of a product page. How do you improve it?

Save to ▾
Show answer
Profile the click to see what runs. Typical problems are a large synchronous re-render of the whole page, heavy analytics code and expensive state updates in the handler. Update the button feedback first and wrap the non-urgent part (cart drawer, recommendations) in startTransition, defer analytics with setTimeout or requestIdleCallback, narrow which components subscribe to cart state and break up long tasks.
150

After a release, the Lighthouse performance score of the home page dropped from 90 to 60. How do you find and fix the cause?

Save to ▾
Show answer
Compare the two builds instead of guessing. Run Lighthouse and WebPageTest on both versions, check which metric dropped (LCP, TBT or CLS), and diff bundle analyser reports to spot new heavy dependencies. Review the release changes: a new third-party script, an unoptimised hero image or a component moved from server to client are common causes. Fix it, then add a performance budget check in CI to prevent repeats.
151

What kinds of tests are written for a React application?

Save to ▾
Show answer
Unit tests check small pieces like utility functions, reducers and custom hooks. Component or integration tests render components with their children and check behaviour the user sees, usually with React Testing Library and Vitest or Jest. End-to-end tests run the full app in a real browser with Playwright or Cypress, covering flows like login and checkout. Static checks with TypeScript and ESLint catch many bugs before tests run.
152

What is the guiding philosophy of React Testing Library?

Save to ▾
Show answer
React Testing Library encourages testing components the way users use them, not their internal implementation. You find elements by role, label or text, interact with them through user events and assert what appears on screen. You avoid checking state variables or component instances. Its motto is that the more your tests resemble the way your software is used, the more confidence they give you, and refactors do not break them.
153

Jest or Vitest: what is the difference for React projects?

Save to ▾
Show answer
Both are test runners with a similar API (describe, it, expect, mocks). Jest is the long-established choice and still common in older projects. Vitest is built on Vite, reuses the same config and transforms, supports ESM and TypeScript natively and is much faster in watch mode, so it is the default for new Vite-based React apps. React Testing Library works with either.
154

Write a test for a counter component that increments on click.

Save to ▾
Show answer
Use React Testing Library with user-event. import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import Counter from './Counter'; test('increments count', async () => { const user = userEvent.setup(); render(<Counter />); await user.click(screen.getByRole('button', { name: '+' })); expect(screen.getByRole('heading')).toHaveTextContent('1'); }); toHaveTextContent comes from @testing-library/jest-dom.
155

What is the difference between getBy, queryBy and findBy queries?

Save to ▾
Show answer
getBy returns the element or throws immediately if it is missing, so use it when the element should exist. queryBy returns null instead of throwing, which is the right choice to assert something is not present: expect(screen.queryByText('Error')).not.toBeInTheDocument(). findBy returns a promise and retries until the element appears or times out, used for content that appears after async work. Each has an AllBy variant for multiple elements.
156

How do you use React DevTools for debugging?

Save to ▾
Show answer
The Components tab shows the component tree; selecting one shows its props, state, hooks and context values, which you can edit live to test behaviour. You can find which component rendered a DOM node, view the owner chain and jump to source. The Profiler tab records renders and shows why each component re-rendered. Combined with browser breakpoints and console logs, it speeds up most UI debugging.
157

How do you respond when a senior developer leaves many comments on your pull request?

Save to ▾
Show answer
Situation: my first big PR received over twenty review comments. Task: address them and learn, not feel defensive. Action: I thanked the reviewer, fixed clear issues, asked questions on ones I did not understand and explained my reasoning politely on two where I had context. Result: the PR merged after one more round, and I created a personal checklist that reduced comments on later PRs.
158

A QA engineer raises a bug you believe is not a bug. How do you handle it?

Save to ▾
Show answer
Situation: QA reported that a filter reset on page refresh. Task: resolve it without friction. Action: I reproduced it, checked the acceptance criteria with QA and the product owner, and found the requirement was unclear rather than either of us being wrong. Result: we agreed to store filters in the URL, I implemented it in a day, and we added clearer criteria to future stories.
159

Which queries should you prefer in React Testing Library and why?

Save to ▾
Show answer
Prefer queries accessible to everyone: getByRole (with the name option) first, then getByLabelText for form fields, getByPlaceholderText, getByText and getByDisplayValue. Use getByAltText and getByTitle for images and titles. getByTestId is a last resort when nothing else works. Role-based queries also check accessibility, because if a button cannot be found by role and name, screen reader users will struggle too.
160

Why is user-event preferred over fireEvent?

Save to ▾
Show answer
fireEvent dispatches a single DOM event, such as one change event. user-event simulates full user interactions: typing fires keydown, keypress, input and keyup for every character, clicking includes pointer and focus events, and it respects disabled elements and visibility. This finds bugs that fireEvent misses. In current versions, call userEvent.setup() and await each interaction because they are asynchronous.
161

How do you test a component that fetches data from an API?

Save to ▾
Show answer
Mock the network, not fetch itself, using Mock Service Worker (MSW), then wait for the UI. const server = setupServer( http.get('/api/users', () => HttpResponse.json([{ id: 1, name: 'Asha' }])) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); test('shows users', async () => { render(<Users />); expect(await screen.findByText('Asha')).toBeInTheDocument(); });
162

How do you mock a module in Vitest?

Save to ▾
Show answer
Use vi.mock with a factory, then control return values per test. import { vi } from 'vitest'; import { getProfile } from './api'; vi.mock('./api', () => ({ getProfile: vi.fn() })); test('shows name', async () => { getProfile.mockResolvedValue({ name: 'Ravi' }); render(<Profile />); expect(await screen.findByText('Ravi')).toBeInTheDocument(); }); In Jest, the same pattern uses jest.mock and jest.fn.
163

How do you test a custom hook?

Save to ▾
Show answer
Use renderHook from React Testing Library and wrap state changes in act. import { renderHook, act } from '@testing-library/react'; import { useCounter } from './useCounter'; test('increments', () => { const { result } = renderHook(() => useCounter(5)); act(() => result.current.increment()); expect(result.current.count).toBe(6); }); If the hook needs context, pass a wrapper option with the provider.
164

Your team has hundreds of snapshot tests that developers update blindly whenever they fail. What are the drawbacks of snapshot tests and what would you suggest?

Save to ▾
Show answer
A snapshot test saves the rendered output to a file and fails when future output differs. It is quick to write and catches unexpected changes. Drawbacks: large snapshots are hard to review, developers often blindly update them, and they fail on harmless markup changes while saying nothing about behaviour. Use small, focused inline snapshots for stable output, and prefer behaviour assertions for most component tests.
165

When would you add end-to-end tests with Playwright or Cypress?

Save to ▾
Show answer
Add E2E tests for critical business flows that cross many components and the backend, such as signup, login, search, add to cart and payment. They run in real browsers and catch integration issues unit tests miss. They are slower and more brittle, so keep them few and focused, use stable selectors like roles or data-testid, seed test data and run them in CI on every pull request.
166

All unit tests passed, but users found that the delete button did nothing. The tests were checking that a handleDelete function was called. What went wrong?

Save to ▾
Show answer
The tests checked implementation details instead of user-visible behaviour. A mocked handler being called says nothing about whether the item actually disappears or the API is hit. Rewrite the test to click the button by role, mock the API with MSW and assert the item is removed from the screen. Behaviour-focused tests survive refactoring and catch real bugs like a broken wiring.
167

How do you include accessibility checks in your React tests?

Save to ▾
Show answer
Use jest-axe or vitest-axe to run axe-core on rendered components. import { axe } from 'vitest-axe'; test('form has no a11y violations', async () => { const { container } = render(<SignupForm />); expect(await axe(container)).toHaveNoViolations(); }); Also query by role and label in tests, run Lighthouse or axe DevTools in the browser, and test keyboard navigation manually, since automated tools catch only part of the issues.
168

How did you bring better testing practices to a team that had very few tests?

Save to ▾
Show answer
Situation: our React app had almost no tests and regressions reached production every release. Task: improve quality without slowing delivery. Action: I set up Vitest, React Testing Library and MSW, wrote example tests for two key screens, ran a short session for the team and added a rule that bug fixes include a test. Result: within three months, critical flows were covered and regressions dropped noticeably.
169

Tell me about a time you had to learn a new tool or library quickly.

Save to ▾
Show answer
Situation: our project needed to switch from Jest to Vitest with a week's notice. Task: migrate around 300 tests. Action: I read the official migration guide, migrated one folder first to discover patterns, wrote a codemod for jest.fn to vi.fn replacements and documented gotchas for the team. Result: we finished in four days, test runs became much faster, and the guide helped others with later work.
170

How do you test a component that depends on Redux and React Router?

Save to ▾
Show answer
Create a custom render helper that wraps the UI with real providers. function renderWithProviders(ui, { route = '/', preloadedState } = {}) { const store = configureStore({ reducer: rootReducer, preloadedState }); return render( <Provider store={store}> <MemoryRouter initialEntries={[route]}>{ui}</MemoryRouter> </Provider> ); } Using a real store with preloaded state is better than mocking useSelector, because it tests actual behaviour.
171

Your tests pass but print 'An update to Component inside a test was not wrapped in act(...)'. What does it mean and how do you fix it?

Save to ▾
Show answer
It means state changed after the test finished checking, usually because an async operation like a fetch or timer resolved later. The test may not be checking the final UI. Fix it by awaiting the result: use findBy queries or waitFor for the expected content, await user-event calls, and use fake timers with act when testing timeouts. Do not just wrap random code in act to hide the warning.
172

In a Next.js app you see a hydration mismatch error. How do you debug it?

Save to ▾
Show answer
It means the HTML rendered on the server differs from the first client render. Common causes: using Date.now(), Math.random() or locale formatting in render, reading window or localStorage during render, browser extensions changing the DOM, and invalid HTML nesting like a div inside a p. Read the diff in the error, render client-only values inside useEffect, use useId for ids and fix invalid markup.
173

A test in CI fails randomly about one time in ten. How do you handle a flaky test?

Save to ▾
Show answer
First reproduce it by running the test repeatedly and in random order. Common causes are shared state between tests, missing awaits, real timers or dates, network calls not mocked and tests depending on execution order. Fix the root cause: reset mocks and stores in afterEach, use findBy or waitFor instead of fixed sleeps, freeze time with fake timers. Quarantine it with a ticket only temporarily, never ignore it.
174

Explain the testing pyramid and the testing trophy. Which applies to frontend?

Save to ▾
Show answer
The pyramid says write many unit tests, fewer integration tests and very few end-to-end tests, because lower tests are fast and cheap. The testing trophy, popular for frontend, adds static analysis at the base and puts the most effort in integration tests, since they give the best confidence per cost. For React, I rely on TypeScript and ESLint, many component tests, some unit tests for logic and a few E2E tests.
175

How do you track errors that happen in production React apps?

Save to ▾
Show answer
Use an error monitoring tool such as Sentry, which captures exceptions with stack traces, browser and user context. Upload source maps during the build so minified stack traces map back to your source, but do not serve them publicly. Wrap major sections in error boundaries that report errors and show friendly fallbacks. Add release tags so you can see which deployment introduced a bug.
176

What is Next.js and why would you use it instead of plain React?

Save to ▾
Show answer
Next.js is a React framework that adds file-based routing, server-side rendering, static generation, React Server Components, API endpoints, image and font optimisation and production build tooling. Plain React with Vite is a client-side library setup where you choose routing and data fetching yourself. Next.js is preferred when you need SEO, fast first load, server logic close to the UI or a full-stack app in one codebase.
177

What are the special files in the Next.js App Router?

Save to ▾
Show answer
Inside the app folder, each route segment can have page.tsx (the UI for that URL), layout.tsx (shared UI that persists across child routes), loading.tsx (Suspense fallback shown while the page loads), error.tsx (error boundary, must be a Client Component), not-found.tsx (404 UI) and route.ts (API route handler). Folders in square brackets like [slug] create dynamic segments, and folders in parentheses group routes without affecting the URL.
178

How do environment variables work in a React or Next.js app?

Save to ▾
Show answer
Values are read at build time from .env files. In Next.js, only variables prefixed with NEXT_PUBLIC_ are exposed to the browser; others stay on the server. In Vite, the prefix is VITE_ and you read import.meta.env.VITE_API_URL. Anything sent to the browser is public, so never put secrets like database passwords or private API keys in client-exposed variables. Keep .env files out of Git.
179

Why do you want to work as a React developer?

Save to ▾
Show answer
I enjoy building things people use directly, and React lets me turn designs into fast, interactive screens. During my training I built three projects with React, TypeScript and APIs, and I liked how components make code reusable. React also has strong demand across startups and service companies in India, a large community and paths into Next.js and React Native, so I see long-term growth in this role.
180

Explain CSR, SSR, SSG and ISR.

Save to ▾
Show answer
CSR (client-side rendering) sends a minimal HTML shell and renders everything in the browser. SSR (server-side rendering) generates HTML on each request, good for personalised or fast-changing pages. SSG (static site generation) builds HTML at build time, fastest for pages that rarely change like blogs. ISR (incremental static regeneration) serves static pages but regenerates them in the background after a time or on demand, mixing speed with freshness.
181

What is the difference between the App Router and the Pages Router in Next.js?

Save to ▾
Show answer
The Pages Router uses the pages directory with getServerSideProps and getStaticProps for data. The App Router, the recommended default, uses the app directory with nested layouts, React Server Components by default, streaming with loading.js, error.js boundaries and Server Functions. Data is fetched directly in async server components. Many older projects still use Pages Router, and both can coexist during migration.
182

What does the 'use client' directive do?

Save to ▾
Show answer
'use client' at the top of a file marks a boundary: that module and everything it imports become part of the client bundle and can use state, effects, event handlers and browser APIs. It does not mean the component is only rendered on the client; it is still pre-rendered to HTML on the server and then hydrated. Keep 'use client' as low in the tree as possible to send less JavaScript.
183

Show a Server Function used to handle a form in Next.js.

Save to ▾
Show answer
A function marked 'use server' runs on the server and can be passed to a form action. // app/actions.ts 'use server'; import { revalidatePath } from 'next/cache'; export async function addTodo(formData: FormData) { const title = String(formData.get('title')); await db.todo.create({ data: { title } }); revalidatePath('/todos'); } // app/todos/page.tsx <form action={addTodo}> <input name="title" required /> <button>Add</button> </form> Always validate input and check authorisation inside the function.
184

How do you fetch data in a Next.js App Router page?

Save to ▾
Show answer
Make the page an async Server Component and await data directly. // app/products/[id]/page.tsx export default async function ProductPage({ params }) { const { id } = await params; const product = await getProduct(id); if (!product) notFound(); return ( <main> <h1>{product.name}</h1> <AddToCartButton id={id} /> </main> ); } AddToCartButton is a Client Component. In recent Next.js versions params is a promise.
185

What is hydration?

Save to ▾
Show answer
Hydration is the process where React, running in the browser, attaches event handlers and state to HTML that was already rendered on the server, making it interactive. React expects the first client render to match the server HTML exactly; if not, it reports a hydration mismatch. Until hydration finishes, the page is visible but buttons may not respond, which is why reducing client JavaScript matters.
186

How do you set SEO metadata in a Next.js App Router page?

Save to ▾
Show answer
Export a metadata object or a generateMetadata function from a page or layout. export async function generateMetadata({ params }) { const { slug } = await params; const post = await getPost(slug); return { title: post.title, description: post.summary, alternates: { canonical: `/blog/${slug}` }, openGraph: { title: post.title, images: [post.cover] } }; } Next.js renders the tags in the head during server rendering.
187

Your Next.js build fails with 'ReferenceError: window is not defined'. Why, and how do you fix it?

Save to ▾
Show answer
Code that touches browser globals runs during server rendering, where window and document do not exist. This often comes from a library that accesses window at import time or from reading localStorage in render. Fix it by moving browser access into useEffect or event handlers inside a Client Component, checking typeof window !== 'undefined', or loading the library with next/dynamic and ssr: false from a client component.
188

What are the common styling options in React, and how do Server Components affect the choice?

Save to ▾
Show answer
Options include plain CSS or CSS Modules (scoped class names), Tailwind CSS utility classes, Sass, and CSS-in-JS libraries like styled-components or Emotion. Runtime CSS-in-JS needs client-side JavaScript and context, so it fits poorly with Server Components. That is why Tailwind and CSS Modules, or zero-runtime libraries, are the most common choice in modern Next.js projects. Component libraries like shadcn/ui build on Tailwind.
189

A blog feature must render HTML content that comes from a CMS. Why is dangerouslySetInnerHTML risky and how do you use it safely?

Save to ▾
Show answer
React escapes values in JSX by default, which protects against XSS. dangerouslySetInnerHTML bypasses this and inserts raw HTML, so if the content comes from users or an untrusted CMS, attackers can inject scripts. If you must render HTML, sanitise it first with a library like DOMPurify, restrict allowed tags, and add a Content Security Policy. Also never put user input into href attributes without validating the protocol.
190

During a security review you find a payment provider's secret key in the browser's JavaScript bundle. What do you do?

Save to ▾
Show answer
Treat it as leaked: rotate the key immediately in the provider dashboard and check logs for misuse. Then fix the cause, usually the secret was in a public env variable such as NEXT_PUBLIC_ or VITE_, or imported into a client component. Move the call to a server route or Server Function that uses a server-only variable, add the server-only package to guard imports, and add secret scanning in CI.
191

How do you add multiple languages to a React app?

Save to ▾
Show answer
Use an i18n library such as react-i18next or, in Next.js, next-intl. Store translations in JSON files per locale, reference keys like t('cart.title') instead of hard-coded text, and handle plurals, dates, numbers and currency with Intl APIs. Put the locale in the URL, like /hi/products, for SEO and shareable links. For Indian audiences, check fonts for Devanagari and other scripts and test longer translated text.
192

Tell me about working with a backend team when an API did not match what the frontend needed.

Save to ▾
Show answer
Situation: the orders API returned deeply nested data and no pagination, making our list screen slow. Task: get a better contract without blocking either team. Action: I shared a proposed response shape with the backend developer, explained the performance impact with numbers and built against a mocked API using MSW meanwhile. Result: they added pagination and flatter fields, and we integrated in two days with no rework.
193

What are React Server Components?

Save to ▾
Show answer
Server Components run only on the server or at build time. They can be async, read databases or files directly and send rendered output to the client without shipping their JavaScript, which reduces bundle size. They cannot use state, effects or browser APIs. Client Components, marked with 'use client', handle interactivity. Server Components can render Client Components and pass them serialisable props.
194

How does caching work in modern Next.js?

Save to ▾
Show answer
Next.js can cache rendered routes and data. In Next.js 15 and later, fetch requests and GET route handlers are not cached by default; you opt in with options like next: { revalidate: 3600 } or the 'use cache' directive with Cache Components in newer versions. You invalidate with revalidatePath or revalidateTag after mutations. The router also caches visited pages on the client. Understanding what is static versus dynamic avoids stale data bugs.
195

What is middleware, now called proxy, in Next.js?

Save to ▾
Show answer
It is code that runs before a request completes, at the edge of the app, and can rewrite, redirect, set headers or cookies based on the request. In Next.js 16 the middleware.ts file convention was renamed to proxy.ts, with the same idea. Typical uses are redirecting unauthenticated users, locale detection, A/B testing and bot filtering. Keep it light, and still check authorisation in data access code.
196

An e-commerce site has one lakh product pages whose prices change a few times a day. Which rendering strategy would you choose in Next.js?

Save to ▾
Show answer
Building all pages statically at deploy time would be slow, and full SSR on every request adds server load. I would pre-render the most popular products at build time, generate the rest on first request and cache them, and revalidate on demand with revalidateTag when prices change in the admin. Stock and price shown in the cart would be fetched fresh. This gives static speed with correct data.
197

What are micro-frontends and when are they worth it?

Save to ▾
Show answer
Micro-frontends split a large web app into independently built and deployed parts owned by different teams, for example search, cart and account, combined at runtime using Module Federation, iframes or route-level composition. They help very large organisations scale teams and deployments. The costs are duplicated dependencies, harder shared state, inconsistent UX and complex tooling, so they are rarely worth it for small or medium teams.
198

How would you build and maintain a shared component library for several React apps?

Save to ▾
Show answer
Start with design tokens for colours, spacing and typography, and build accessible primitives, often on top of headless libraries like Radix UI or React Aria. Document components in Storybook with usage examples, add visual regression and accessibility tests, and publish versioned packages from a monorepo with semantic versioning and changelogs. Keep APIs small and composable, and collect feedback from consuming teams before breaking changes.
199

How do you write a generic, type-safe List component in TypeScript?

Save to ▾
Show answer
Use a type parameter so the item type flows to the render callback. type ListProps<T> = { items: T[]; getKey: (item: T) => string | number; renderItem: (item: T) => React.ReactNode; }; function List<T>({ items, getKey, renderItem }: ListProps<T>) { return <ul>{items.map(i => <li key={getKey(i)}>{renderItem(i)}</li>)}</ul>; } <List items={users} getKey={u => u.id} renderItem={u => u.name} />
200

Describe how you led a large frontend migration.

Save to ▾
Show answer
Situation: our app ran on an unmaintained Create React App setup with slow builds. Task: move to Vite without stopping feature work. Action: I wrote a migration plan, fixed incompatible imports and env variables in a branch, ran both builds in CI for a week, and trained the team on differences. Result: we switched over a weekend, local start time went from over a minute to a few seconds, and nothing broke for users.

Frequently asked questions

What jobs can I get after learning React JS?

You can apply for roles such as React developer, frontend developer, UI developer, MERN stack developer and Next.js developer. React is used by product startups, fintech and e-commerce companies, SaaS firms and large IT service companies working on global client projects. With some experience you can move into senior frontend, full-stack or frontend architect roles. Building two or three solid projects and a GitHub profile greatly improves your chances of getting shortlisted.

Who can learn React JS and what do I need to know first?

Students, fresh graduates from any stream, working professionals switching careers and backend developers can all learn React. You should be comfortable with HTML, CSS and core JavaScript, including functions, arrays, objects, promises and ES6 syntax like destructuring and arrow functions. If your JavaScript is weak, spend two to three weeks strengthening it first, because most React interview questions and bugs come down to JavaScript fundamentals.

How long does it take to learn React JS for a job?

With daily practice of two to three hours, most learners become comfortable with React basics in about four to six weeks and job-ready in around three months, including hooks, state management, routing, testing and Next.js. The exact time depends on your JavaScript background and how many projects you build. Consistent project work matters more than watching long tutorials, because interviews test whether you can actually build and debug features.

Is React still worth learning in 2026?

Yes. React remains the most used frontend library, with React 19, the React Compiler and frameworks like Next.js keeping it modern. Job portals in India consistently list more React openings than other frontend frameworks, especially in startups and product companies. Skills you learn, such as components, state management and TypeScript, also transfer to React Native for mobile apps and to other frameworks if you switch later.

Will I get a certificate and does it help in getting hired?

You receive a course completion certificate after finishing the training and projects. A certificate helps show structured learning on your resume and LinkedIn, but recruiters mainly judge React candidates by projects, GitHub code and interview performance. Use the certificate alongside two or three deployed projects, a clean portfolio and practice with real interview questions, which together make your profile far stronger than a certificate alone.

Should I learn Next.js and TypeScript along with React?

Yes. Most new React job descriptions mention TypeScript, and many companies build production apps with Next.js for SEO and performance. Learn plain React first so you understand components, state and hooks, then add TypeScript while building projects, and finally learn Next.js App Router and Server Components. This order avoids confusion and prepares you for both client-side React roles and full-stack Next.js roles.