27 role-specific questions
React.js Developer Interview Questions & Answers
React interviews go beyond hooks syntax: interviewers want to know you understand rendering and reconciliation, can manage state sensibly, optimise only what's slow, and test components the way users use them.
Free, no sign-up. 110 questions in this role's practice pool, including behavioural, HR and situational questions.
React interview questions
Rendering, reconciliation, hooks, state management and performance — from the questions every React interview asks to senior-level depth.
1.
Explain the React rendering process. What happens when state changes?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand render vs commit, which underpins performance work.
Key points a strong answer covers
- Triggers. A render is triggered by a state update, a parent re-render or a context change.
- Render phase. React calls your components to get new elements — this should be pure, with no side effects.
- Reconciliation / diff. It compares the new tree with the previous one to work out what changed.
- Commit phase. In the commit phase React applies the minimal DOM changes, then runs effects.
- Batching. Multiple state updates in one event are batched into one render.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying a re-render always updates the DOM.
- Putting side effects in the render body.
Likely follow-up questions
- Why must components be pure during render?
- When do
useLayoutEffectanduseEffectrun relative to paint?
Example strong answer
When state changes, React schedules a render of that component — and by default its children. In the render phase React calls the component functions to produce a new tree of elements; that work must be pure, because React may call it more than once or throw it away. It then reconciles: compares the new tree with the previous one to find what actually changed. In the commit phase it applies only those changes to the DOM, runs layout effects, lets the browser paint, and then runs
useEffects. Updates inside one event are batched into a single render. So a re-render doesn't necessarily touch the DOM — it only does if the output differs.2.
How does React reconciliation work, and why do list keys matter?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding of the diffing heuristics and the bugs that bad keys cause.
Key points a strong answer covers
- Heuristic diff. React uses heuristics to diff in O(n) rather than a full tree comparison.
- Type changes remount. If an element's type changes, React throws away that subtree and mounts a new one.
- Keys identify items. Keys tell React which list item is which between renders.
- Index key bugs. Index keys attach state to the wrong item when the list is reordered or items are inserted.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
Math.random()as a key. - Thinking keys are only about silencing the console warning.
Likely follow-up questions
- How can you use a key to reset a component's state on purpose?
- What happens if two siblings share a key?
Example strong answer
Reconciliation is how React decides what changed between two renders. A full tree diff would be too slow, so React assumes two things: elements of a different type produce different trees — so if a
<div>becomes a<section>, or one component becomes another, the old subtree is unmounted and a new one mounted — and keys identify children in a list. With stable keys from your data, React can match items even when they move, keeping their state and DOM. With index keys, inserting at the top shifts every key, so state like a text input's value ends up on the wrong row. You can also change a key deliberately to reset a component, like<Profile key={userId} />.3.
What is the difference between useMemo and useCallback? When are they worth using?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you optimise deliberately rather than by habit.
Key points a strong answer covers
- useMemo caches a value.
useMemocaches the result of a calculation between renders. - useCallback caches a function.
useCallbackcaches a function's identity —useCallback(fn, deps)isuseMemo(() => fn, deps). - Dependencies. Both recompute only when their dependencies change.
- When worth it. Worth it for expensive work, props to memoised children, or effect dependencies — measure first.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Wrapping everything in useMemo/useCallback “for performance”.
- Thinking useMemo prevents a component from re-rendering.
Likely follow-up questions
- Why does useCallback do nothing if the child isn't wrapped in React.memo?
- How does the React Compiler change this advice?
Example strong answer
useMemocaches a computed value;useCallbackcaches a function so its identity stays the same between renders —useCallback(fn, deps)is equivalent touseMemo(() => fn, deps). Both recompute only when a dependency changes. They're worth it in three cases: an expensive calculation like filtering thousands of rows, passing an object or callback to a child wrapped inReact.memoso it can skip renders, and keeping a value stable when it's an effect dependency. Otherwise they add complexity for nothing — I measure with the Profiler first. With the React Compiler, much of this memoisation is automatic.- useMemo caches a value.
4.
What are controlled and uncontrolled components?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Form handling fundamentals.
Key points a strong answer covers
- Controlled = React state. A controlled input's value comes from React state and changes through onChange.
- Uncontrolled = DOM keeps value. An uncontrolled input keeps its own value in the DOM; you read it with a ref or FormData.
- Trade-offs. Controlled suits instant validation and formatting; uncontrolled is simpler and cheaper for big forms.
- Libraries / file inputs. Libraries like React Hook Form are largely uncontrolled; file inputs are always uncontrolled.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Switching an input from uncontrolled to controlled (value undefined → string).
- Not knowing file inputs can't be controlled.
Likely follow-up questions
- What causes the “changing an uncontrolled input to be controlled” warning?
- How would you handle a 50-field form efficiently?
Example strong answer
A controlled input gets its value from React state and updates through
onChange, so React is the single source of truth — ideal when you need instant validation, formatting like a phone mask, or to enable a button as the user types. An uncontrolled input keeps its own value in the DOM; you set adefaultValueand read it on submit with a ref orFormData. That's simpler and avoids a re-render per keystroke, which helps on big forms — React Hook Form is built on this. File inputs are always uncontrolled. A common bug is starting withvalue={undefined}and later passing a string, which flips an input from uncontrolled to controlled.5.
How does useEffect work, and what are the most common mistakes with it?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Correct mental model of effects as synchronisation, not lifecycle methods.
Key points a strong answer covers
- Runs after commit. Effects run after React commits the render to the screen.
- Dependencies. They re-run when dependencies change; missing deps cause stale values.
- Cleanup. The returned cleanup runs before the next effect and on unmount.
- Don't need an effect. Derived state and event-driven logic don't belong in effects; data fetching is better in a library or framework.
- Strict mode double run. In development Strict Mode, effects mount, clean up and mount again to surface missing cleanup.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using an effect to copy props into state.
- Fetching without cancelling, causing race conditions.
Likely follow-up questions
- Why does my effect run twice in development?
- How do you avoid a race condition when fetching in an effect?
Example strong answer
useEffectsynchronises a component with something outside React — a subscription, a timer, the document title. It runs after the render is committed, and again whenever a dependency changes; the function you return is the cleanup, which runs before the next run and on unmount. The common mistakes are missing dependencies, which give stale values; no cleanup, which leaks listeners; fetching without ignoring stale responses, which causes race conditions; and using effects for things that aren't effects — derived values should be calculated during render, and logic caused by a click belongs in the event handler. In development Strict Mode effects run, clean up and run again to expose missing cleanups.6.
How do you manage complex application state in React?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Architecture judgement: choosing the simplest tool that fits.
Key points a strong answer covers
- Local first. Keep state as close as possible to where it's used; lift only when needed.
- Server state is different. Remote data belongs in a cache library (TanStack Query, SWR) or the framework, not global state.
- Context for low-frequency. Context suits rarely changing values; frequent updates re-render every consumer.
- Global stores. For complex shared client state: useReducer, Zustand or Redux Toolkit.
- URL state. Filters and selections often belong in the URL.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Putting everything, including API data, in one global store.
- Using Context for fast-changing values like an input.
Likely follow-up questions
- What's the difference between client state and server state?
- When would you pick Redux Toolkit over Zustand?
Example strong answer
I start by sorting state into kinds. Server state — data from APIs — goes in a caching layer such as TanStack Query or the framework's data loading, which handles loading, caching and refetching. URL state, like filters and the current tab, goes in search params so it's shareable. UI state stays local with
useState, lifted only as far as needed, anduseReducerwhen updates have complex rules. Context is for low-frequency values like the theme or current user, since every consumer re-renders on change. Only if there's genuinely complex shared client state — a multi-step editor, say — do I add a store like Zustand or Redux Toolkit.7.
How would you optimise a slow React application?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
A measured, methodical approach to performance.
Key points a strong answer covers
- Measure first. Profile with the React DevTools Profiler and Performance panel; check Core Web Vitals.
- Reduce re-renders. Avoid unnecessary renders: colocate state, split context, memoise where measured.
- Large lists. Virtualise long lists.
- Bundle / loading. Code-split routes and heavy components; optimise images and bundle size.
- Defer non-urgent work. useTransition / useDeferredValue keep typing responsive; move heavy work to a worker.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Jumping straight to memoising everything without profiling.
- Ignoring network and bundle size and only looking at renders.
Likely follow-up questions
- What does the Profiler's flame graph tell you?
- When would you use
useDeferredValue?
Example strong answer
First I measure, because slow can mean many things. I check Core Web Vitals to see whether it's load time (LCP) or interaction (INP), then profile the slow interaction with the React DevTools Profiler and the browser's Performance panel. For load time: code-split routes and heavy widgets with
lazy, trim the bundle, optimise images. For slow interactions: find components re-rendering unnecessarily — often state too high up or a context with a frequently changing value — and colocate state, split context, or memoise the expensive child. Long lists get virtualised. For heavy filtering while typing,useDeferredValueoruseTransitionkeeps input responsive. Then I measure again to confirm the gain.8.
What are React Server Components, and how are they different from server-side rendering?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Up-to-date knowledge of modern React architecture.
Key points a strong answer covers
- Render only on the server. Server Components run only on the server; their code never ships to the browser.
- Zero client JS. They add no JavaScript to the bundle.
- Direct data access. They can be async and read databases or secrets directly.
- Client components for interactivity. Interactivity needs Client Components marked with 'use client'.
- Not the same as SSR. SSR renders HTML for the first load then hydrates everything; RSC is about which components ever reach the client.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying RSC is just another name for SSR.
- Passing functions or class instances as props from server to client.
Likely follow-up questions
- What can you pass as props from a Server Component to a Client Component?
- Can a Client Component import a Server Component?
Example strong answer
Server Components are components that run only on the server — at build time or per request — and send their rendered result to the client, never their code. So they add no JavaScript to the bundle, can be async, and can read a database or use secrets directly. Anything interactive — state, effects, event handlers — goes in a Client Component marked
'use client', which you can render inside a Server Component, passing serialisable props. That's different from SSR: SSR renders all components to HTML for a fast first paint and then hydrates them all in the browser, so their code still ships. RSC changes which components ever reach the client. In practice you use both together.9.
When do you write a custom hook? Give an example.
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Code organisation and reuse of stateful logic.
Key points a strong answer covers
- Reuse stateful logic. Custom hooks extract and reuse stateful logic between components.
- Naming / rules of hooks. They start with
useand follow the rules of hooks. - Separate state per caller. Each component calling the hook gets its own state; hooks share logic, not state.
- Example. e.g. useDebounce, useLocalStorage, useMediaQuery, useOnlineStatus.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking two components using the same hook share state.
- Wrapping trivial one-liners in hooks.
Likely follow-up questions
- How would you test a custom hook?
- Why must hooks be called in the same order every render?
Example strong answer
I write a custom hook when two or more components need the same stateful logic, or when a component's logic is getting long and has a clear name. For example
useDebouncedValue(value, delay)wraps a state and a timer effect, anduseMediaQuery('(max-width: 640px)')subscribes to a media query and cleans up. A custom hook is just a function starting withusethat calls other hooks, so it follows the rules of hooks — top level, same order every render. Importantly, it shares logic, not state: every component that calls it gets its own independent state. If I need shared state, that's context or a store.10.
What is React Context for, and what are its performance pitfalls?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Knowing when Context is the right tool.
Key points a strong answer covers
- Avoid prop drilling. Context passes data through the tree without prop drilling.
- Good uses. Theme, current user, locale, feature flags — values that change rarely.
- Re-renders all consumers. When the value changes, every consumer re-renders.
- Mitigations. Split contexts, memoise the value object, or use a store with selectors for fast-changing state.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Creating the value object inline so it changes every render.
- Using one giant context for the whole app.
Likely follow-up questions
- Why should the provider's value be memoised?
- How does a store with selectors avoid unnecessary renders?
Example strong answer
Context lets a value reach any depth of the tree without passing props through every level — good for the theme, the signed-in user, the locale or feature flags. The catch is that when the provider's value changes, every component that reads that context re-renders. So I keep fast-changing state out of it, split unrelated values into separate contexts, and memoise the value object —
value={{ user, logout }}inline creates a new object each render and re-renders all consumers. For frequently updated shared state, a store like Zustand with selectors is better because components re-render only when the slice they select changes.11.
How do you handle errors in a React app?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Resilience and user experience when things fail.
Key points a strong answer covers
- Error boundaries. Error boundaries catch render errors in their subtree and show a fallback UI.
- What they don't catch. They don't catch errors in event handlers or async code — handle those with try/catch.
- Placement. Place boundaries around routes and risky widgets, not just the root.
- Reporting & recovery. Report errors to monitoring and offer a retry or reset.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Expecting an error boundary to catch a failed fetch in an event handler.
- One boundary at the root that blanks the whole app.
Likely follow-up questions
- Why are error boundaries class components?
- How would you reset an error boundary after the user retries?
Example strong answer
For rendering errors I use error boundaries: a component — still a class, or a library like react-error-boundary — that catches errors thrown while rendering its children and shows a fallback instead of a blank page. I place them around routes and risky widgets, so a broken chart doesn't take the whole dashboard down, and the fallback offers a retry that resets the boundary. They don't catch errors in event handlers, timers or promises, so those get try/catch and a visible error state. Every caught error is reported to monitoring like Sentry, with enough context to reproduce it.
12.
What do Suspense and transitions (useTransition) do?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Familiarity with concurrent React features.
Key points a strong answer covers
- Suspense shows a fallback. Suspense shows a fallback while children wait for code or data.
- Works with lazy and data. It works with
lazy()code splitting and Suspense-aware data sources, and enables streaming. - Transitions are non-urgent.
startTransitionmarks an update as non-urgent so urgent input stays responsive. - Avoid jarring loaders. Transitions keep showing the old UI (with
isPending) instead of a fallback flashing.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking Suspense fetches data by itself.
- Wrapping every update in a transition.
Likely follow-up questions
- How does
useDeferredValuediffer fromuseTransition? - How does Suspense enable streaming SSR?
Example strong answer
Suspense lets a component wait for something — code loaded with
lazy(), or data from a Suspense-aware source like a framework loader or theusehook — and shows the nearest boundary's fallback meanwhile. Boundaries let you decide where loading states appear, and on the server they enable streaming HTML in chunks. Transitions are about priority: wrapping an update instartTransitionmarks it as non-urgent, so typing stays responsive while React prepares the new screen in the background, and an already-visible UI isn't replaced by a fallback — you getisPendingto show a subtle indicator. A typical use is switching tabs or filtering a big list.13.
How do you test React components?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Testing philosophy and practical tooling.
Key points a strong answer covers
- Test behaviour not implementation. Test what the user sees and does, not internal state.
- Testing Library. React Testing Library queries by role and text.
- User events / async. Simulate real interactions with user-event and await async UI.
- Mock the network. Mock APIs at the network level (MSW) rather than mocking internals.
- Test pyramid. Mostly integration-style component tests, plus a few end-to-end tests with Playwright.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Testing internal state or snapshot-testing everything.
- Querying by class names or test ids when a role would do.
Likely follow-up questions
- Why prefer
getByRoleovergetByTestId? - What would you cover with Playwright rather than unit tests?
Example strong answer
I test behaviour the way a user experiences it. With React Testing Library I render the component, find elements by role and accessible name —
getByRole('button', { name: /save/i })— interact with user-event, and assert on what appears. For async UI I usefindByqueries. I mock the network with MSW instead of mocking hooks or modules, so components run their real code. I avoid testing internal state and large snapshots, which break on harmless refactors. Most coverage comes from these integration-style tests, with a handful of Playwright end-to-end tests for critical flows like sign-up and checkout.
JavaScript interview questions
Closures, the event loop, async code, scope and the prototype chain — the core of every front-end and Node.js interview.
1.
Explain closures in JavaScript, with a practical example.
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand lexical scope and can connect it to real code, not just recite a definition.
Key points a strong answer covers
- Function + outer scope. A closure is a function bundled with references to the variables of the scope it was created in.
- Variables stay alive. The captured variables live on after the outer function returns.
- Practical use. Private state, factories, memoisation, debounce/throttle and event handlers all rely on closures.
- Pitfall. Watch for stale values (e.g. in React effects),
varin loops, and accidentally retaining large objects.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying a closure is “a function inside a function” without explaining what it captures.
- No example — interviewers want to see you've used one.
Likely follow-up questions
- What does
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))print, and why? - How can a closure cause a memory leak?
Example strong answer
A closure is a function together with the variables from the scope where it was defined. Because the function keeps a reference to that scope, those variables stay alive even after the outer function has returned. A simple example is a counter factory:
makeCounter()declareslet count = 0and returns a function that increments it — each counter has its own privatecount. I use closures every day for event handlers, debounce helpers and module-private state. The main pitfall is stale values: a React effect or a timer can capture an old variable, so you need the right dependencies or a ref.2.
What is the event loop, and how do microtasks differ from macrotasks?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you can predict the order async code runs in, which matters for debugging race conditions and UI jank.
Key points a strong answer covers
- Single thread + call stack. JavaScript runs one call stack on a single thread; the event loop decides what runs next.
- Task queue. Timers, I/O and UI events queue (macro)tasks.
- Microtasks first. After each task, all queued microtasks (promise callbacks, await continuations) run before the next task.
- Rendering / blocking. Long synchronous work or endless microtasks block rendering.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
setTimeout(fn, 0)runs immediately. - Forgetting that microtasks drain completely before the browser can paint.
Likely follow-up questions
- In what order do
console.log,setTimeoutandPromise.resolve().thenlog? - How would you break up a long-running loop so the page stays responsive?
Example strong answer
JavaScript runs on one thread with one call stack. The event loop takes the next task — a timer callback, an I/O completion or a UI event — and runs it to completion. After every task it drains the microtask queue, which holds promise reactions and
awaitcontinuations, and only then can the browser render and pick the next task. Soconsole.log('a'); setTimeout(() => log('b')); Promise.resolve().then(() => log('c')); log('d')prints a, d, c, b. In practice that's why a heavy synchronous loop freezes the UI; I split long work into chunks withsetTimeoutorscheduler.yield, or move it to a Web Worker.3.
What's the difference between var, let and const?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Basic language fluency: scope, hoisting and immutability of bindings.
Key points a strong answer covers
- Function vs block scope.
varis function-scoped;letandconstare block-scoped. - Hoisting / TDZ. All are hoisted, but
varis initialised to undefined whilelet/constsit in the temporal dead zone until declared. - const binding, not value.
conststops reassignment, not mutation — a const object can still change. - Re-declaration.
varallows re-declaration in the same scope;let/constdon't.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Claiming
constmakes objects immutable. - Saying
letandconstaren't hoisted at all.
Likely follow-up questions
- How would you make an object truly read-only?
- Why does
varin a for-loop cause bugs with callbacks?
Example strong answer
varis function-scoped, can be re-declared, and is hoisted and initialised toundefined, so you can read it before the declaration line.letandconstare block-scoped; they're hoisted too, but they're in the temporal dead zone until the declaration runs, so early access throws.constprevents reassigning the binding, not changing the value —const user = {}can still get new properties; for a read-only object you'd useObject.freeze, which is shallow. In modern code I default toconst, useletwhen a value really changes, and avoidvar.- Function vs block scope.
4.
Explain promises and async/await. How do you handle errors and run requests in parallel?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical async skills: error handling, sequencing and concurrency.
Key points a strong answer covers
- Promise states. A promise is pending, then fulfilled or rejected, once.
- async/await is syntax over promises. An async function returns a promise;
awaitpauses that function until the promise settles. - Error handling. Use try/catch around awaits (or
.catch), and never leave a rejection unhandled. - Parallel vs sequential. Awaiting in a loop is sequential;
Promise.allruns them together;allSettledwaits for every result.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Awaiting independent requests one by one, making the page slower.
- Using
Promise.allwithout considering that one rejection fails the whole batch.
Likely follow-up questions
- When would you choose
Promise.allSettledoverPromise.all? - How would you limit concurrency to five requests at a time?
Example strong answer
A promise represents a value that will arrive later; it's pending, then fulfilled or rejected exactly once.
async/awaitis syntax over promises: an async function always returns a promise, andawaitpauses just that function until the promise settles, so code reads top to bottom. For errors I wrap awaits in try/catch, or attach.catchwhen I'm not awaiting. If requests don't depend on each other I start them together withPromise.all, which rejects as soon as one fails; when I need every outcome — say, uploading ten files and reporting which failed — I usePromise.allSettled. For large batches I limit concurrency with a small pool.5.
How is the value of
thisdetermined in JavaScript?IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand call-site binding — a frequent source of bugs in callbacks and classes.
Key points a strong answer covers
- Depends on the call.
thisis set by how a function is called, not where it's written. - Method / default binding.
obj.fn()sets this to obj; a plain call gives undefined in strict mode (the global object otherwise). - Explicit binding.
call,applyandbindsetthisexplicitly. - Arrow functions. Arrow functions don't have their own
this; they use the enclosing scope's. - new. With
new,thisis the newly created object.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
thisrefers to the function itself. - Not knowing why a method loses
thiswhen passed as a callback.
Likely follow-up questions
- Why does
setTimeout(obj.method, 100)losethis, and how do you fix it? - When would you avoid an arrow function as an object method?
Example strong answer
thisis decided by the call, not the definition. Called as a method —user.greet()—thisisuser. Called as a plain function, it'sundefinedin strict mode or the global object otherwise.call,applyandbindset it explicitly, and withnewit's the newly created instance. Arrow functions don't bind their ownthis; they take it from the surrounding scope, which is why they're handy in callbacks inside class methods. A classic bug is passingobj.methodtosetTimeoutor an event listener: it's called without the object, sothisis lost — fix it withobj.method.bind(obj)or an arrow wrapper.- Depends on the call.
6.
Explain prototypal inheritance. How do ES6 classes relate to it?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Depth of language knowledge beyond syntax.
Key points a strong answer covers
- Prototype chain. Objects link to a prototype; property lookups walk up the chain until found or null.
- Shared methods. Methods on the prototype are shared by all instances rather than copied.
- Classes are syntax.
classis mostly syntax over constructor functions and prototypes. - Creating links.
Object.create, constructor functions andextendsset up the prototype link.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Describing JavaScript classes as if they copy methods like Java classes.
- Confusing
prototype(on functions) with an object's internal prototype.
Likely follow-up questions
- What's the difference between
Foo.prototypeandObject.getPrototypeOf(foo)? - How does
hasOwnPropertydiffer from theinoperator?
Example strong answer
Every object has an internal link to another object, its prototype. When you read a property that isn't on the object itself, JavaScript looks it up on the prototype, then that object's prototype, and so on until it reaches
null. That's how inheritance works: methods live once on a prototype and every instance shares them. ES6 classes are largely syntax over this —class Admin extends UsersetsAdmin.prototype's prototype toUser.prototype, and methods in the class body go on the prototype. You can also link objects directly withObject.create(proto). Knowing this helps when debugginginstanceofor checking own properties withObject.hasOwn.7.
What is event delegation, and why is it useful?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
DOM fundamentals and awareness of performance with many elements.
Key points a strong answer covers
- Bubbling. Most events bubble from the target up through its ancestors.
- One listener on a parent. Attach one listener to a common parent instead of one per child.
- Identify the target. Use
event.target.closest(selector)to find which child was clicked. - Benefits. Works for elements added later and uses fewer listeners.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
event.targetdirectly when the click lands on a nested icon inside the button. - Forgetting events like
focusdon't bubble (usefocusin).
Likely follow-up questions
- What's the difference between
event.targetandevent.currentTarget? - How do
stopPropagationandpreventDefaultdiffer?
Example strong answer
Events bubble: a click on a list item also fires on the list and every ancestor. Event delegation uses that by putting one listener on a parent — say the
<ul>of a long to-do list — and working out which child was clicked withevent.target.closest('li'). It means fewer listeners and it automatically handles items added later, which is ideal for tables or infinite lists. Two things to watch: useclosestbecause the target might be an icon inside the button, and some events such asfocusdon't bubble, so you'd usefocusininstead.8.
What's the difference between
==and===? What aboutObject.is?BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Precision about type coercion.
Key points a strong answer covers
- Coercion.
==converts types before comparing;===doesn't. - Strict equality.
===requires the same type and value. - Edge cases.
null == undefinedis true;NaN === NaNis false; objects compare by reference. - Object.is.
Object.isis like===but treats NaN as equal to itself and +0/-0 as different.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
==compares values and===compares references. - Not mentioning that objects are compared by reference with both.
Likely follow-up questions
- Why is
[] == falsetrue? - How would you compare two objects by their contents?
Example strong answer
===is strict equality: same type and same value, no conversion.==applies type coercion first, which produces surprises like'0' == falseand[] == falseboth being true. The one coercion I find genuinely useful isx == null, which catches both null and undefined. Objects and arrays are compared by reference with either operator, so two identical-looking objects aren't equal.Object.isis like===exceptObject.is(NaN, NaN)is true andObject.is(0, -0)is false. In code I use===by default and lint against==.- Coercion.
9.
What's the difference between debounce and throttle? When would you use each?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical performance techniques for event-heavy UIs.
Key points a strong answer covers
- Debounce waits for a pause. Debounce runs once after events stop for a set time.
- Throttle limits rate. Throttle runs at most once per interval while events keep firing.
- Use cases. Debounce: search-as-you-type, autosave. Throttle: scroll, resize, mousemove.
- Implementation. Both are built with timers (and a closure holding the timer id).
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Mixing up which is which.
- Debouncing scroll position tracking so it only updates after the user stops.
Likely follow-up questions
- How would you implement debounce in a few lines?
- What does a leading-edge debounce do?
Example strong answer
Both limit how often a function runs during a burst of events. Debounce waits until the events stop for, say, 300 ms and then runs once — ideal for search-as-you-type so you send one request when the user pauses, or for autosave. Throttle runs at most once per interval while the events keep coming — good for scroll or resize handlers that need regular updates. Debounce is a closure holding a timer: each call clears the previous timeout and sets a new one. Throttle tracks the last run time or uses a timer flag. Where available,
requestAnimationFrameis often the best throttle for visual updates.10.
How do you copy an object in JavaScript? What's the difference between a shallow and a deep copy?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding of references and immutable update patterns.
Key points a strong answer covers
- Shallow copy. Spread and
Object.assigncopy only the top level; nested objects are still shared. - Deep copy. A deep copy duplicates nested objects too;
structuredClonedoes this natively. - JSON trick limits.
JSON.parse(JSON.stringify(x))loses dates, functions, undefined, Maps and cycles. - Why it matters. Accidental shared references cause state bugs, especially in React/Redux.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking spread makes a full independent copy.
- Recommending the JSON trick without its limitations.
Likely follow-up questions
- What can't
structuredClonecopy? - How would you update a nested property immutably?
Example strong answer
Assigning an object just copies the reference. Spread (
{...obj}) andObject.assignmake a shallow copy: the top-level properties are new, but nested objects are still shared, so changingcopy.address.citychanges the original. For a deep copy I usestructuredClone, which handles nested objects, arrays, Dates, Maps and even cycles — but not functions or DOM nodes. The oldJSON.parse(JSON.stringify())trick loses dates, undefined and functions. In React state I usually don't deep copy at all; I copy just the path I'm changing, like{...user, address: {...user.address, city}}.- Shallow copy. Spread and
11.
Compare ES modules and CommonJS.
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Familiarity with tooling and how code is loaded in browsers and Node.
Key points a strong answer covers
- Syntax. ESM uses import/export; CommonJS uses require and module.exports.
- Static vs dynamic. ESM imports are static, enabling tree shaking; require is a runtime call.
- Loading. ESM loads asynchronously and supports top-level await; CommonJS loads synchronously.
- Interop. Node chooses via
"type": "module"or .mjs/.cjs; interop has rough edges.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Not knowing why tree shaking needs static imports.
- Ignoring that exports in ESM are live bindings.
Likely follow-up questions
- What is a dynamic
import()used for? - Why might a library ship both ESM and CommonJS builds?
Example strong answer
ES modules use
importandexport; CommonJS usesrequireandmodule.exports. ESM imports are static — they're resolved before the code runs — so bundlers can tree-shake unused exports, and the browser supports ESM natively.requireis an ordinary synchronous function call at runtime, which is flexible but harder to analyse. ESM loads asynchronously, supports top-level await and exports live bindings. In Node, the package's"type"field or the .mjs/.cjs extension decides which system a file uses. For code splitting I use dynamicimport(), which returns a promise.12.
How do memory leaks happen in a JavaScript application, and how would you find one?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Debugging maturity on long-lived single-page apps.
Key points a strong answer covers
- Garbage collection basics. Memory is freed when objects become unreachable; leaks are unwanted references.
- Common causes. Forgotten listeners, intervals, subscriptions, growing caches, globals and detached DOM nodes.
- Tools. Compare heap snapshots in DevTools and look at retainers.
- Fixes. Clean up in teardown (effects' cleanup), use AbortController, WeakMap for caches.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying JavaScript can't leak because it's garbage collected.
- No method — guessing instead of measuring.
Likely follow-up questions
- What's a detached DOM node?
- How does
AbortControllerhelp clean up listeners?
Example strong answer
JavaScript is garbage collected, so a leak is really an unwanted reference that keeps objects reachable. Common causes in SPAs are event listeners or intervals that are never removed when a component unmounts, subscriptions that aren't cancelled, caches that only grow, and detached DOM nodes still referenced from JS. To find one I reproduce the action several times — open and close a modal ten times — take heap snapshots before and after in Chrome DevTools, and compare what's growing, then follow the retainers to the code holding it. Fixes are cleanup functions in effects,
AbortControllersignals for listeners and fetches, and WeakMap for object-keyed caches.13.
When would you use map, filter, reduce and forEach?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Idiomatic, readable code and understanding of immutability.
Key points a strong answer covers
- map transforms.
mapreturns a new array of the same length with each item transformed. - filter selects.
filterreturns a new array with the items that pass a test. - reduce accumulates.
reducecombines items into one value — a total, an object, a group-by. - forEach for side effects.
forEachis for side effects and returns undefined; it can't be chained or broken out of.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
mapjust to loop (and ignoring the returned array). - Writing unreadable reduce calls when map + filter is clearer.
Likely follow-up questions
- How would you group an array of orders by customer?
- Which of these mutate the original array?
Example strong answer
maptransforms every item and returns a new array of the same length — turning API records into view models, for example.filterreturns the items that pass a test, like active users.reducefolds the array into one value: a sum, a lookup object, or grouping orders by customer.forEachis for side effects such as logging; it returns undefined and you can't break out of it. None of them mutate the original array, which suits React state. I prefer a readablefilterthenmapover a cleverreduce, and for very large data I'd use a single loop.- map transforms.
14.
Does
fetchreject on a 404 or 500 response? How do you handle HTTP errors properly?IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Real-world API handling and robustness.
Key points a strong answer covers
- Only network errors reject. fetch only rejects on network failures; HTTP errors still resolve.
- Check response.ok. Check
response.okor the status code and throw yourself. - Timeouts / aborts. Use AbortController (or
AbortSignal.timeout) for timeouts and cancellation. - User-facing handling. Parse the error body, show a useful message, and retry only safe requests.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Assuming a try/catch around fetch catches 500 errors.
- Never cancelling requests when a component unmounts.
Likely follow-up questions
- How would you add a 10-second timeout?
- Which requests is it safe to retry automatically?
Example strong answer
No —
fetchonly rejects for network-level failures such as DNS errors or the connection dropping. A 404 or 500 resolves normally, so I always checkresponse.ok(or the status) and throw an error with the status and the parsed error body. I wrap that in a small API helper so every call handles it the same way. For timeouts and cancellation I pass anAbortControllersignal —AbortSignal.timeout(10000)for a deadline, and aborting on unmount so stale responses don't update the UI. I'd only auto-retry idempotent requests like GETs, with backoff.
Ready to answer them out loud?
Run a timed react.js developer mock interview, type or speak your answers, and get a score breakdown with what to improve.