Skip to content

React JS Interview Questions for 7 Years Experience

40 questions with answers for candidates with 7 years of experience — 1 easy, 21 medium, 18 hard.

What interviewers expect: 7 years experience

With seven years, you are assessed as a technical lead or staff-level engineer. Expect discussions on scaling frontend codebases across teams, monorepos, micro-frontends, performance budgets, observability and migration strategies. Behavioural rounds probe conflict resolution, influencing without authority and balancing delivery with tech debt, backed by concrete stories with outcomes.

This set is weighted towards Testing and Debugging (7), Next.js and Advanced React (7), Performance Optimization (6), State Management (6).

Large-scale frontend architecture Migrations and tech debt strategy Observability and performance budgets Cross-team leadership
Solved at this levelStart 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

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.
02

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(); });
03

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.
04

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.
05

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.
06

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.
07

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> </>); }
08

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.
09

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.
10

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.
11

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.
12

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} />; }
13

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.
14

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.
15

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.
16

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.
17

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} />
18

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.
19

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.
20

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.
21

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.
22

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.
23

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.
24

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.
25

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.
26

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.
27

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.
28

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.
29

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.
30

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.
31

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.
32

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; }); }
33

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.
34

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.
35

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.
36

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.
37

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.
38

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.
39

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.
40

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.

Frequently asked questions

What is asked in React JS interviews for 7 years of experience?

With seven years, you are assessed as a technical lead or staff-level engineer. Expect discussions on scaling frontend codebases across teams, monorepos, micro-frontends, performance budgets, observability and migration strategies. Behavioural rounds probe conflict resolution, influencing without authority and balancing delivery with tech debt, backed by concrete stories with outcomes.

How many questions should I practise before a React JS interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 7 years of experience?

Focus first on Large-scale frontend architecture, Migrations and tech debt strategy, Observability and performance budgets, Cross-team leadership.