Skip to content

Top 50 Most Asked React JS Interview Questions

The questions that appear most often across company-wise sets — master these first.

Why start here

We count how often each question appears across the 20 company-wise React JS practice sets on this site and show the 50 most common. They are the safest questions to master first.

Solved — top 50Start 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

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

Routing and FormsIn 11 company setsMedium
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> </>); }
02

Write a useDebounce custom hook.

React HooksIn 10 company setsMedium
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
03

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

State ManagementIn 10 company setsMedium
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.
04

How do you mock a module in Vitest?

Testing and DebuggingIn 9 company setsMedium
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.
05

How do you test a custom hook?

Testing and DebuggingIn 9 company setsMedium
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.
06

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?

Testing and DebuggingIn 9 company setsMedium
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.
07

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

Next.js and Advanced ReactIn 9 company setsMedium
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.
08

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

Props and StateIn 8 company setsMedium
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.
09

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

Performance OptimizationIn 8 company setsMedium
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.
10

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

Next.js and Advanced ReactIn 8 company setsMedium
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.
11

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?

React FundamentalsIn 7 company setsMedium
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.
12

How do you create an error boundary in React?

React FundamentalsIn 7 company setsMedium
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.
13

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?

Props and StateIn 7 company setsMedium
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.
14

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?

Props and StateIn 7 company setsMedium
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.
15

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

State ManagementIn 7 company setsMedium
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.
16

What are loaders and actions in React Router?

Routing and FormsIn 7 company setsMedium
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.
17

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

React FundamentalsIn 6 company setsMedium
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

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

React FundamentalsIn 6 company setsMedium
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.
19

What are portals and when would you use them?

React FundamentalsIn 6 company setsMedium
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.
20

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

Props and StateIn 6 company setsMedium
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.
21

How do you type props for a component in TypeScript?

Props and StateIn 6 company setsMedium
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>; }
22

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?

Props and StateIn 6 company setsMedium
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.
23

What is the difference between server state and client state?

State ManagementIn 6 company setsMedium
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.
24

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

State ManagementIn 6 company setsHard
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.
25

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

State ManagementIn 6 company setsMedium
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.
26

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

Routing and FormsIn 6 company setsHard
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.
27

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

Routing and FormsIn 6 company setsHard
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.
28

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

Performance OptimizationIn 6 company setsHard
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.
29

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

Performance OptimizationIn 6 company setsMedium
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.
30

How do you include accessibility checks in your React tests?

Testing and DebuggingIn 6 company setsMedium
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.
31

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

Next.js and Advanced ReactIn 6 company setsMedium
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.
32

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

Next.js and Advanced ReactIn 6 company setsMedium
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.
33

What are synthetic events in React?

React FundamentalsIn 5 company setsMedium
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}.
34

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

Props and StateIn 5 company setsMedium
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.
35

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

Props and StateIn 5 company setsHard
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.
36

What do useActionState and useFormStatus do in React 19?

React HooksIn 5 company setsMedium
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.
37

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

React HooksIn 5 company setsMedium
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.
38

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

React HooksIn 5 company setsMedium
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.
39

Create a Redux Toolkit slice for a counter.

State ManagementIn 5 company setsMedium
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;
40

Show how to fetch data with TanStack Query.

State ManagementIn 5 company setsMedium
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} />; }
41

Why must Redux reducers be pure functions?

State ManagementIn 5 company setsEasy
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.
42

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

State ManagementIn 5 company setsHard
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.
43

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

Routing and FormsIn 5 company setsMedium
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.
44

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

Routing and FormsIn 5 company setsMedium
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.
45

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

Routing and FormsIn 5 company setsMedium
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.
46

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?

Performance OptimizationIn 5 company setsMedium
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.
47

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?

Testing and DebuggingIn 5 company setsHard
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.
48

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

Testing and DebuggingIn 5 company setsHard
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.
49

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

Next.js and Advanced ReactIn 5 company setsMedium
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.
50

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?

React FundamentalsIn 4 company setsMedium
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.

Frequently asked questions

How is this list made?

We count how often each question appears across the 20 company-wise React JS practice sets on this site and show the 50 most common. They are the safest questions to master first.

Is this enough to clear an interview?

It is the best starting point, not the finish line. After these, practise the company pages for your target employers and the sheets for your weaker topics.