Jump to section

React interview questions test your understanding of component architecture, state management, rendering behavior, and performance optimization. Interviewers evaluate whether you can build maintainable UIs, debug rendering issues, and make informed decisions about hooks, context, and third-party libraries in production applications.

Question Difficulty by Experience Level

LevelTopics CoveredExpected Depth
Junior (0-2 yrs) JSX, props, state, basic hooks, event handling Can build components and explain the basics
Mid (2-5 yrs) Custom hooks, context, performance, testing, patterns Can architect features and debug complex issues
Senior (5+ yrs) Architecture, state management at scale, SSR, migration Can design systems and mentor others

This guide covers:

Conceptual React Questions

These questions test whether you understand how React works under the hood. Interviewers are not looking for memorized definitions. They want to hear you reason through concepts and explain trade-offs.

1. Explain the virtual DOM and how React uses it

What interviewers assess: Foundational understanding of React's rendering model.

React creates an in-memory representation of the DOM called the virtual DOM. When state changes, React builds a new virtual DOM tree, diffs it against the previous one, and calculates the minimal set of changes needed. Those changes are batched and applied to the real DOM in a single update.

The key insight is that DOM manipulation is expensive, and batching updates reduces layout thrashing. React's fiber architecture takes this further by breaking rendering work into units that can be paused, prioritized, and resumed. This enables features like concurrent rendering and transitions.

Common mistake: Saying the virtual DOM is "faster than the real DOM." It is not inherently faster. The virtual DOM is a programming model that makes it easier to write declarative UI code while React handles efficient updates for you. The performance benefit comes from avoiding unnecessary DOM operations, not from the virtual DOM being fast on its own.

2. What are the rules of hooks?

What interviewers assess: Correctness and understanding of React's execution model.

There are two rules. First, hooks must be called at the top level of your component or custom hook. Never call them inside conditions, loops, or nested functions. Second, hooks can only be called from React function components or custom hooks, not from regular JavaScript functions.

The reason behind the first rule is that React tracks hook state by call order. Each render, React expects the same hooks to be called in the same sequence. If you put a hook inside a condition, the call order changes between renders, and React loses track of which state belongs to which hook.

Explain why the constraint exists, not just the rule itself. Interviewers want to know you understand the execution model, not that you memorized a list.

3. How does React handle reconciliation?

What interviewers assess: Understanding of the diffing algorithm and its performance implications.

Reconciliation is the process React uses to determine what changed between two renders. React compares elements by type first. If the type changes (for example, from a <div> to a <span>), React tears down the old tree and builds a new one. If the type stays the same, React updates the existing node's props.

For lists, React uses keys to match elements between renders. Without keys (or with index-as-key), React may re-render the entire list unnecessarily or produce bugs when items are reordered. Stable, unique keys allow React to efficiently insert, remove, and move items.

The diffing algorithm is O(n) by design. React makes the simplifying assumption that elements of different types produce different trees. This is nearly always true in practice and keeps the algorithm fast.

4. When would you use useRef vs useState?

What interviewers assess: Mental model of React's render cycle.

useState stores values that affect what the user sees. When you update state, React re-renders the component. useRef stores values that persist across renders but do not trigger re-renders when they change.

Use useRef for DOM element references, storing timer IDs, tracking previous values, and holding any mutable data that does not affect visual output. Use useState for anything the user sees or interacts with: form inputs, toggle states, counters, loading flags.

A common interview follow-up is: "What happens if you store a value in useRef and try to display it?" The answer is that the display will not update when the ref changes because React does not know about it. Only state changes trigger re-renders.

5. Explain React's context API and its limitations

What interviewers assess: State management decisions and awareness of trade-offs.

Context provides a way to pass data through the component tree without threading props through every level. You create a context with createContext, provide a value at the top with a Provider component, and consume it anywhere below with useContext.

The main limitation is performance. Any component that calls useContext re-renders whenever the context value changes, even if the component only uses a small part of that value. There is no built-in selector mechanism like you get with Redux or Zustand.

Context works well for low-frequency updates: themes, locale, authentication status. For high-frequency updates like form state or real-time data, external state management libraries are usually a better choice. Discuss the trade-off: context is simple and built-in, but it can cause unnecessary re-renders at scale.

6. What is the difference between controlled and uncontrolled components?

What interviewers assess: Form handling patterns and when to use each.

In a controlled component, React manages the input's value through state. Every keystroke updates state, and the input's value is always driven by that state. In an uncontrolled component, the DOM itself holds the current value, and you access it through a ref when needed.

Controlled components give you real-time access to the input value, which enables validation on every keystroke, conditional rendering based on input, and coordinated multi-field forms. The trade-off is more boilerplate: you need a state variable and an onChange handler for each input.

Uncontrolled components are simpler for basic forms where you only need the value on submit. File inputs are always uncontrolled because their value is read-only in the browser.

7. How does React handle error boundaries?

What interviewers assess: Production readiness and resilience patterns.

Error boundaries are class components that implement componentDidCatch and getDerivedStateFromError. They catch JavaScript errors during rendering, in lifecycle methods, and in constructors of child components. When an error is caught, the boundary renders a fallback UI instead of crashing the entire app.

Important limitations: error boundaries do not catch errors in event handlers, asynchronous code (setTimeout, promises), or server-side rendering. For event handler errors, you need regular try/catch blocks.

In production, you typically place error boundaries at route level and around critical features. The fallback UI should give users a way to recover, like a "Try again" button or navigation to a working page. Pair error boundaries with error reporting services to capture and triage issues.

8. Explain server-side rendering and when you would use it

What interviewers assess: Architecture decisions and framework knowledge.

Server-side rendering (SSR) runs your React code on the server and sends fully rendered HTML to the client. The browser displays the HTML immediately while JavaScript loads in the background. Once JavaScript is ready, React "hydrates" the page, attaching event listeners to the existing DOM.

SSR improves initial load time and is essential for SEO on content-heavy pages. Streaming SSR (introduced in React 18) sends HTML progressively, so users see content before the entire page is rendered.

The trade-offs: SSR adds server complexity, increases time-to-first-byte if your data fetching is slow, and requires careful handling of browser-only APIs. Static site generation (SSG) is better for content that does not change per request. Client-side rendering is fine for authenticated dashboards where SEO does not matter.

Frameworks like Next.js handle SSR, SSG, and hybrid rendering out of the box, which is why they are increasingly expected in full-stack React roles.

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Practical React Questions

Practical questions test whether you can build things, not just explain concepts. Interviewers want to see clean code, awareness of edge cases, and thoughtful decisions about when to use built-in tools vs libraries.

1. Build a debounced search input

What interviewers assess: Hooks composition and cleanup logic.

Create a custom hook that wraps useState and useEffect with a debounce timer. The hook accepts a value and a delay, then returns the debounced value. Inside the effect, set a timeout that updates the debounced value after the delay. Return a cleanup function that clears the timeout.

The cleanup function is critical. Without it, you get stale closures: if the component unmounts before the timeout fires, you will try to update state on an unmounted component. The cleanup runs before every re-execution of the effect and on unmount.

Edge cases to discuss: race conditions when async search results return out of order (the solution is an AbortController or a flag that ignores stale results), and what happens if the user types and then navigates away mid-debounce. A strong answer separates the debounce logic into a reusable hook and the search logic into the consuming component.

2. Implement an infinite scroll component

What interviewers assess: Performance awareness and API usage.

Use the IntersectionObserver API to detect when a sentinel element near the bottom of the list enters the viewport. When it does, trigger the next page fetch. This is more efficient than scroll event listeners because IntersectionObserver runs off the main thread.

Handle loading states (show a spinner while fetching), error states (show a retry button if a request fails), and deduplication (prevent firing multiple requests for the same page). Track whether there are more pages to load and remove the observer when the list is complete.

For very long lists (thousands of items), discuss virtualization. Libraries like react-window or react-virtuoso render only the visible items plus a small buffer, keeping the DOM size constant regardless of list length. This prevents memory issues and keeps scrolling smooth.

3. Your component re-renders too often. How do you debug it?

What interviewers assess: Performance debugging methodology.

Start with React DevTools Profiler. Record an interaction and look at which components re-rendered and why. Common culprits: a parent re-rendering causes all children to re-render, new object or function references created on every render get passed as props, or context changes trigger updates in components that do not need them.

Apply fixes based on the root cause. React.memo prevents a child from re-rendering when its props have not changed. useMemo stabilizes object and array references. useCallback stabilizes function references. But only apply these after profiling. Premature memoization adds complexity without solving the actual problem.

Common mistake: Wrapping everything in React.memo and useMemo without measuring. This adds memory overhead and makes code harder to read. Find the bottleneck first, then optimize surgically.

4. Create a custom hook for API data fetching

What interviewers assess: Abstraction skills and error handling.

Build a useFetch hook that manages three states: loading, data, and error. Accept a URL and optional configuration. Use useEffect to trigger the fetch when the URL changes. Handle the response, parse JSON, and update the appropriate state.

The critical detail is handling race conditions. If the URL changes while a request is in flight, the old request's response should be ignored. Use an AbortController to cancel the previous request, or use a boolean flag in the effect cleanup to mark stale responses.

Discuss when you would stop using a custom hook and reach for a library like React Query or SWR. These libraries handle caching, deduplication, background refetching, retry logic, and optimistic updates. For a production application with many API calls, they save significant development time and cover edge cases that are hard to get right manually.

5. Implement a modal system that supports stacking

What interviewers assess: Component composition, portal usage, and accessibility.

Use createPortal to render modals outside the component tree, directly into document.body or a dedicated modal root. This avoids z-index conflicts and overflow:hidden issues from parent containers.

For stacking, maintain an array of active modals in state. Each modal gets a z-index based on its position in the stack. Pressing Escape closes the topmost modal only. Clicking the backdrop closes the topmost modal only.

Accessibility requirements: trap focus within the active modal (Tab and Shift+Tab should cycle through focusable elements inside it), restore focus to the trigger element when the modal closes, and add role="dialog" and aria-modal="true" attributes. Discuss how you would handle screen readers and keyboard navigation throughout.

6. Refactor a class component to use hooks

What interviewers assess: Migration knowledge and lifecycle understanding.

Map lifecycle methods to hooks systematically. componentDidMount becomes useEffect with an empty dependency array. componentDidUpdate becomes useEffect with specific dependencies. componentWillUnmount becomes the cleanup function returned from useEffect.

Replace this.state with individual useState calls. If the class had many related state values, you can use useReducer instead. Replace this.context with useContext.

Watch for subtle differences. Class components batch state updates only inside event handlers, while function components with React 18+ batch all state updates automatically. Also, useEffect runs after paint, while componentDidMount runs before paint. If you need the pre-paint timing, use useLayoutEffect instead.

System Design with React

Senior React interviews often include system design questions. You will not be asked to draw boxes and arrows for backend infrastructure. Instead, you will discuss how to structure a large frontend application, manage state across features, and make performance trade-offs.

State Management at Scale

Start with the simplest approach that works. Local component state (useState) handles most UI state: form inputs, toggle visibility, local loading flags. Context is appropriate for global, low-frequency data like authentication, theme, and locale.

When you need shared state that updates frequently or is accessed by many components, reach for an external library. Redux is well-established but verbose. Zustand offers a simpler API with similar capabilities. Jotai uses an atomic model where each piece of state is independent. The right choice depends on your team's experience and the complexity of your state graph.

The key principle is colocating state close to where it is used. Do not hoist state to the top of the tree "just in case." Every piece of state lifted higher than necessary causes unnecessary re-renders in components below. If two sibling components share state, lift it to their nearest common parent and no further.

Component Architecture

Atomic design is a common framework: atoms (buttons, inputs), molecules (search bars, form fields), organisms (navigation, data tables), templates (page layouts), and pages. This gives teams a shared vocabulary and makes component reuse predictable.

Compound components (like a <Tabs> component with <Tab> and <TabPanel> children) provide flexible APIs without prop explosion. The parent manages shared state and passes it down through context or cloneElement.

Hooks have largely replaced render props and higher-order components for sharing logic. Custom hooks are easier to compose, test, and understand. Use them to extract reusable behavior like data fetching, form validation, keyboard shortcuts, and animation state.

For large codebases, organize by feature rather than by type. Group all files for a feature (components, hooks, tests, styles) in one directory instead of spreading them across separate component/, hook/, and style/ folders. This makes it easier to find, modify, and delete features as requirements change.

Performance at Scale

Code splitting with React.lazy and Suspense reduces initial bundle size. Split at the route level first, then at the feature level for large routes. Prefetch routes the user is likely to visit next using import() on hover or viewport entry.

Image optimization matters more than most developers think. Use modern formats (WebP, AVIF), serve responsive sizes with srcset, and lazy-load images below the fold. Frameworks like Next.js handle this automatically with their Image component.

Bundle analysis with tools like webpack-bundle-analyzer or source-map-explorer reveals unexpected dependencies inflating your bundle. Common offenders: moment.js (replace with date-fns or dayjs), lodash (import individual functions), and icon libraries (tree-shake or use SVGs directly).

Testing Strategy

Unit tests for custom hooks: use renderHook from Testing Library to test hooks in isolation. Verify state changes, side effects, and cleanup behavior.

Integration tests for user flows: render full components with Testing Library and simulate user interactions. Test what the user sees and does, not implementation details. Query by role, label, and text rather than test IDs or class names.

End-to-end tests for critical paths: use Playwright or Cypress for login flows, checkout, and other business-critical journeys. Keep E2E tests focused and fast. Run them in CI but do not rely on them for comprehensive coverage.

The Testing Library philosophy is worth mentioning: "The more your tests resemble the way your software is used, the more confidence they can give you." This means testing behavior, not implementation. Avoid testing internal state or method calls directly.

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Common React Interview Mistakes

Over-engineering simple components

Not every component needs a custom hook, context provider, and memoization. Start simple and add abstractions only when the complexity demands it. Interviewers notice when you complicate straightforward problems.

Using useEffect for everything

useEffect is not a lifecycle method replacement. It synchronizes your component with external systems. If you find yourself using useEffect to derive state from other state, you probably need a computed value or useReducer instead. The React docs call this "You Might Not Need an Effect" for a reason.

Not explaining trade-offs

When an interviewer asks "which approach would you use," they do not want a single answer. They want to hear you compare options, acknowledge downsides, and explain why one approach fits the situation better. Always discuss trade-offs.

Forgetting accessibility in component design

If you build a custom dropdown, modal, or tab component without mentioning keyboard navigation, focus management, or ARIA attributes, you are leaving points on the table. Accessibility is part of component quality, not an afterthought.

Memorizing hook signatures without understanding the mental model

Knowing that useEffect takes a dependency array is not enough. You need to understand why it exists (to control when the effect re-runs), what happens when you get it wrong (stale closures, infinite loops), and how cleanup works. Interviewers probe the "why" behind every answer.

Ignoring error handling and loading states

When you build a component in an interview, always handle the loading state, the error state, and the empty state. Jumping straight to the happy path makes your solution look incomplete. Production components deal with failure, and interviewers expect you to show that awareness.

React Question Bank

The 180 questions below are grouped by topic, from fundamentals and hooks to performance, state management, routing, testing, and Next.js. Open any question to see what the interviewer is really asking, how weak, average, and strong answers are scored, the key points to hit, common mistakes, a sample answer, and the follow-ups to expect.

Read a question, answer it out loud before you open it, then compare. To rehearse with follow-up questions under time pressure, run an AI mock interview for your target React role.

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Conceptual / Theory Questions (30)

What is React?
easy

What they're really asking

This tests foundational React knowledge and whether candidates understand React's core philosophy of component-based UI development. The interviewer wants to see if you grasp React's declarative approach versus imperative DOM manipulation.

How you'll be scored

Weak

Gives vague answers like 'React is a framework for building websites' without mentioning components or declarative concepts.

Average

Correctly identifies React as a JavaScript library for building user interfaces with components.

Strong

Explains React's declarative component-based approach, mentions virtual DOM, and contrasts it with imperative DOM manipulation.

How to structure your answer

  1. Define React as a JavaScript library for building user interfaces.
  2. Explain the component-based architecture concept.
  3. Mention declarative programming approach.
  4. Contrast with traditional imperative DOM manipulation.
  5. Briefly touch on React's main benefits.

Key points to hit

  • React is a JavaScript library, not a framework, focused specifically on building user interfaces.
  • Component-based architecture allows you to break UI into reusable, isolated pieces.
  • Declarative approach means you describe what the UI should look like for any given state.
  • React handles the how of updating the DOM efficiently through its reconciliation process.

Common mistakes

  • Calling React a framework instead of a library, which shows lack of precision about React's scope.
  • Focusing only on technical features without explaining the fundamental mental model shift from imperative to declarative.

Sample answer

React is a JavaScript library developed by Facebook for building user interfaces, particularly web applications. The core idea is component-based architecture where you break your UI into small, reusable pieces called components.

What makes React special is its declarative approach - instead of manually manipulating the DOM like with jQuery, you describe what your UI should look like for any given state, and React figures out how to update the DOM efficiently. This makes code much more predictable and easier to debug than traditional imperative DOM manipulation.

How to level up

  • Mention React's unidirectional data flow as a key architectural principle that prevents many common bugs.
  • Discuss how React's component model enables better testing and code organization compared to traditional approaches.
  • Reference React's ecosystem and how it focuses on the view layer, allowing flexibility in choosing other tools.

Follow-up questions to expect

  • What are the main benefits of component-based architecture over traditional approaches?
  • How does React's declarative approach differ from imperative programming?
  • What problems was React designed to solve in frontend development?
Practice this question with AI feedback →
What is JSX? How does it work and why is it used?
easy

What they're really asking

This tests understanding of JSX syntax and the compilation process. The interviewer wants to see if you know JSX is syntactic sugar and understand how it transforms into JavaScript function calls.

How you'll be scored

Weak

Says JSX is HTML inside JavaScript without understanding the compilation or why it exists.

Average

Correctly explains JSX as syntax extension that compiles to React.createElement calls.

Strong

Explains JSX compilation, why it improves developer experience, and mentions key differences from HTML like className.

How to structure your answer

  1. Define JSX as JavaScript syntax extension.
  2. Explain how JSX compiles to React.createElement calls.
  3. Show a concrete before/after example.
  4. Explain why JSX improves developer experience.
  5. Mention key differences from HTML.

Key points to hit

  • JSX is syntactic sugar that compiles to React.createElement function calls at build time.
  • Babel or TypeScript compiler transforms JSX into regular JavaScript before the browser sees it.
  • JSX makes React code more readable and familiar to developers who know HTML.
  • Key differences from HTML include className instead of class, and camelCase event handlers like onClick.

Common mistakes

  • Thinking JSX runs directly in the browser without understanding the compilation step.
  • Not knowing the differences between JSX and HTML attributes like className vs class.

Sample answer

JSX is a syntax extension for JavaScript that lets you write HTML-like code inside your JavaScript files. Under the hood, JSX doesn't run directly in the browser. Instead, build tools like Babel compile it into React.createElement function calls. For example, `
Hello
` becomes `React.createElement('div', {className: 'header'}, 'Hello')`. This compilation step is why you need to import React in files that use JSX. The main benefit is developer experience - JSX is much more readable and familiar than writing React.createElement calls manually, while still being just JavaScript.

How to level up

  • Mention that with React 17's new JSX transform, you no longer need to import React in every file.
  • Discuss how JSX enables better tooling like syntax highlighting and autocomplete in editors.
  • Explain that JSX expressions must return a single parent element or React Fragment.

Follow-up questions to expect

  • What happens if you forget to import React when using JSX in older React versions?
  • Can you show me how a complex JSX expression would compile to createElement calls?
  • What are some limitations or gotchas when working with JSX?
Practice this question with AI feedback →
What is the Virtual DOM and how does React use it?
easy

What they're really asking

This tests understanding of React's core performance optimization strategy and reconciliation process. The interviewer wants to see if you understand how React minimizes expensive DOM operations through diffing.

How you'll be scored

Weak

Vague explanation about Virtual DOM being faster without understanding the diffing process or why DOM operations are expensive.

Average

Correctly explains Virtual DOM as JavaScript representation that React diffs to minimize DOM updates.

Strong

Explains the reconciliation process, why DOM operations are expensive, and how React's diffing algorithm optimizes updates.

How to structure your answer

  1. Define Virtual DOM as JavaScript representation of the real DOM.
  2. Explain why direct DOM manipulation is expensive.
  3. Describe React's diffing and reconciliation process.
  4. Show how this minimizes actual DOM operations.
  5. Mention batching of updates for performance.

Key points to hit

  • Virtual DOM is a JavaScript object tree that represents the structure of your UI components.
  • Direct DOM operations are expensive because they trigger layout, painting, and style recalculation.
  • React compares the new Virtual DOM tree with the previous one to find the minimal set of changes needed.
  • Only the differences between Virtual DOM trees result in actual DOM updates, reducing expensive operations.

Common mistakes

  • Thinking Virtual DOM is always faster than direct DOM manipulation, when actually small targeted updates can be faster.
  • Not understanding that Virtual DOM's main benefit is predictable performance, not raw speed.

Sample answer

The Virtual DOM is React's JavaScript representation of the actual DOM structure. When your component state changes, React creates a new Virtual DOM tree representing the new state. It then compares this new tree with the previous Virtual DOM tree in a process called diffing.

The key insight is that JavaScript object comparisons are much faster than DOM operations, which trigger expensive browser reflows and repaints. React calculates the minimal set of changes needed and applies only those specific updates to the real DOM, often batching multiple updates together for even better performance.

How to level up

  • Mention that React's diffing algorithm uses heuristics like component type and key props to make O(n) comparisons instead of O(n³)
  • Discuss how React Fiber improved this process with time-slicing and priority-based updates.
  • Explain that keys help React identify which list items have changed, moved, or been removed during diffing.

Follow-up questions to expect

  • How does React's diffing algorithm decide which DOM nodes to update?
  • What role do keys play in Virtual DOM diffing for lists?
  • Are there cases where direct DOM manipulation might be faster than Virtual DOM?
Practice this question with AI feedback →
What is the difference between the Real DOM and the Virtual DOM?
easy

What they're really asking

This tests deeper understanding of why Virtual DOM exists and the performance characteristics of different DOM manipulation approaches. The interviewer wants to see if you understand the trade-offs between abstraction and control.

How you'll be scored

Weak

Simply states Virtual DOM is faster without explaining the underlying performance characteristics or trade-offs.

Average

Correctly identifies Real DOM as browser API and Virtual DOM as JavaScript abstraction with performance benefits.

Strong

Explains the performance trade-offs, when each approach is better, and understands that Virtual DOM optimizes for developer experience and predictable performance.

How to structure your answer

  1. Define Real DOM as the browser's native API.
  2. Define Virtual DOM as React's JavaScript abstraction.
  3. Compare performance characteristics of each.
  4. Explain when each approach is preferable.
  5. Discuss developer experience implications.

Key points to hit

  • Real DOM is the browser's tree structure with expensive operations like style calculation and layout.
  • Virtual DOM is lightweight JavaScript objects that can be created and compared quickly.
  • Real DOM updates trigger synchronous browser work like reflow and repaint.
  • Virtual DOM allows React to batch updates and apply minimal changes asynchronously.

Common mistakes

  • Claiming Virtual DOM is always faster, when targeted Real DOM updates can actually be quicker for simple changes.
  • Not recognizing that Virtual DOM's main advantage is predictable performance and easier mental model, not raw speed.

Sample answer

The Real DOM is the browser's actual tree structure where changes trigger expensive operations like style recalculation, layout, and painting. The Virtual DOM is React's lightweight JavaScript representation of this structure. When you update state, React creates a new Virtual DOM tree, compares it with the previous one, and calculates the minimum changes needed.

The key difference is that Virtual DOM operations happen in memory and are very fast, while Real DOM operations are expensive because they involve the browser's rendering engine. However, Virtual DOM isn't always faster - if you know exactly what to change, direct DOM manipulation can be quicker.

Virtual DOM's real benefit is predictable performance and a simpler mental model for developers.

How to level up

  • Mention that Virtual DOM enables React's declarative programming model where you describe the end state rather than the steps to get there.
  • Discuss how Virtual DOM allows for advanced optimizations like time-slicing and concurrent rendering in React 18.
  • Explain that Virtual DOM abstraction enables server-side rendering and React Native by decoupling from browser DOM.

Follow-up questions to expect

  • In what scenarios might direct DOM manipulation be preferable to Virtual DOM?
  • How does Virtual DOM enable features like server-side rendering?
  • What are the memory trade-offs of keeping a Virtual DOM representation?
Practice this question with AI feedback →
What is the difference between an Element and a Component in React?
easy

What they're really asking

This tests understanding of React's building blocks and the distinction between data and behavior. The interviewer wants to see if you understand that elements are what components return and how React's rendering model works.

How you'll be scored

Weak

Confuses elements and components or gives circular definitions without understanding the relationship.

Average

Correctly identifies elements as objects describing what to render and components as functions or classes that return elements.

Strong

Explains the element-component relationship, shows how React.createElement creates elements, and understands elements are immutable descriptions.

How to structure your answer

  1. Define React elements as plain objects describing what to render.
  2. Define components as functions or classes that return elements.
  3. Show the relationship between the two concepts.
  4. Explain element immutability and component reusability.
  5. Provide concrete examples to illustrate the difference.

Key points to hit

  • Elements are plain JavaScript objects that describe what you want to see on screen, created by React.createElement or JSX.
  • Components are functions or classes that accept props and return elements describing the UI.
  • Elements are immutable - once created, you can't change their children or attributes.
  • Components are reusable and can be called multiple times to create many elements with different props.

Common mistakes

  • Using the terms interchangeably without understanding that components produce elements.
  • Not understanding that elements are the actual objects React works with during rendering and diffing.

Sample answer

A React element is a plain JavaScript object that describes what you want to render - it's like a blueprint created by JSX or React.createElement. For example, `
Hello
` creates an element object with type 'div' and children 'Hello'. A component, on the other hand, is a function or class that accepts props and returns elements. Think of it this way: if I write a Button component function, that's the reusable template. But when I use `<Button color='blue' />` in my JSX, that creates a specific Button element with those props. Elements are immutable snapshots, while components are the reusable factories that produce those elements.

How to level up

  • Mention that React.isValidElement can check if something is a React element, useful for building component libraries.
  • Discuss how understanding this distinction helps with debugging - React DevTools shows component trees, but React works with element trees internally.
  • Explain that element types can be strings for DOM nodes or component functions/classes for custom components.

Follow-up questions to expect

  • Can you show me what a React element object actually looks like internally?
  • How does React use element types during the reconciliation process?
  • What happens when you try to modify a React element after it's created?
Practice this question with AI feedback →
What is the difference between functional components and class components?
easy

What they're really asking

This tests understanding of React's evolution from class-based to functional patterns and whether you can articulate the practical differences that matter in daily development work.

How you'll be scored

Weak

Lists surface differences without understanding when to use each or mentions outdated patterns as current best practices.

Average

Correctly explains syntax differences and mentions hooks but doesn't connect to practical development benefits.

Strong

Demonstrates understanding of both patterns, explains why functional components became preferred, and shows awareness of when class components might still be needed.

How to structure your answer

  1. Define both component types with syntax examples.
  2. Explain how state and lifecycle methods differ between them.
  3. Discuss the introduction of hooks and what changed.
  4. Mention when you might still use class components.
  5. Connect to modern React development practices.

Key points to hit

  • Functional components use hooks for state and side effects instead of this.state and lifecycle methods.
  • Class components require binding methods or using arrow functions to maintain proper 'this' context.
  • Hooks like useState and useEffect replaced the need for class component patterns in most cases.
  • Error boundaries still require class components since there's no hook equivalent yet.

Common mistakes

  • Claiming functional components are always better without acknowledging specific use cases for classes.
  • Forgetting that hooks fundamentally changed how we write React, not just the syntax.

Sample answer

Functional components are JavaScript functions that return JSX, while class components extend React.Component. The main difference is how they handle state and side effects. Class components use this.state and lifecycle methods like componentDidMount, while functional components use hooks like useState and useEffect.

For example, a class component needs a constructor to set initial state and you have to bind methods or use arrow functions to avoid 'this' binding issues.

Functional components with hooks are now the preferred approach because they're simpler to write and test, though you still need class components for error boundaries since there's no hook equivalent.

How to level up

  • Mention that functional components can be easier to optimize with React.memo compared to class components with PureComponent.
  • Explain how custom hooks enable better code reuse than class component patterns like higher-order components.

Follow-up questions to expect

  • Can you show me how you'd convert a class component with state to a functional component?
  • When would you still choose a class component over a functional component?
  • How do you handle component lifecycle in functional components?
Practice this question with AI feedback →
What are props in React? How are they different from state?
easy

What they're really asking

The interviewer is testing whether you understand React's core data flow model. They want to hear you explain the difference between data that flows down from a parent and data that a component manages internally.

How you'll be scored

Weak

Confuses props and state, or says something vague like "props are for passing data and state stores data" without explaining the relationship.

Average

Correctly defines both but does not explain immutability of props, unidirectional data flow, or when to choose one over the other.

Strong

Clearly defines both, explains that props are read-only and flow downward while state is mutable and local, and gives a concrete example showing them working together.

How to structure your answer

  1. Define props: external data passed from a parent component to a child, read-only within the child.
  2. Define state: internal data managed by the component itself, mutable via setState or useState.
  3. Explain the key differences: ownership, mutability, and direction of data flow.
  4. Give a concrete example showing props and state working together.

Key points to hit

  • Props are immutable from the child's perspective. A child component cannot modify its own props.
  • State is local and mutable. When state changes, the component re-renders.
  • Data flows one way in React: parent to child through props. This is called unidirectional data flow.
  • A parent's state often becomes a child's props. This is how components communicate.

Common mistakes

  • Saying state is "global" data. State is local to the component that owns it unless you explicitly lift it up or use context.
  • Forgetting to mention that changing state triggers a re-render but changing props from the parent also causes the child to re-render.

Sample answer

Props are inputs that a parent component passes to a child. They are read-only inside the child, meaning the child cannot change them. State is data that a component owns and manages internally using useState. When state updates, React re-renders that component.

For example, a SearchPage component might hold a query string in its state, and pass the current results as props to a ResultsList child. When the user types a new query, SearchPage updates its state, which triggers a re-render, and ResultsList receives the new results through its props.

The key idea is that data flows downward: a parent's state becomes a child's props.

How to level up

  • Mention that if multiple sibling components need the same data, you should lift state up to their closest common parent rather than duplicating it.
  • Bring up the distinction between controlled and uncontrolled components as a practical example of the state vs props decision.
  • Note that while props are immutable in the child, callback functions passed as props let the child communicate changes back up to the parent.

Follow-up questions to expect

  • When would you lift state up versus use context or a state management library?
  • What is prop drilling and how do you avoid it?
  • What happens when a parent re-renders but the props passed to a child have not changed?
Practice this question with AI feedback →
What is state in React and how do you update it?
easy

What they're really asking

This tests whether you understand React's fundamental concept of state-driven UI updates and can explain the immutability requirement that trips up many developers.

How you'll be scored

Weak

Describes state as variables you can change directly or doesn't understand the asynchronous nature of state updates.

Average

Correctly explains state holds component data and mentions useState, but misses immutability requirements or batching behavior.

Strong

Demonstrates understanding of state as immutable data that triggers re-renders, explains proper update patterns, and shows awareness of React's batching behavior.

How to structure your answer

  1. Define what state represents in React components.
  2. Show how to declare state with useState hook.
  3. Explain the immutability requirement for state updates.
  4. Demonstrate proper update patterns for objects and arrays.
  5. Mention that state updates are asynchronous and batched.

Key points to hit

  • State represents data that can change over time and triggers component re-renders when updated.
  • Never mutate state directly; always create new objects or arrays when updating complex state.
  • State updates are asynchronous, so you can't immediately read the new value after calling setState.
  • React batches multiple state updates in event handlers for performance.

Common mistakes

  • Mutating state directly like users.push(newUser) instead of setUsers([...users, newUser])
  • Assuming state updates happen immediately and trying to use the new value in the same function.

Sample answer

State in React represents data that belongs to a component and can change over time. When state changes, React re-renders the component to reflect the new data. I use the useState hook to add state to functional components, which returns the current value and a setter function.

The key thing to remember is that state should never be mutated directly. For example, if I have an array of users, I can't do users.push(newUser). Instead, I need to create a new array like setUsers([...users, newUser]). State updates are also asynchronous, so React batches them for performance.

How to level up

  • Explain how functional state updates like setCount(prev => prev + 1) solve problems with stale closures.
  • Mention that React 18's automatic batching extends to timeouts and promises, not just event handlers.

Follow-up questions to expect

  • How would you update a nested object in state?
  • What's the difference between useState and useReducer for complex state?
  • Can you explain what happens when you call setState multiple times in the same function?
Practice this question with AI feedback →
What is the difference between controlled and uncontrolled components?
easy

What they're really asking

This tests understanding of React's data flow philosophy and whether you can identify when to let React manage form state versus handling it yourself with refs.

How you'll be scored

Weak

Confuses the concepts or can't explain when to use each approach in practical scenarios.

Average

Correctly defines both patterns but doesn't explain the trade-offs or when to choose each approach.

Strong

Clearly explains both patterns, demonstrates when to use each, and understands the implications for form validation and user experience.

How to structure your answer

  1. Define controlled components where React manages form state.
  2. Define uncontrolled components where DOM manages its own state.
  3. Show code examples of each pattern.
  4. Explain when to choose controlled vs uncontrolled.
  5. Discuss trade-offs like performance and validation capabilities.

Key points to hit

  • Controlled components have their value managed by React state, making React the single source of truth.
  • Uncontrolled components manage their own state internally and you access values through refs.
  • Controlled components enable real-time validation and dynamic behavior but require more code.
  • Uncontrolled components are simpler for basic forms but harder to validate or manipulate programmatically.

Common mistakes

  • Using defaultValue with controlled components instead of value, which creates a hybrid that React warns about.
  • Choosing uncontrolled components for complex forms where you need validation or conditional logic.

Sample answer

Controlled components have their form input values managed by React state, so the component controls what the user sees. I set the input's value prop to state and handle changes with onChange. Uncontrolled components manage their own state internally like regular DOM elements, and I access their values using refs.

I prefer controlled components when I need real-time validation or want to transform user input, like formatting a phone number as they type. I use uncontrolled components for simple forms where I just need the final values on submit, since they require less code and avoid unnecessary re-renders.

How to level up

  • Mention that React Hook Form uses uncontrolled components by default for better performance with large forms.
  • Explain how controlled components enable better accessibility by letting you programmatically focus or announce changes.

Follow-up questions to expect

  • How would you handle a form with dozens of inputs? Would you still use controlled components?
  • Can you show me how to implement real-time validation with controlled components?
  • What are the performance implications of controlled vs uncontrolled components?
Practice this question with AI feedback →
What is the purpose of the key prop in React? Why is it important in lists?
easy

What they're really asking

This tests whether you understand React's reconciliation algorithm and can explain how keys help React identify which list items have changed, moved, or been added or removed.

How you'll be scored

Weak

Thinks keys are just to avoid warnings or explains them incorrectly as performance optimizations without understanding identity.

Average

Correctly explains keys help React identify list items but doesn't connect to reconciliation or explain what makes a good key.

Strong

Demonstrates understanding of React's diffing algorithm, explains how keys preserve component identity, and knows what makes keys stable and unique.

How to structure your answer

  1. Explain React's need to track list items during re-renders.
  2. Describe how keys provide stable identity for reconciliation.
  3. Show what happens with and without proper keys.
  4. Explain characteristics of good keys (stable, unique)
  5. Connect to performance and user experience benefits.

Key points to hit

  • Keys help React's reconciliation algorithm identify which list items are the same across re-renders.
  • Without keys, React assumes list items correspond by position, which breaks when items move or are added/removed.
  • Good keys are stable (don't change between renders) and unique within the list.
  • Keys preserve component state and DOM focus when list items move around.

Common mistakes

  • Using array indices as keys when the list can be reordered, filtered, or have items added/removed.
  • Thinking keys are just to suppress React warnings rather than understanding their role in reconciliation.

Sample answer

The key prop helps React identify which items in a list are the same between re-renders. During reconciliation, React uses keys to figure out if a list item moved, was added, or was removed, rather than assuming items match by position.

Without keys, React might destroy and recreate components unnecessarily, losing component state and DOM focus. Good keys need to be stable and unique within the list.

For example, if I'm rendering a list of users, I'd use the user ID as the key rather than the array index, because the ID stays the same even if users get reordered or filtered.

How to level up

  • Explain how keys can prevent bugs with form inputs losing focus or checkboxes becoming unchecked when lists change.
  • Mention that keys only need to be unique among siblings, not globally unique across the entire application.

Follow-up questions to expect

  • What problems can occur if you use array index as keys?
  • How do you choose good keys when your data doesn't have natural IDs?
  • Can you show me an example where wrong keys cause a bug?
Practice this question with AI feedback →
What happens if you use array index as a key? What bugs can it cause?
medium

What they're really asking

This tests deeper understanding of React's reconciliation process and whether you can identify specific scenarios where index keys cause silent bugs that are hard to debug.

How you'll be scored

Weak

Says it causes performance issues without understanding the actual bugs or thinks index keys are always fine.

Average

Mentions that items might not update correctly but can't give specific examples of when this breaks.

Strong

Can describe specific scenarios like reordering, filtering, or form state where index keys cause components to maintain wrong state or lose user input.

How to structure your answer

  1. Explain why array indices seem convenient but are problematic.
  2. Describe what happens when list order changes with index keys.
  3. Give specific examples of bugs this causes.
  4. Show code demonstrating the problem.
  5. Explain the solution with stable keys.

Key points to hit

  • Array indices change when items are added, removed, or reordered, breaking React's ability to track component identity.
  • Components can retain state from the wrong list item when indices shift.
  • Form inputs can lose focus, become unchecked, or display wrong values when using index keys with dynamic lists.
  • The bug is silent and hard to debug because the UI appears to work until users interact with it in specific ways.

Common mistakes

  • Thinking index keys only cause performance problems rather than functional bugs.
  • Using index keys for lists that seem static but might become dynamic later.

Sample answer

Using array index as keys breaks React's reconciliation when list items move around. For example, imagine a todo list where each item has a checkbox and text input.

If I use index keys and the user deletes the first todo, React thinks the first component should now display the second todo's data, but it keeps the first component's DOM state. So if the first checkbox was checked, the second todo suddenly appears checked even though it shouldn't be.

The same thing happens with text inputs losing focus or displaying wrong values. React can't tell that components represent different data because the keys shifted when the array changed.

How to level up

  • Demonstrate with a code example showing how deleting the first item in a list with index keys causes the second item to inherit the first item's local state.
  • Explain how this becomes especially problematic in apps with user interactions like editing, selecting, or expanding list items.

Follow-up questions to expect

  • Can you show me a code example where index keys cause this bug?
  • How would you generate stable keys for a list that doesn't have natural IDs?
  • Are there any cases where using index as keys is actually acceptable?
Practice this question with AI feedback →
What are React Fragments and why are they used?
easy

What they're really asking

This tests whether you understand React's requirement for single root elements and how Fragments solve wrapper div pollution. The interviewer wants to see if you know why extra DOM nodes matter for styling and performance.

How you'll be scored

Weak

Cannot explain why Fragments exist or confuses them with regular div wrappers.

Average

Knows Fragments let you group children without adding extra DOM nodes.

Strong

Explains the DOM bloat problem, shows both <Fragment> and shorthand <> syntax, and mentions keyed Fragments for lists.

How to structure your answer

  1. Explain React's single root element requirement.
  2. Show how wrapper divs create DOM bloat problems.
  3. Introduce Fragments as the solution.
  4. Show both full and shorthand syntax.
  5. Mention keyed Fragments for lists.

Key points to hit

  • React components must return a single root element, which used to force unnecessary wrapper divs.
  • Fragments let you group multiple children without adding extra nodes to the DOM.
  • Shorthand syntax <> is the most common usage for simple grouping.
  • The full <Fragment key={id}> syntax is required when you need to pass a key prop in lists.

Common mistakes

  • Not knowing the difference between <> shorthand and <Fragment> with key support.
  • Thinking Fragments are just syntactic sugar with no real performance or layout benefit.

Sample answer

React Fragments solve a common problem. React requires every component to return a single root element, which used to mean wrapping sibling elements in a div. That creates unnecessary DOM nodes that can break CSS layouts like Flexbox or Grid and bloat the DOM tree. Fragments let you group children without adding any extra node to the DOM. I use the shorthand <> syntax most of the time. But when rendering lists, you need the full <Fragment key={id}> syntax because the shorthand doesn't support key props. It's a small thing that makes a real difference in keeping the DOM clean.

How to level up

  • Mention that Fragments are especially important inside table, list, and Flexbox/Grid layouts where extra divs break structure.
  • Discuss how Fragments reduce memory usage in large component trees by avoiding unnecessary DOM nodes.
  • Point out that React DevTools shows Fragment boundaries which helps with debugging component hierarchy.

Follow-up questions to expect

  • When would you need to use the full Fragment syntax instead of the shorthand?
  • Can you nest Fragments inside other Fragments?
  • What CSS layout issues can unnecessary wrapper divs cause?
Practice this question with AI feedback →
What are synthetic events in React?
medium

What they're really asking

This tests understanding of React's event system abstraction layer. The interviewer wants to see if you know why React wraps native browser events and what practical implications that has for cross-browser compatibility and event handling.

How you'll be scored

Weak

Cannot explain what synthetic events are or confuses them with native DOM events.

Average

Knows synthetic events are React's cross-browser wrapper around native events.

Strong

Explains the wrapper pattern, event pooling history, how to access native events, and performance implications of React's event delegation.

How to structure your answer

  1. Define synthetic events as React's cross-browser event wrapper.
  2. Explain why React uses this abstraction layer.
  3. Describe how event delegation works at the root.
  4. Mention accessing native events with e.nativeEvent.
  5. Note the removal of event pooling in React 17.

Key points to hit

  • SyntheticEvent is a cross-browser wrapper around the native browser event with the same interface.
  • React delegates all events to the root element instead of attaching handlers to individual DOM nodes.
  • You can access the underlying native event through e.nativeEvent when needed.
  • React 17 removed event pooling, so you no longer need to call e.persist() to use events asynchronously.

Common mistakes

  • Not knowing that event pooling was removed in React 17 and still suggesting e.persist() as current best practice.
  • Thinking synthetic events have a different API than native events, when they actually follow the same W3C spec interface.

Sample answer

Synthetic events are React's cross-browser wrapper around native DOM events. When you write onClick or onChange, React doesn't attach handlers to individual DOM nodes. Instead, it uses event delegation at the root container and wraps the native event in a SyntheticEvent object that follows the same W3C spec. This gives you consistent behavior across browsers.

If you need the real browser event, you can access it through e.nativeEvent. One thing that changed in React 17 is that event pooling was removed, so you no longer need to worry about calling e.persist() when using events in async callbacks or setTimeout.

How to level up

  • Mention that React 17 moved event delegation from document to the root container, which improved micro-frontend compatibility.
  • Discuss how stopPropagation on synthetic events works differently than native events since React uses delegation.
  • Explain that some events like scroll and focus don't bubble natively but React normalizes this behavior.

Follow-up questions to expect

  • How does React's event delegation improve performance compared to individual event listeners?
  • What changed about event delegation in React 17 and why?
  • When would you need to access the native event instead of the synthetic one?
Practice this question with AI feedback →
What is reconciliation in React?
medium

What they're really asking

This tests your understanding of how React determines what changed and what needs updating in the DOM. The interviewer wants to see if you know the algorithm React uses to efficiently update the UI after state changes.

How you'll be scored

Weak

Gives a vague answer about React updating the DOM without explaining the comparison process or heuristics.

Average

Correctly describes reconciliation as the diffing process between old and new Virtual DOM trees.

Strong

Explains the O(n) heuristic approach, the role of element types and keys, and how reconciliation connects to batching and commit phases.

How to structure your answer

  1. Define reconciliation as React's process for determining DOM updates.
  2. Explain the two heuristics React uses for diffing.
  3. Describe what happens when element types match versus differ.
  4. Explain the role of keys in list reconciliation.
  5. Connect to the render and commit phases.

Key points to hit

  • Reconciliation is the algorithm React uses to compare old and new element trees to determine minimal DOM changes.
  • React uses two heuristics: elements of different types produce different trees, and keys identify stable elements across renders.
  • When an element type changes, React destroys the old tree and builds a new one from scratch.
  • Keys help React identify which items in a list changed, moved, or were removed without comparing every element.

Common mistakes

  • Confusing reconciliation with rendering, when reconciliation is the diffing step that happens before DOM updates.
  • Not understanding that changing a parent element type causes React to unmount the entire subtree including child state.

Sample answer

Reconciliation is the process React uses to figure out the minimum number of DOM operations needed after a state change. When you update state, React renders a new element tree and compares it with the previous one. It relies on two key heuristics to keep this O(n) instead of O(n cubed).

First, if two elements have different types, React tears down the old subtree entirely and builds a new one. Second, developers provide key props to signal which items in a list are stable across renders. After the diffing phase identifies what changed, React batches the actual DOM mutations in the commit phase.

This two-phase approach is what makes React feel fast even with frequent updates.

How to level up

  • Discuss how React Fiber improved reconciliation by making it interruptible and allowing priority-based scheduling.
  • Mention that reconciliation is why you should keep component types stable and avoid creating components inside render functions.
  • Explain that React's concurrent features like useTransition give you control over reconciliation priority.

Follow-up questions to expect

  • What happens to child component state when a parent element type changes during reconciliation?
  • How do keys affect reconciliation performance in large lists?
  • What is the difference between the render phase and commit phase in reconciliation?
Practice this question with AI feedback →
What is React Fiber and what is its main goal?
hard

What they're really asking

This tests deep understanding of React's internal architecture rewrite and why incremental rendering matters. The interviewer wants to see if you grasp the limitations of the old stack reconciler and how Fiber enables concurrent features.

How you'll be scored

Weak

Cannot explain what Fiber is or confuses it with the Virtual DOM or general React concepts.

Average

Knows Fiber is React's reconciliation engine rewrite that enables incremental rendering.

Strong

Explains the unit of work concept, priority scheduling, interruptible rendering, and how Fiber enables concurrent features like useTransition and Suspense.

How to structure your answer

  1. Explain the problem with the old stack reconciler.
  2. Define Fiber as the new reconciliation architecture.
  3. Explain the unit of work and linked list structure.
  4. Describe how work can be paused, prioritized, and resumed.
  5. Connect to modern concurrent features it enables.

Key points to hit

  • The old stack reconciler processed the entire component tree synchronously, blocking the main thread during large updates.
  • Fiber represents each component as a unit of work that can be paused, aborted, or reused.
  • Fiber uses a linked list structure instead of a recursive call stack, making rendering interruptible.
  • This architecture enables concurrent features like time-slicing, Suspense, and useTransition.

Common mistakes

  • Thinking Fiber replaced the Virtual DOM, when Fiber is the reconciliation engine that processes the Virtual DOM.
  • Not connecting Fiber to practical features like concurrent rendering and being unable to explain why it matters to developers.

Sample answer

React Fiber is the complete rewrite of React's reconciliation engine, introduced in React 16. The old stack reconciler had a fundamental problem: it processed the entire component tree in a single synchronous pass, which meant large updates could block the main thread and make the UI unresponsive.

Fiber solves this by representing each component as a unit of work in a linked list structure instead of a recursive call stack. This means React can pause work on one component, handle a higher-priority update like user input, and then resume where it left off.

Each fiber node tracks its own state, effects, and priority level. This architecture is what makes modern concurrent features possible, including useTransition for deprioritizing expensive updates and Suspense for declarative loading states.

How to level up

  • Mention the double-buffering technique where Fiber maintains current and work-in-progress trees to enable seamless switching.
  • Discuss how Fiber's priority lanes system replaced the original expiration time model for more granular scheduling.
  • Explain that Fiber's interruptible rendering is why React separates the render phase (pure, can be interrupted) from the commit phase (synchronous, applies DOM changes)

Follow-up questions to expect

  • How does Fiber decide which updates to prioritize over others?
  • What is the difference between the current tree and work-in-progress tree in Fiber?
  • How does Fiber relate to React's concurrent mode and Suspense?
Practice this question with AI feedback →
What is the diffing algorithm in React?
hard

What they're really asking

This tests understanding of how React's tree comparison works under the hood and the specific heuristics that make it efficient. The interviewer wants to see if you can explain the algorithmic complexity and trade-offs React makes.

How you'll be scored

Weak

Vaguely mentions comparing trees without understanding the specific heuristics or complexity trade-offs.

Average

Correctly explains the element type and key heuristics that make diffing O(n).

Strong

Details all three comparison scenarios (different types, same DOM type, same component type), explains key-based list diffing, and discusses the trade-offs of these heuristics.

How to structure your answer

  1. State the algorithmic complexity problem and React's O(n) solution.
  2. Explain the element type heuristic.
  3. Explain how same-type elements are diffed for attributes.
  4. Describe key-based list reconciliation.
  5. Discuss the practical implications for developers.

Key points to hit

  • A generic tree diff algorithm is O(n cubed), but React uses heuristics to achieve O(n) by comparing nodes level by level.
  • Elements of different types trigger a full subtree rebuild, unmounting all child components and their state.
  • Same-type DOM elements only update the changed attributes, and same-type components trigger a re-render with new props.
  • Keys let React match children across renders for efficient list updates without comparing every possible pair.

Common mistakes

  • Not understanding that the O(n) complexity comes from deliberate trade-offs that work well in practice but are not theoretically optimal.
  • Forgetting that changing a root element type destroys all nested component state, which is a common source of bugs.

Sample answer

React's diffing algorithm compares two element trees to find the minimum changes needed. A generic tree diff is O(n cubed), which is way too slow for UI updates. React gets this down to O(n) using two assumptions. First, elements of different types produce completely different trees, so React doesn't try to match them.

It just tears down the old subtree and builds fresh. Second, keys on list items tell React which elements are the same across renders. When elements have the same type, React compares their attributes for DOM elements or passes new props for component elements.

For lists without keys, React compares by position, which breaks down when items are reordered or inserted. With keys, React can match moved items efficiently. These heuristics work well in practice because component types rarely change and lists usually have stable identifiers.

How to level up

  • Mention that React compares breadth-first by level, never comparing children of elements that differ in type.
  • Discuss how unstable keys (like Math.random) cause unnecessary unmounting and remounting, destroying state and hurting performance.
  • Explain that the diffing algorithm is why component identity matters and why you should never define components inside render functions.

Follow-up questions to expect

  • What are the practical consequences of React's assumption that different types produce different trees?
  • How does key-based diffing handle reordered items differently than index-based diffing?
  • Can you describe a scenario where React's diffing heuristics produce suboptimal results?
Practice this question with AI feedback →
Explain one-way data flow in React.
easy

What they're really asking

This tests understanding of React's core architectural principle and whether you can explain how data flows through component hierarchies. The interviewer wants to see if you grasp unidirectional data flow and can predict how changes propagate.

How you'll be scored

Weak

Vague explanation about data moving in one direction without connecting it to components, props, and state updates.

Average

Correctly explains that data flows from parent to child via props but doesn't connect it to predictable rendering.

Strong

Explains the parent-to-child flow with props, connects it to predictable updates and easier debugging, and contrasts with two-way binding.

How to structure your answer

  1. Define one-way data flow in React context.
  2. Explain how data moves from parent to child via props.
  3. Show how state changes trigger re-renders down the tree.
  4. Contrast with two-way data binding.
  5. Explain the benefits for predictability.

Key points to hit

  • Data flows from parent components to children through props, never the reverse.
  • State lives in components and gets passed down as props to children.
  • Children communicate back to parents through callback functions passed as props.
  • This makes data flow predictable and easier to debug than two-way binding.

Common mistakes

  • Confusing one-way data flow with the inability for children to communicate with parents.
  • Not explaining how callback functions enable upward communication while maintaining one-way flow.

Sample answer

One-way data flow means data in React moves in a single direction from parent components down to child components through props. When a parent component has state, it passes that data to children as props.

If a child needs to update that data, the parent passes down a callback function as a prop, and the child calls that function. This keeps the actual data flow unidirectional because the child isn't directly modifying parent state.

This pattern makes applications much more predictable because you always know where data is coming from and how it can change.

How to level up

  • Connect one-way flow to React's reconciliation algorithm and how it enables efficient diffing.
  • Explain how this principle influences state management patterns like Redux and Context API.

Follow-up questions to expect

  • How do you handle communication between sibling components?
  • What happens if you try to modify props directly in a child component?
  • How does one-way data flow relate to React's rendering performance?
Practice this question with AI feedback →
What is prop drilling? How do you avoid it?
medium

What they're really asking

This tests whether you recognize a common architectural problem in React applications and know multiple solutions. The interviewer wants to see practical experience with component composition and state management patterns.

How you'll be scored

Weak

Can't clearly explain what prop drilling is or suggests only basic solutions like lifting state up.

Average

Explains prop drilling correctly and mentions Context API as a solution but lacks depth on when to use different approaches.

Strong

Explains the problem clearly, provides multiple solutions with trade-offs, and shows judgment about when to use each approach.

How to structure your answer

  1. Define prop drilling with a concrete example.
  2. Explain why it becomes problematic.
  3. Present Context API as the primary solution.
  4. Mention component composition patterns.
  5. Discuss when each solution is appropriate.

Key points to hit

  • Prop drilling occurs when you pass props through multiple component layers just to reach a deeply nested child.
  • Use React Context API to share data across components without passing through intermediates.
  • Component composition with children prop can eliminate some prop drilling cases.
  • Consider if the drilling is actually a problem before adding complexity with Context.

Common mistakes

  • Reaching for Context API too early when simple prop passing would suffice.
  • Not considering component composition patterns that can reduce the need for shared state.

Sample answer

Prop drilling happens when you need to pass data through several component layers to reach a deeply nested component that actually needs it. For example, passing user data from App through Header, Navigation, and UserMenu just to display the username. This creates tight coupling and makes components harder to reuse.

The main solution is React Context API, where you create a context provider near the top of your tree and consume it directly in the components that need the data. You can also use component composition, passing components as children props to avoid some drilling scenarios.

I typically only use Context when I'm passing the same props through three or more levels.

How to level up

  • Combine Context with useReducer for complex state that multiple components need to modify.
  • Consider splitting contexts by concern rather than having one large context to minimize re-renders.

Follow-up questions to expect

  • How do you handle performance issues with Context API?
  • When would you choose a state management library over Context?
  • How do you decide between lifting state up versus using Context?
Practice this question with AI feedback →
Why does React recommend against mutating state?
medium

What they're really asking

This tests fundamental understanding of React's reconciliation process and immutability principles. The interviewer wants to see if you understand how React detects changes and can write bug-free state updates.

How you'll be scored

Weak

Mentions immutability but can't explain how React detects changes or why mutations cause bugs.

Average

Explains that React uses reference equality to detect changes but lacks specific examples of problems mutations cause.

Strong

Explains reference equality checks, provides examples of mutation bugs, and shows correct patterns for updating nested state.

How to structure your answer

  1. Explain how React detects state changes using reference equality.
  2. Show what happens when you mutate state directly.
  3. Provide examples of mutation bugs.
  4. Demonstrate correct patterns for state updates.
  5. Connect to React's rendering optimization.

Key points to hit

  • React uses Object.is comparison to detect state changes, so mutating an object won't trigger re-renders.
  • Mutations can cause components to not update even when the underlying data changes.
  • Always create new objects or arrays when updating state, using spread operators or methods like concat.
  • React.memo and other optimizations rely on reference equality, so mutations break performance optimizations.

Common mistakes

  • Mutating nested objects or arrays and expecting React to detect the change.
  • Using array methods like push() or sort() that modify the original array instead of returning a new one.

Sample answer

React recommends against mutating state because it uses reference equality to detect when state has changed. When you mutate an object or array directly, the reference stays the same, so React thinks nothing changed and won't re-render your component. This leads to bugs where your UI doesn't reflect the actual data.

Instead, you should create new objects using spread syntax like setState({...state, name: 'new name'}) or for arrays use methods like concat() instead of push(). This also ensures that performance optimizations like React.memo work correctly since they rely on comparing references to determine if a component should re-render.

How to level up

  • Use libraries like Immer for complex nested state updates while maintaining immutability.
  • Understand that mutation bugs are often silent and hard to debug, making immutability a defensive programming practice.

Follow-up questions to expect

  • How would you update a deeply nested object in state?
  • What are the performance implications of always creating new objects?
  • How does immutability relate to React's concurrent features?
Practice this question with AI feedback →
What is the difference between React and ReactDOM? Why are they separated?
medium

What they're really asking

This tests understanding of React's modular architecture and platform abstraction. The interviewer wants to see if you understand how React separates core logic from rendering targets.

How you'll be scored

Weak

Can't explain the difference or thinks they're the same thing with different names.

Average

Knows React is the core library and ReactDOM handles browser rendering but lacks depth on why they're separate.

Strong

Explains the separation enables multiple rendering targets, understands the reconciler pattern, and can name other renderers.

How to structure your answer

  1. Define React as the core component and reconciliation library.
  2. Explain ReactDOM as the browser-specific renderer.
  3. Discuss why separation enables multiple platforms.
  4. Mention other renderers like React Native.
  5. Connect to React's architecture philosophy.

Key points to hit

  • React contains the core component logic, hooks, and reconciliation algorithm that's platform-agnostic.
  • ReactDOM handles browser-specific rendering, DOM manipulation, and event handling.
  • This separation allows React's component model to work on different platforms like mobile with React Native.
  • ReactDOM provides methods like render(), createRoot(), and unmountComponentAtNode() for browser integration.

Common mistakes

  • Thinking ReactDOM is just an older version of React.
  • Not understanding that React itself doesn't know anything about the DOM.

Sample answer

React is the core library that handles components, hooks, state management, and the reconciliation algorithm that figures out what needs to update. ReactDOM is a separate package that handles actually rendering React components to the browser DOM and managing browser-specific concerns like events.

They're separated because React's component model and reconciliation logic can work on different platforms. The same React core powers React Native for mobile apps, React VR for virtual reality, and even server-side rendering. ReactDOM specifically provides the bridge between React's virtual representation and the actual browser DOM, with methods like createRoot() to mount your app.

How to level up

  • Understand that other renderers like react-three-fiber use the same React core but render to WebGL instead of DOM.
  • The separation follows the pattern where React is the reconciler and different packages are renderers for specific platforms.

Follow-up questions to expect

  • How does server-side rendering fit into this separation?
  • What's the difference between ReactDOM.render() and ReactDOM.createRoot()?
  • How would you create a custom React renderer?
Practice this question with AI feedback →
What is the children prop in React?
easy

What they're really asking

This tests understanding of React's component composition model and how props enable flexible, reusable components. The interviewer wants to see if you grasp composition patterns that make components more flexible.

How you'll be scored

Weak

Can't explain what children prop is or how it differs from regular props.

Average

Knows children contains nested elements but doesn't explain the composition benefits or flexibility it provides.

Strong

Explains children as a composition tool, shows how it enables flexible component design, and understands it can contain any valid React element.

How to structure your answer

  1. Define children as a special prop containing nested elements.
  2. Show how it enables component composition.
  3. Provide a practical example of a wrapper component.
  4. Explain the flexibility benefits.
  5. Mention that children can be any React element type.

Key points to hit

  • The children prop automatically contains any elements nested between a component's opening and closing tags.
  • It enables composition patterns where parent components wrap and enhance child content without knowing what that content is.
  • Children can be React elements, strings, numbers, arrays, or even functions for render prop patterns.
  • This pattern makes components more reusable because they can work with any nested content.

Common mistakes

  • Thinking children is just for text content when it can contain any React elements.
  • Not recognizing children as a key pattern for building flexible, reusable wrapper components.

Sample answer

The children prop is a special prop that automatically receives whatever you nest between a component's opening and closing tags. It's React's way of enabling composition where a parent component can wrap and enhance child content without knowing what that content is.

For example, if I build a Card component, I can use children to let any content be placed inside it: the Card handles styling and layout while children provides the actual content. This makes components much more flexible and reusable because they don't need to know about their content ahead of time.

Children can be text, other components, arrays of elements, or even functions.

How to level up

  • Use React.Children utilities to manipulate or validate children props when building flexible wrapper components.
  • Children prop enables the render prop pattern where children is a function that receives data from the parent.

Follow-up questions to expect

  • How would you validate or manipulate the children prop?
  • What's the difference between children and render props?
  • How do you handle cases where children might be undefined?
Practice this question with AI feedback →
Why should component names start with a capital letter?
easy

What they're really asking

This tests understanding of how React distinguishes between HTML elements and custom components during JSX compilation. The interviewer wants to see if you understand the technical reason behind the naming convention.

How you'll be scored

Weak

Says it's just a convention or coding standard without understanding the technical reason.

Average

Knows that lowercase names are treated as HTML elements and uppercase as components.

Strong

Explains how JSX compilation handles the distinction, shows what breaks with lowercase component names, and mentions the dot notation workaround.

How to structure your answer

  1. Explain how JSX compilation distinguishes elements from components.
  2. Show what happens when you use a lowercase component name.
  3. Demonstrate the difference in compiled output.
  4. Mention the dot notation exception for namespaced components.

Key points to hit

  • JSX treats lowercase tags as HTML elements and compiles them to string arguments in createElement.
  • Uppercase tags are treated as component references and compiled to variable references in createElement.
  • Using a lowercase name for a custom component will render an HTML element instead of your component.
  • Dot notation like MyLibrary.Button works for lowercase after the dot because the root is uppercase.

Common mistakes

  • Thinking it's purely a style convention rather than a technical requirement that affects JSX compilation.
  • Not knowing that dot notation provides an exception for component libraries with namespaced exports.

Sample answer

This isn't just a style convention. It's a technical requirement for how JSX compiles. When Babel or TypeScript sees a lowercase tag like
, it compiles to React.createElement('div'), passing the tag name as a string. But when it sees an uppercase tag like <Button>, it compiles to React.createElement(Button), passing the actual component reference as a variable. So if you name your component button with a lowercase b, React will try to render an HTML button element instead of your custom component. There is one exception: dot notation works, so something like <UI.button> would work because the compiler sees UI as the variable reference. But in general, always capitalize your component names.

How to level up

  • Mention that this behavior is defined in the JSX specification and affects all JSX transpilers, not just React.
  • Discuss how this relates to tree-shaking since uppercase components are variable references that bundlers can track.
  • Point out that this is why you sometimes need to assign a dynamic component to a capitalized variable before using it in JSX.

Follow-up questions to expect

  • How would you render a component whose name is stored in a variable?
  • What is dot notation syntax in JSX and when would you use it?
  • What happens if you try to use a lowercase name for a custom component?
Practice this question with AI feedback →
What is the difference between createElement and cloneElement?
medium

What they're really asking

This tests understanding of React's element creation APIs and when you would need to clone versus create elements. The interviewer wants to see if you understand the use cases for each and how cloneElement enables component composition patterns.

How you'll be scored

Weak

Cannot differentiate the two or has never used cloneElement.

Average

Correctly explains createElement creates new elements and cloneElement copies existing ones with merged props.

Strong

Explains both APIs, shows practical use cases for cloneElement in component libraries, and mentions that modern patterns often prefer render props or hooks over cloneElement.

How to structure your answer

  1. Define createElement and what JSX compiles to.
  2. Define cloneElement and how it copies elements with merged props.
  3. Show practical use cases for cloneElement.
  4. Mention modern alternatives like render props and hooks.

Key points to hit

  • createElement creates a new React element with a given type, props, and children. JSX is syntactic sugar for this.
  • cloneElement takes an existing element, copies it, and lets you merge in additional props or override existing ones.
  • cloneElement preserves the original element's key and ref by default unless you explicitly override them.
  • Modern React often prefers render props, hooks, or Context over cloneElement for prop injection patterns.

Common mistakes

  • Thinking cloneElement does a deep clone of the component tree when it actually creates a shallow copy of a single element.
  • Not knowing that cloneElement is often considered a legacy pattern and that hooks or render props are preferred in new code.

Sample answer

createElement is the core function behind JSX. When you write <Button color="blue" />, it compiles to React.createElement(Button, {color: 'blue'}). It creates a brand new React element from scratch. cloneElement is different. It takes an existing React element and creates a copy of it, letting you merge in new props or override existing ones.

For example, React.cloneElement(child, {onClick: handleClick}) adds an onClick handler to whatever element child is. This was popular in component libraries for injecting props into children you don't control. But in modern React, this pattern has fallen out of favor. Hooks and render props give you cleaner composition without the implicit prop merging that cloneElement does.

How to level up

  • Mention that cloneElement is still useful in some component library patterns like Tabs or Accordion components that need to inject active state into children.
  • Discuss how React.Children.map combined with cloneElement was the classic pattern for iterating and enhancing children.
  • Point out that the React team has discussed deprecating cloneElement in future versions in favor of composition patterns.

Follow-up questions to expect

  • When would cloneElement be preferred over passing render props?
  • How does cloneElement handle ref forwarding on the cloned element?
  • What are the downsides of using cloneElement for prop injection?
Practice this question with AI feedback →
What are Pure Components in React?
medium

What they're really asking

This tests understanding of render optimization techniques and shallow comparison concepts. The interviewer wants to see if you know how Pure Components prevent unnecessary re-renders and what their limitations are.

How you'll be scored

Weak

Confuses Pure Components with pure functions or cannot explain the shallow comparison mechanism.

Average

Knows PureComponent does a shallow prop and state comparison to skip unnecessary re-renders.

Strong

Explains shallow comparison behavior, its limitations with nested objects, the functional equivalent with React.memo, and when pure components actually help versus when they add overhead.

How to structure your answer

  1. Define PureComponent and its automatic shouldComponentUpdate implementation.
  2. Explain how shallow comparison works for props and state.
  3. Show the functional component equivalent with React.memo.
  4. Discuss limitations with nested objects and arrays.
  5. Explain when Pure Components help versus when they add overhead.

Key points to hit

  • PureComponent implements shouldComponentUpdate with a shallow comparison of props and state.
  • Shallow comparison checks reference equality for objects and arrays, not deep structural equality.
  • React.memo is the functional component equivalent that wraps a component to skip re-renders with same props.
  • Pure Components can cause bugs if you mutate objects or arrays in place instead of creating new references.

Common mistakes

  • Assuming Pure Components are always better, when the shallow comparison itself has a cost and can be wasteful for components that almost always re-render.
  • Not understanding that shallow comparison fails to detect changes inside nested objects or mutated arrays.

Sample answer

In class components, PureComponent is a base class that automatically implements shouldComponentUpdate with a shallow comparison of props and state. If nothing changed by reference, it skips the re-render. For functional components, the equivalent is wrapping your component with React.memo. The key thing to understand is that the comparison is shallow.

It checks if each prop reference is the same, not if the contents are the same. So if you pass an object like {name: 'Dan'} as a prop and recreate it every render, PureComponent sees a new reference and re-renders anyway.

And if you mutate an array with push instead of creating a new array with spread, PureComponent misses the change entirely. They work best when props are primitives or stable references.

How to level up

  • Mention that React.memo accepts a custom comparison function as a second argument for more control than shallow comparison.
  • Discuss how useMemo and useCallback in parent components help ensure stable references for Pure Component children.
  • Point out that the React Profiler can help identify whether Pure Components are actually reducing renders in your specific case.

Follow-up questions to expect

  • How does shallow comparison handle nested objects differently than deep comparison?
  • When would React.memo with a custom comparison function be useful?
  • What happens if you mutate state directly in a PureComponent?
Practice this question with AI feedback →
What does re-rendering mean in React? What triggers a re-render?
medium

What they're really asking

This tests understanding of React's render cycle and the specific conditions that cause components to update. The interviewer wants to see if you can list all re-render triggers and explain the difference between rendering and DOM updates.

How you'll be scored

Weak

Thinks re-rendering means the DOM is always updated or can only name setState as a trigger.

Average

Lists the main triggers: state changes, prop changes, and parent re-renders.

Strong

Explains all triggers including context changes and forceUpdate, distinguishes rendering from DOM commits, and discusses how React batches re-renders for performance.

How to structure your answer

  1. Define what re-rendering means in React's execution model.
  2. List all triggers that cause a re-render.
  3. Explain that rendering does not always mean DOM updates.
  4. Discuss how React batches multiple re-renders.
  5. Mention optimization techniques to reduce unnecessary re-renders.

Key points to hit

  • Re-rendering means React calls your component function again to get a new element tree describing the current UI.
  • Triggers include setState/useState updates, new props from parent, context value changes, parent re-rendering, and forceUpdate.
  • A re-render does not mean the DOM changes. React compares the new tree with the previous one and only updates what differs.
  • React 18 automatically batches multiple state updates into a single re-render for better performance.

Common mistakes

  • Confusing re-rendering with DOM manipulation. Re-rendering is the virtual step. DOM updates happen only if the diff finds changes.
  • Not knowing that a parent re-rendering causes all children to re-render by default, even if their props haven't changed.

Sample answer

Re-rendering in React means calling your component function again to produce a new element tree. It does not mean the DOM is updated. React compares the new tree with the previous one and only commits actual DOM changes where differences exist. Several things trigger re-renders. The most obvious is calling setState or a useState setter.

But a component also re-renders when its parent re-renders, even if its own props haven't changed. Context value changes trigger re-renders for all consumers. And in class components, forceUpdate bypasses shouldComponentUpdate entirely.

React 18 improved this by automatically batching multiple state updates in event handlers, promises, and timeouts into a single re-render, which was previously only batched in event handlers.

How to level up

  • Mention that you can use React.memo to prevent child re-renders when props are unchanged, breaking the parent re-render cascade.
  • Discuss how the React Profiler and why-did-you-render library help identify unnecessary re-renders in development.
  • Explain that concurrent features like useTransition let you mark some re-renders as lower priority so they don't block user interactions.

Follow-up questions to expect

  • How do you prevent a child from re-rendering when its parent re-renders?
  • What is the difference between a render and a commit in React?
  • How does React 18 automatic batching differ from React 17 batching?
Practice this question with AI feedback →
What is the difference between re-render and re-mount?
medium

What they're really asking

This tests understanding of React's component lifecycle and the critical distinction between updating a component in place versus destroying and recreating it. The interviewer wants to see if you can explain when each happens and the state implications.

How you'll be scored

Weak

Uses the terms interchangeably or cannot explain what happens to component state in each case.

Average

Knows re-render updates the component while re-mount destroys and recreates it.

Strong

Explains when each occurs based on element type and key changes, describes the state and effect cleanup implications, and shows how keys can force remounting.

How to structure your answer

  1. Define re-render as updating a component in place.
  2. Define re-mount as destroying and recreating a component from scratch.
  3. Explain what triggers each behavior during reconciliation.
  4. Describe the state and lifecycle implications of each.
  5. Show how keys can be used to intentionally force remounting.

Key points to hit

  • Re-render calls the component function again but preserves state, refs, and DOM nodes.
  • Re-mount completely destroys the component instance, runs cleanup effects, then creates a fresh instance with initial state.
  • Re-mounting happens when the element type changes at the same position or when the key prop changes.
  • You can use key changes to intentionally reset a component's state without writing manual reset logic.

Common mistakes

  • Not understanding that re-mounting destroys all child component state in the entire subtree, not just the changed component.
  • Thinking re-mounting only happens with explicit unmount/mount cycles rather than during normal reconciliation.

Sample answer

Re-render and re-mount are fundamentally different. A re-render calls your component function again with updated props or state, but React preserves the component instance, its state, refs, and the existing DOM nodes. Only the parts that changed in the output get applied to the DOM. A re-mount is completely different.

React destroys the entire component instance, runs all cleanup functions from useEffect, removes the DOM nodes, then creates a brand new instance with fresh initial state. This happens in two situations: when the element type at a given position changes, like swapping a div for a span, or when the key prop changes.

This is actually useful. If you have a form component and want to reset it when the user ID changes, you can pass the user ID as a key. React will unmount the old form and mount a fresh one with clean state.

How to level up

  • Discuss how defining components inside render functions causes remounting on every render because the function reference changes each time.
  • Mention that re-mounting is expensive and should be avoided for performance-critical components, but is the correct behavior when you need a true reset.
  • Explain that the React DevTools Profiler shows mount versus update to help distinguish these behaviors during debugging.

Follow-up questions to expect

  • How can you use key props to intentionally reset component state?
  • What happens to child component state when a parent changes type during reconciliation?
  • Why is defining components inside other components a performance problem?
Practice this question with AI feedback →
Why can't browsers read JSX directly?
easy

What they're really asking

This tests your understanding of how JSX transpilation works and why React needs a build step. The interviewer wants to see if you grasp the fundamental difference between JSX syntax and native JavaScript.

How you'll be scored

Weak

Gives vague answer about JSX being 'special syntax' without explaining transpilation or what browsers actually understand.

Average

Correctly explains JSX needs to be transpiled to JavaScript but lacks detail about the transformation process.

Strong

Explains JSX transpilation, shows what JSX becomes after transformation, and understands the role of tools like Babel in the build process.

How to structure your answer

  1. Explain what JSX is syntactically.
  2. Describe what browsers can actually parse and execute.
  3. Explain the transpilation process.
  4. Mention the tools that handle this transformation.

Key points to hit

  • JSX is syntactic sugar that looks like HTML but isn't valid JavaScript syntax.
  • Browsers only understand standard JavaScript, HTML, and CSS.
  • JSX gets transpiled to React.createElement() calls during the build process.
  • Tools like Babel handle the transformation from JSX to browser-compatible JavaScript.

Common mistakes

  • Saying JSX is HTML or that it runs directly in browsers.
  • Not mentioning the build step or transpilation process.

Sample answer

Browsers can't read JSX directly because JSX isn't valid JavaScript syntax. When I write something like
Hello
, that looks like HTML but it's actually syntactic sugar that needs to be transformed. During the build process, tools like Babel transpile JSX into React.createElement() calls, so
Hello
becomes React.createElement('div', null, 'Hello'). The browser then receives standard JavaScript that it can execute normally.

How to level up

  • Explain the specific transformation showing before and after code.
  • Mention newer JSX transform that doesn't require importing React.
  • Discuss how TypeScript can also handle JSX transpilation.

Follow-up questions to expect

  • Can you show me what this JSX compiles to: <MyComponent prop={value} />?
  • What's the difference between the classic and automatic JSX transforms?
  • How would you set up JSX transpilation in a project without Create React App?
Practice this question with AI feedback →
What is the difference between Shadow DOM and Virtual DOM?
medium

What they're really asking

This tests whether you understand the distinction between two similar-sounding but completely different DOM technologies. The interviewer wants to see if you can clearly differentiate React's rendering strategy from web components.

How you'll be scored

Weak

Confuses the two concepts or gives incorrect definitions of either Virtual DOM or Shadow DOM.

Average

Correctly identifies that Virtual DOM is React-specific and Shadow DOM is a web standard but lacks depth on their purposes.

Strong

Clearly explains both concepts, their different use cases, and demonstrates understanding of when you'd use each technology.

How to structure your answer

  1. Define Virtual DOM and its purpose in React.
  2. Define Shadow DOM and its purpose in web components.
  3. Explain the key differences in what problems they solve.
  4. Mention when you'd use each one.

Key points to hit

  • Virtual DOM is React's in-memory representation for efficient diffing and updates.
  • Shadow DOM is a web standard for style and markup encapsulation.
  • Virtual DOM is about performance optimization, Shadow DOM is about component isolation.
  • They can be used together but serve completely different purposes.

Common mistakes

  • Thinking they're the same thing or that Shadow DOM is part of React.
  • Not understanding that Shadow DOM is about encapsulation, not performance.

Sample answer

Virtual DOM and Shadow DOM solve completely different problems. Virtual DOM is React's in-memory representation of the real DOM that enables efficient diffing and batched updates for better performance. Shadow DOM is a web standard that creates isolated DOM subtrees with encapsulated styles, like what you see in HTML elements such as video controls.

Virtual DOM is about optimizing renders, while Shadow DOM is about preventing style conflicts. You could actually use both together if you're building React components that need style isolation.

How to level up

  • Explain how React's reconciliation algorithm uses the Virtual DOM.
  • Discuss how Shadow DOM enables true CSS encapsulation unlike CSS modules.
  • Mention that React doesn't use Shadow DOM by default but can work with it.

Follow-up questions to expect

  • How does React's reconciliation process work with the Virtual DOM?
  • Can you use Shadow DOM inside React components?
  • What are the performance implications of Virtual DOM diffing?
Practice this question with AI feedback →
What are default props? How do you set them?
easy

What they're really asking

This tests your knowledge of React's prop system and how to handle component defaults. The interviewer wants to see if you understand both the old class-based approach and modern functional component patterns.

How you'll be scored

Weak

Only knows one approach or gives incorrect syntax for setting default props.

Average

Shows the basic defaultProps pattern but doesn't mention modern alternatives like destructuring defaults.

Strong

Demonstrates multiple approaches including defaultProps, destructuring defaults, and explains the trade-offs between them.

How to structure your answer

  1. Define what default props are and why they're useful.
  2. Show the classic defaultProps approach.
  3. Show modern destructuring default parameters.
  4. Explain when to use each approach.

Key points to hit

  • Default props provide fallback values when props aren't passed or are undefined.
  • Classic approach uses Component.defaultProps = {} after component definition.
  • Modern approach uses destructuring with defaults in the parameter list.
  • Destructuring defaults work immediately in the function signature and are more explicit.

Common mistakes

  • Forgetting that defaultProps only triggers for undefined props, not null props.
  • Not knowing the modern destructuring approach for functional components.

Sample answer

Default props provide fallback values when props aren't passed to a component. In class components, I set them using Component.defaultProps = {}, but in functional components, I prefer using destructuring defaults directly in the parameters like function MyComponent({title = 'Default Title', count = 0}).

The destructuring approach is more explicit and works immediately in the function signature. Both approaches only apply when props are undefined, not when they're explicitly passed as null.

How to level up

  • Explain the difference in behavior between undefined and null props.
  • Show how TypeScript interfaces can define optional props with defaults.
  • Discuss performance implications of object creation in defaultProps vs destructuring.

Follow-up questions to expect

  • What happens if you pass null vs undefined for a prop with a default value?
  • How do default props work with TypeScript?
  • Can you show how to set default props for nested object props?
Practice this question with AI feedback →
How does React handle event handling differently from HTML?
easy

What they're really asking

This tests your understanding of React's SyntheticEvent system and event delegation. The interviewer wants to see if you grasp how React optimizes event handling and provides cross-browser consistency.

How you'll be scored

Weak

Thinks React events work exactly like HTML events or doesn't understand SyntheticEvent.

Average

Mentions SyntheticEvent and cross-browser compatibility but lacks detail about event delegation.

Strong

Explains SyntheticEvent, event delegation, cross-browser normalization, and understands the performance benefits.

How to structure your answer

  1. Explain React's SyntheticEvent system.
  2. Describe event delegation and where listeners are attached.
  3. Mention cross-browser normalization benefits.
  4. Explain performance advantages.

Key points to hit

  • React uses SyntheticEvent objects that wrap native events for consistency.
  • Event delegation attaches listeners to the root element, not individual elements.
  • SyntheticEvents provide the same API across all browsers.
  • Event pooling was used in older React versions for performance but was removed in React 17.

Common mistakes

  • Not understanding that React doesn't attach event listeners to individual DOM elements.
  • Thinking you always need to call preventDefault() or stopPropagation() differently than in HTML.

Sample answer

React wraps native events in SyntheticEvent objects to provide cross-browser consistency and better performance. Instead of attaching event listeners to individual DOM elements like HTML, React uses event delegation and attaches a single listener to the root of your application. When events bubble up, React determines which component should handle them.

SyntheticEvents have the same API as native events, including preventDefault() and stopPropagation(), but they work consistently across all browsers without needing polyfills.

How to level up

  • Explain the changes in React 17 where event delegation moved from document to root container.
  • Discuss how to access the native event using nativeEvent property when needed.
  • Mention that event pooling was removed in React 17 for better developer experience.

Follow-up questions to expect

  • How can you access the native event object if you need it?
  • What changed about React's event system in React 17?
  • When would you need to use addEventListener directly instead of React events?
Practice this question with AI feedback →

Hooks Questions (30)

What are React Hooks? Why were they introduced?
easy

What they're really asking

This tests your understanding of React's evolution from class components to functional components and the fundamental shift in how we write React. The interviewer wants to see if you grasp the benefits hooks provide for logic reuse and component simplicity.

How you'll be scored

Weak

Gives vague explanation about hooks being 'new features' without understanding the problems they solve.

Average

Correctly explains hooks let you use state in functional components but misses the logic reuse benefits.

Strong

Explains hooks enable state and lifecycle in functional components, solve logic reuse problems, and understand the shift away from complex class hierarchies.

How to structure your answer

  1. Define what hooks are syntactically.
  2. Explain the problems with class components they solve.
  3. Describe the key benefits for logic reuse and simplicity.
  4. Mention the most common hooks and their purposes.

Key points to hit

  • Hooks are functions that let you use state and other React features in functional components.
  • They solve problems with complex class components, confusing lifecycle methods, and hard-to-reuse stateful logic.
  • Custom hooks enable easy sharing of stateful logic between components.
  • useState and useEffect are the most fundamental hooks that replace class state and lifecycle methods.

Common mistakes

  • Thinking hooks are just about adding state to functional components without understanding the broader benefits.
  • Not mentioning the logic reuse problem that higher-order components and render props couldn't solve elegantly.

Sample answer

React Hooks are functions that let you use state and other React features inside functional components. They were introduced to solve several problems with class components: confusing lifecycle methods, difficulty reusing stateful logic between components, and complex component hierarchies.

With hooks like useState and useEffect, I can handle state and side effects in functional components more intuitively. The biggest advantage is custom hooks, which let me extract and share stateful logic between components in a way that's much cleaner than higher-order components or render props.

How to level up

  • Explain the rules of hooks and why they exist (consistent call order)
  • Discuss how hooks compose better than mixins or higher-order components.
  • Mention that hooks enable better code splitting and tree shaking.

Follow-up questions to expect

  • What are the rules of hooks and why do they exist?
  • How would you create a custom hook for data fetching?
  • What problems did hooks solve that higher-order components couldn't?
Practice this question with AI feedback →
What are the rules of Hooks and why are they important?
easy

What they're really asking

This tests understanding of Hook constraints and React's rendering model. The interviewer wants to see if you grasp why these rules prevent bugs and enable React's optimization strategies.

How you'll be scored

Weak

Lists rules without explaining why they exist or how they prevent bugs.

Average

States the rules correctly and gives a basic explanation about React tracking state.

Strong

Explains rules, connects them to React's fiber reconciliation, and describes specific bugs that violate them.

How to structure your answer

  1. State the two main rules clearly.
  2. Explain why React needs these constraints.
  3. Connect to React's internal tracking mechanism.
  4. Give example of what breaks when violated.
  5. Mention ESLint plugin for enforcement.

Key points to hit

  • Only call Hooks at the top level, never inside loops or conditions.
  • Only call Hooks from React functions, not regular JavaScript functions.
  • Rules ensure consistent Hook order across renders for React's internal array-based tracking.
  • eslint-plugin-react-hooks catches most violations automatically.

Common mistakes

  • Thinking rules are arbitrary rather than fundamental to how React tracks state.
  • Not connecting rules to practical debugging scenarios.

Sample answer

The rules of Hooks are: only call them at the top level of your component, never inside loops, conditions, or nested functions, and only call them from React function components or custom hooks. These rules exist because React relies on the order of Hook calls to track state between renders.

React uses an internal array where each Hook call corresponds to an index. If you call useState conditionally, that index gets out of sync and you'll get the wrong state values or bugs that are really hard to debug. The ESLint plugin catches these violations, so I always make sure that's enabled in my projects.

How to level up

  • Explain how React's fiber reconciliation uses Hook call order for state persistence.
  • Describe how custom hooks follow the same rules and enable logic reuse.
  • Mention that the rules enable React DevTools to properly track Hook state.

Follow-up questions to expect

  • What happens internally when you break the rules of Hooks?
  • How would you refactor conditional logic that violates Hook rules?
  • Why can't you use Hooks inside class components?
Practice this question with AI feedback →
How does the useState hook work?
easy

What they're really asking

This tests basic React state management understanding. The interviewer wants to see if you know how useState manages component re-renders and state updates.

How you'll be scored

Weak

Vague explanation that doesn't mention the array return or state update triggering re-renders.

Average

Correctly explains useState returns an array with current value and setter function.

Strong

Explains useState mechanics, mentions state updates trigger re-renders, and covers functional updates for complex state changes.

How to structure your answer

  1. Explain what useState returns.
  2. Describe how state updates trigger re-renders.
  3. Show basic usage example.
  4. Explain functional updates for complex scenarios.
  5. Mention batching behavior.

Key points to hit

  • useState returns an array with current state value and setter function.
  • Calling the setter function triggers a component re-render with new state.
  • State updates are batched in event handlers for performance.
  • Use functional updates when new state depends on previous state to avoid stale closures.

Common mistakes

  • Not understanding that state updates are asynchronous and batched.
  • Using stale state values in closures instead of functional updates.

Sample answer

useState is a Hook that lets you add state to functional components. It returns an array with two elements: the current state value and a function to update it. When you call the setter function, React schedules a re-render with the new state value.

The key thing to remember is that state updates are asynchronous and React batches them for performance. If you need to update state based on the previous value, like incrementing a counter, use the functional form like setCount(prev => prev + 1) to avoid stale closure bugs.

How to level up

  • Explain how React 18's automatic batching works across async operations.
  • Describe when to use multiple useState calls vs. single state object.
  • Mention Object.is comparison for determining when to re-render.

Follow-up questions to expect

  • When would you use multiple useState calls vs a single state object?
  • How does React determine if state has actually changed?
  • What happens if you call setState with the same value?
Practice this question with AI feedback →
What is useEffect and what is the role of its dependency array?
easy

What they're really asking

This tests understanding of side effects and component lifecycle in functional components. The interviewer wants to see if you can manage effects correctly without introducing memory leaks or infinite loops.

How you'll be scored

Weak

Basic explanation without understanding dependency array or cleanup implications.

Average

Correctly explains useEffect runs after render and dependency array controls when it runs.

Strong

Explains effect timing, dependency array behavior, cleanup functions, and common pitfalls like missing dependencies.

How to structure your answer

  1. Define what useEffect handles.
  2. Explain when effects run in component lifecycle.
  3. Describe dependency array behavior.
  4. Cover cleanup functions.
  5. Highlight common dependency mistakes.

Key points to hit

  • useEffect runs side effects after component renders, like API calls or DOM manipulation.
  • Empty dependency array means effect runs once after initial render.
  • Missing dependencies cause stale closures and bugs that are hard to debug.
  • Return a cleanup function to prevent memory leaks when component unmounts or dependencies change.

Common mistakes

  • Omitting dependencies that the effect actually uses, causing stale closure bugs.
  • Not providing cleanup functions for subscriptions or timers, leading to memory leaks.

Sample answer

useEffect is for handling side effects in functional components, like API calls, subscriptions, or DOM manipulation. It runs after the component renders. The dependency array is crucial because it tells React when to re-run the effect.

An empty array means run once after mount, no array means run after every render, and with dependencies, it only runs when those values change. The most important thing is including all variables from component scope that the effect uses, otherwise you'll get stale closure bugs.

Always return a cleanup function for things like subscriptions to prevent memory leaks.

How to level up

  • Explain how useEffect timing differs from componentDidMount in class components.
  • Describe the eslint-plugin-react-hooks exhaustive-deps rule for catching missing dependencies.
  • Mention useLayoutEffect for effects that need to run synchronously before paint.

Follow-up questions to expect

  • How would you fetch data on component mount with useEffect?
  • What's the difference between useEffect with empty deps vs no deps?
  • How do you handle cleanup for async operations in useEffect?
Practice this question with AI feedback →
What is the difference between useEffect and useLayoutEffect?
medium

What they're really asking

This tests understanding of browser rendering phases and when synchronous DOM mutations are necessary. The interviewer wants to see if you know when to use the less common but important useLayoutEffect.

How you'll be scored

Weak

Can't explain the timing difference or gives incorrect information about when to use each.

Average

Correctly states that useLayoutEffect runs synchronously before paint while useEffect runs after.

Strong

Explains timing difference, identifies specific use cases for useLayoutEffect, and understands performance implications.

How to structure your answer

  1. Explain timing difference in browser render cycle.
  2. Describe when useLayoutEffect is necessary.
  3. Give concrete example of visual flickering problem.
  4. Explain performance trade-offs.
  5. Recommend useEffect as default choice.

Key points to hit

  • useEffect runs asynchronously after paint, useLayoutEffect runs synchronously before paint.
  • Use useLayoutEffect when you need to measure or mutate DOM before user sees the update.
  • useLayoutEffect can cause performance issues because it blocks painting.
  • Most effects should use useEffect unless you specifically need synchronous execution.

Common mistakes

  • Using useLayoutEffect by default instead of useEffect, causing unnecessary performance overhead.
  • Not understanding that useLayoutEffect can block the browser's paint phase.

Sample answer

useEffect runs asynchronously after the browser paints the screen, while useLayoutEffect runs synchronously before the paint. I use useLayoutEffect when I need to measure DOM elements or make changes that would cause visual flickering if delayed.

For example, if I'm calculating the position of a tooltip based on a button's location, useLayoutEffect ensures the tooltip appears in the right place immediately without a flash. However, useLayoutEffect blocks painting so it can hurt performance. I default to useEffect and only switch to useLayoutEffect when I specifically need synchronous DOM access.

How to level up

  • Explain how useLayoutEffect is equivalent to componentDidMount and componentDidUpdate timing.
  • Describe measuring DOM elements with getBoundingClientRect as a common useLayoutEffect use case.
  • Mention that useLayoutEffect effects run before useEffect effects in the same render.

Follow-up questions to expect

  • Can you give a specific example where useLayoutEffect prevents flickering?
  • What performance problems can useLayoutEffect cause?
  • How do you decide between useEffect and useLayoutEffect for DOM manipulation?
Practice this question with AI feedback →
What is the difference between useMemo and useCallback?
medium

What they're really asking

This tests understanding of React performance optimization and memoization strategies. The interviewer wants to see if you can distinguish between memoizing values vs functions and apply them appropriately.

How you'll be scored

Weak

Confuses the two hooks or gives incorrect explanations of what they memoize.

Average

Correctly identifies that useMemo memoizes values and useCallback memoizes functions.

Strong

Explains both hooks correctly, identifies when each is useful, and understands their dependency arrays and performance implications.

How to structure your answer

  1. Define what each hook memoizes.
  2. Explain dependency arrays for both.
  3. Give practical examples for each.
  4. Describe when optimization is actually beneficial.
  5. Mention common overuse patterns.

Key points to hit

  • useMemo memoizes computed values, useCallback memoizes function references.
  • Both use dependency arrays to determine when to recalculate or recreate.
  • useCallback is mainly useful when passing functions to memoized child components.
  • Don't use these hooks unless you have a performance problem, as they add complexity and memory overhead.

Common mistakes

  • Overusing memoization hooks without measuring actual performance benefit.
  • Thinking useCallback prevents function recreation in all cases, rather than just returning the same reference.

Sample answer

useMemo memoizes the result of a computation and only recalculates when its dependencies change, while useCallback memoizes a function reference and only creates a new function when dependencies change. I use useMemo for expensive calculations like filtering large arrays, and useCallback when passing functions as props to React.memo wrapped components to prevent unnecessary re-renders.

The key insight is that useCallback doesn't prevent function recreation, it just returns the same reference. Both hooks add memory overhead, so I only use them when I've identified an actual performance issue, not preemptively.

How to level up

  • Explain how useCallback is essentially useMemo(() => fn, deps) under the hood.
  • Describe profiling with React DevTools to identify when memoization actually helps.
  • Mention that referential equality matters more for child component props than the memoization itself.

Follow-up questions to expect

  • When would useMemo actually improve performance vs just adding overhead?
  • How do you identify components that would benefit from useCallback?
  • What's the relationship between useCallback and React.memo?
Practice this question with AI feedback →
What is the useRef hook and when should you use it?
medium

What they're really asking

This tests understanding of mutable references in React's functional component model. The interviewer wants to see if you know the difference between refs for DOM access versus refs as persistent mutable containers that survive re-renders.

How you'll be scored

Weak

Only knows useRef for accessing DOM elements and cannot explain the mutable container pattern.

Average

Explains both DOM access and mutable value storage, but doesn't articulate why ref changes don't trigger re-renders.

Strong

Covers DOM refs, mutable containers, explains that ref mutations don't cause re-renders, and gives practical use cases like storing previous values or interval IDs.

How to structure your answer

  1. Define useRef as a hook that returns a mutable ref object persisted across renders.
  2. Explain the DOM element access use case.
  3. Explain the mutable container use case for values that shouldn't trigger re-renders.
  4. Contrast with useState behavior.
  5. Give practical examples of each pattern.

Key points to hit

  • useRef returns an object with a .current property that persists across renders without causing re-renders when mutated.
  • The most common use is attaching refs to DOM elements to access them imperatively, like focusing an input.
  • useRef also works as a mutable container for values like timer IDs, previous state values, or flags that shouldn't trigger re-renders.
  • Unlike useState, changing ref.current does not cause the component to re-render.

Common mistakes

  • Thinking useRef is only for DOM access and not knowing about the mutable container pattern.
  • Trying to use ref.current in JSX output and expecting it to update visually, since ref changes don't trigger re-renders.

Sample answer

useRef returns a mutable object with a .current property that persists for the entire lifetime of the component. The most familiar use is accessing DOM elements. You pass the ref to an element's ref attribute, and after mounting, ref.current points to that DOM node. So you can call inputRef.current.focus() to programmatically focus an input.

But useRef has a second important use as a mutable container. Because changing ref.current doesn't trigger a re-render, it's perfect for storing values you need to track without causing updates.

I use it for things like storing interval or timeout IDs so I can clear them in cleanup functions, tracking the previous value of a prop with a useEffect, and storing flags like whether a component has mounted yet.

How to level up

  • Mention the callback ref pattern for cases where you need to run logic when a ref attaches or detaches from a DOM node.
  • Discuss how useRef is useful for breaking out of stale closures by always reading the latest value from ref.current.
  • Point out that useRef is the correct way to store mutable values in concurrent mode since it's not affected by render interruptions.

Follow-up questions to expect

  • How would you use useRef to track the previous value of a prop?
  • What is the difference between a ref callback and a ref object?
  • Why can't you use a regular variable instead of useRef to store values across renders?
Practice this question with AI feedback →
What is the difference between useState and useRef?
medium

What they're really asking

This tests whether you understand when to use state versus refs and the rendering implications of each. The interviewer wants to see if you can make the right architectural choice based on whether a value change should update the UI.

How you'll be scored

Weak

Cannot clearly articulate the re-render difference or confuses when to use each.

Average

Knows useState triggers re-renders while useRef does not.

Strong

Explains the re-render behavior, persistence across renders, update timing differences, and gives clear decision criteria for choosing between them.

How to structure your answer

  1. Compare the core difference: re-render trigger behavior.
  2. Explain when updated values become available in each case.
  3. Provide decision criteria for choosing between them.
  4. Give concrete examples where each is the right choice.

Key points to hit

  • useState triggers a re-render when the setter is called, making the new value visible in the UI.
  • useRef mutations are immediate but never trigger re-renders, so the UI won't reflect the change.
  • useState updates are batched and the new value is available on the next render, while ref.current changes are synchronous and immediately readable.
  • Use useState when the value drives what the user sees, use useRef when you need to track something without affecting the output.

Common mistakes

  • Using useRef to store values that should be displayed in the UI, leading to stale displayed values.
  • Using useState for values like timer IDs or previous props that don't need to trigger re-renders, causing unnecessary performance overhead.

Sample answer

The fundamental difference is about rendering. When you call a useState setter, React schedules a re-render and your component runs again with the new value.

The update is batched and asynchronous. useRef gives you a .current property that you can mutate directly, and the change happens synchronously, but React doesn't know about it and won't re-render. So the decision comes down to this: does changing this value need to update what the user sees? If yes, useState. If no, useRef.

I use useState for form values, toggle states, and data that renders in JSX. I use useRef for interval IDs, DOM element references, tracking previous values, and flags like whether an async operation was cancelled. Using useState where useRef would suffice means unnecessary re-renders. Using useRef where useState is needed means stale UI.

How to level up

  • Mention that useState values captured in closures can be stale, while reading ref.current always gives the latest value, making refs useful for event handlers in effects.
  • Discuss how combining both patterns works well, using useRef to store the latest state value for use in callbacks that need the current value without stale closures.
  • Point out that in strict mode, React intentionally double-invokes state initializers to catch side effects, but useRef initial values are only set once.

Follow-up questions to expect

  • Can you show a scenario where using useState causes a bug that useRef would solve?
  • How do stale closures relate to the choice between useState and useRef?
  • What happens if you try to display a useRef value in JSX and update it?
Practice this question with AI feedback →
When should you use useReducer instead of useState?
medium

What they're really asking

This tests your ability to choose the right state management tool based on complexity. The interviewer wants to see if you understand when state transitions become complex enough to benefit from a reducer pattern.

How you'll be scored

Weak

Says useReducer is just Redux inside a component or cannot give concrete criteria for when to switch.

Average

Knows useReducer is better for complex state logic but struggles to define what makes state complex enough.

Strong

Gives specific criteria like multiple related state values, complex transitions, and next-state-depends-on-previous patterns, and explains testing and debugging benefits.

How to structure your answer

  1. Explain what useReducer provides versus useState.
  2. List specific criteria for when useReducer is the better choice.
  3. Describe the reducer pattern with actions and dispatch.
  4. Discuss testing and debugging advantages.
  5. Mention combining useReducer with useContext for shared state.

Key points to hit

  • useReducer is better when you have multiple related state values that update together, like a form with validation.
  • The reducer pattern centralizes state transition logic, making it explicit what actions can happen and how state changes.
  • useReducer is preferred when the next state depends on the previous state in complex ways, beyond simple toggles or increments.
  • Reducers are pure functions that are easy to unit test independently from the component.

Common mistakes

  • Defaulting to useReducer for simple boolean toggles or single values where useState is cleaner and more readable.
  • Not recognizing that useReducer combined with useContext can replace lightweight Redux setups for medium-complexity apps.

Sample answer

I reach for useReducer over useState in a few specific situations. First, when I have multiple pieces of state that change together. Like a data fetching scenario with loading, error, and data values that need coordinated updates. Second, when state transitions are complex.

A shopping cart where you add, remove, update quantity, and apply discounts has enough transition logic that a switch statement in a reducer is clearer than scattered setState calls. Third, when the next state depends on the previous state in non-trivial ways.

The reducer receives the current state and an action, so you always have access to the latest state without closure issues. A big bonus is testability. Since reducers are pure functions, I can test them by passing in state and actions and asserting the output without rendering any components.

How to level up

  • Mention that useReducer with dispatch is stable across renders, so passing dispatch to children avoids the useCallback wrapper needed for setState callbacks.
  • Discuss the useReducer plus useContext pattern as a lightweight alternative to Redux for mid-size applications.
  • Point out that TypeScript discriminated unions for action types make reducers extremely type-safe and self-documenting.

Follow-up questions to expect

  • How would you structure a useReducer for a multi-step form with validation?
  • Can you combine useReducer with useContext? How does that compare to Redux?
  • How does dispatch stability across renders compare to useState setters?
Practice this question with AI feedback →
What is the useContext hook and when should you use it?
medium

What they're really asking

This tests understanding of React's built-in state sharing mechanism and when it is appropriate versus over-engineered. The interviewer wants to see if you can identify the right use cases and know the performance implications.

How you'll be scored

Weak

Describes useContext as a replacement for Redux or cannot explain how it differs from prop drilling.

Average

Correctly explains useContext for sharing data without prop drilling and can describe the Provider/Consumer pattern.

Strong

Explains appropriate use cases, describes re-render behavior when context values change, and discusses strategies for avoiding unnecessary re-renders.

How to structure your answer

  1. Explain what useContext does and the problem it solves.
  2. Describe the createContext, Provider, and useContext workflow.
  3. List appropriate use cases like theme, locale, and auth.
  4. Explain the re-render implications when context values change.
  5. Discuss when context is not the right solution.

Key points to hit

  • useContext lets you read a context value without prop drilling through intermediate components.
  • You create a context with createContext, wrap a subtree with a Provider that supplies a value, and consume it with useContext anywhere below.
  • Good use cases include theme, locale, authentication state, and other rarely-changing global values.
  • Every component that calls useContext re-renders when the context value changes, regardless of whether it uses the specific part that changed.

Common mistakes

  • Using context for frequently changing values like form input state, which causes all consumers to re-render on every keystroke.
  • Not splitting contexts by update frequency, leading to unnecessary re-renders across unrelated consumers.

Sample answer

useContext lets you subscribe to a React context value without passing props through every level of the component tree. You start by creating a context with createContext, then wrap a part of your tree with a Provider component that supplies a value. Any component below that Provider can call useContext to read the current value.

I use it for things like theme preferences, authentication state, and locale settings. These are values that many components need but that change infrequently. The important thing to understand is the performance implication. When the context value changes, every component calling useContext for that context re-renders.

So if you put rapidly changing state like a search input value into context, every consumer re-renders on every keystroke. That is why I split contexts by update frequency and keep fast-changing state in local useState.

How to level up

  • Mention that memoizing the context value object with useMemo prevents unnecessary consumer re-renders when the Provider's parent re-renders.
  • Discuss the pattern of splitting context into a state context and a dispatch context so components that only dispatch don't re-render on state changes.
  • Point out that React.memo does not help with context-triggered re-renders since useContext bypasses the memo check.

Follow-up questions to expect

  • How would you prevent unnecessary re-renders when a context value changes?
  • Can you split context to optimize re-render performance? How?
  • When would you choose Redux or Zustand over useContext?
Practice this question with AI feedback →
How do you create and use custom hooks in React?
medium

What they're really asking

This tests your ability to extract and share stateful logic through composition. The interviewer wants to see if you understand the custom hooks pattern, the naming convention, and how hooks enable logic reuse without changing component hierarchy.

How you'll be scored

Weak

Cannot explain how to create a custom hook or thinks custom hooks require special React APIs beyond existing hooks.

Average

Can create a basic custom hook that extracts state and effect logic into a reusable function.

Strong

Demonstrates clean custom hook patterns, explains the use prefix convention and why it matters, shows how hooks compose together, and discusses when to extract versus inline logic.

How to structure your answer

  1. Explain that custom hooks are regular functions that call other hooks.
  2. Describe the use prefix naming convention and why it matters.
  3. Walk through creating a practical custom hook example.
  4. Explain how multiple components can use the same custom hook independently.
  5. Discuss when to extract logic into a custom hook.

Key points to hit

  • A custom hook is a JavaScript function starting with "use" that calls other React hooks internally.
  • The "use" prefix is required for React's linter to enforce the Rules of Hooks on your custom hook.
  • Each component that uses a custom hook gets its own independent copy of the state and effects.
  • Custom hooks let you share stateful logic between components without render props or higher-order components.

Common mistakes

  • Thinking that components sharing a custom hook also share the same state instance, when each call creates independent state.
  • Creating custom hooks for simple logic that doesn't involve other hooks, which is just a regular utility function and doesn't need the use prefix.

Sample answer

A custom hook is just a JavaScript function whose name starts with "use" and that calls other hooks inside it. The "use" prefix isn't just convention. React's ESLint plugin uses it to enforce the Rules of Hooks on your function. To create one, I extract the stateful logic I want to reuse.

For example, I might create useWindowSize that uses useState to track dimensions and useEffect to listen for resize events. Any component that calls useWindowSize gets its own independent state. The hook doesn't share state between consumers.

I extract custom hooks when I see the same combination of useState and useEffect repeated across components, or when a component has complex logic that makes it hard to read. The hook encapsulates the complexity and gives the component a clean interface.

How to level up

  • Mention that custom hooks can return anything: values, arrays, objects, or even other functions, depending on what makes the API cleanest.
  • Discuss how custom hooks can compose other custom hooks, building layers of abstraction like useAuth calling useLocalStorage and useApi.
  • Point out that custom hooks are the primary replacement for the render props and HOC patterns that were common before hooks.

Follow-up questions to expect

  • Can you show me a custom hook that handles data fetching with loading and error states?
  • How do you test custom hooks in isolation from components?
  • What is the difference between a custom hook and a regular utility function?
Practice this question with AI feedback →
What are "stale closures" in hooks and how do you fix them?
hard

What they're really asking

This tests understanding of JavaScript closures in React's execution model and ability to debug subtle state bugs. The interviewer wants to see if you can identify why hooks capture stale values and implement proper fixes.

How you'll be scored

Weak

Cannot explain what stale closures are or suggests incorrect solutions like force re-rendering.

Average

Explains the concept correctly and mentions dependency arrays as the main solution.

Strong

Explains the closure mechanism, shows code examples of both the problem and multiple solutions, discusses when each approach is appropriate.

How to structure your answer

  1. Define what stale closures are in React context.
  2. Show a concrete code example demonstrating the problem.
  3. Explain why this happens with JavaScript closures.
  4. Present the primary solution using dependency arrays.
  5. Mention alternative approaches like useCallback and refs.

Key points to hit

  • Stale closures happen when useEffect or event handlers capture outdated values from previous renders.
  • The dependency array in useEffect ensures the callback recreates with fresh values.
  • Use useCallback for event handlers that need current state.
  • useRef can hold mutable values that persist across renders without causing re-renders.

Common mistakes

  • Forgetting that omitting dependencies doesn't just cause warnings but creates real bugs.
  • Using force updates or keys to work around the problem instead of fixing the closure issue.

Sample answer

Stale closures happen when a useEffect or event handler captures state values from an old render and doesn't see updates.

For example, if I have a useEffect that sets up a timer and references a count state, but I don't include count in the dependency array, the timer callback will always see the initial count value, not the current one. This happens because JavaScript closures capture variables at creation time.

The fix is including all referenced state in the dependency array so React recreates the effect with fresh values. For event handlers, I use useCallback with proper dependencies, or useRef for values I need to mutate without triggering re-renders.

How to level up

  • Use the exhaustive-deps ESLint rule to catch missing dependencies automatically.
  • Consider custom hooks to encapsulate complex state logic and reduce closure-related bugs.
  • For complex scenarios, useReducer can eliminate many closure issues by passing dispatch instead of individual state values.

Follow-up questions to expect

  • Can you show me a code example of a stale closure bug?
  • When would you use useRef instead of useState to avoid stale closures?
  • How does the React compiler (when available) help with these issues?
Practice this question with AI feedback →
How do you properly cancel async requests inside useEffect?
medium

What they're really asking

This tests understanding of component lifecycle cleanup and async operation management. The interviewer wants to see if you can prevent memory leaks and race conditions from pending requests.

How you'll be scored

Weak

Suggests setting state after unmount without any cleanup mechanism or doesn't understand the problem.

Average

Mentions using cleanup functions and AbortController but lacks implementation details.

Strong

Shows complete implementation using AbortController, explains race conditions, and demonstrates proper cleanup patterns.

How to structure your answer

  1. Explain why cancellation is necessary.
  2. Show AbortController implementation in useEffect.
  3. Demonstrate the cleanup function pattern.
  4. Handle the cancellation gracefully in your async code.
  5. Mention alternative approaches for non-fetch requests.

Key points to hit

  • Use AbortController to cancel fetch requests when component unmounts or dependencies change.
  • Return a cleanup function from useEffect that calls controller.abort()
  • Handle AbortError specifically to avoid logging cancelled requests as real errors.
  • For non-fetch async operations, use boolean flags or cleanup mechanisms specific to that operation.

Common mistakes

  • Trying to set state after component unmounts, which causes React warnings and potential memory leaks.
  • Not handling AbortError separately, causing cancelled requests to appear as failures in error logs.

Sample answer

I use AbortController to cancel pending requests. In useEffect, I create a new AbortController and pass its signal to fetch. Then I return a cleanup function that calls controller.abort() when the component unmounts or dependencies change. In my async code, I check if the error is an AbortError before handling it as a real failure.

For non-fetch operations like timeouts, I clear them in the cleanup function. This prevents the classic 'cannot set state on unmounted component' warning and avoids race conditions where an old request overwrites newer data.

How to level up

  • Create a custom hook like useAsyncEffect to encapsulate the abort logic and reuse it across components.
  • For libraries that don't support AbortController, maintain a mounted flag using useRef and check it before setting state.
  • Consider using libraries like React Query that handle cancellation automatically.

Follow-up questions to expect

  • How would you handle cancellation for multiple concurrent requests?
  • What's your approach for libraries that don't support AbortController?
  • How do you test async cancellation in your components?
Practice this question with AI feedback →
Why can't you write useEffect(async () => { ... })?
medium

What they're really asking

This tests understanding of useEffect's execution model and async/await patterns. The interviewer wants to see if you know why async functions break useEffect's cleanup mechanism.

How you'll be scored

Weak

Doesn't understand the issue or suggests using async directly without explaining the problems.

Average

Knows you can't use async directly and mentions cleanup functions, but explanation lacks depth.

Strong

Explains that async functions return Promises instead of cleanup functions, shows proper async patterns within useEffect, and understands the cleanup timing.

How to structure your answer

  1. Explain what useEffect expects from its callback function.
  2. Clarify why async functions return Promises, not cleanup functions.
  3. Show the correct pattern for async operations in useEffect.
  4. Demonstrate proper cleanup with async operations.
  5. Mention the timing implications for cleanup.

Key points to hit

  • useEffect expects its callback to return either nothing or a cleanup function, but async functions always return a Promise.
  • Create an async function inside useEffect and call it immediately, rather than making the callback itself async.
  • Cleanup functions run synchronously before the next effect or unmount, which is important for preventing race conditions.
  • Use flags or AbortController to handle cleanup of async operations properly.

Common mistakes

  • Trying to make the useEffect callback async, which breaks React's cleanup mechanism.
  • Not understanding that cleanup needs to be synchronous to prevent race conditions.

Sample answer

useEffect expects its callback to return either nothing or a cleanup function for React to call later. But async functions always return a Promise, not a cleanup function, so React can't handle cleanup properly. Instead, I create an async function inside the useEffect callback and call it immediately.

This way, the useEffect callback itself remains synchronous and can return a proper cleanup function. The cleanup function can then cancel the async operation using AbortController or flags, preventing race conditions and memory leaks when the component unmounts or dependencies change.

How to level up

  • Create a custom hook like useAsyncEffect that handles the async pattern and cleanup boilerplate.
  • Remember that cleanup runs synchronously, so any async cleanup operations need to be fire-and-forget.
  • Consider using libraries like React Query for data fetching, which handle async operations and cleanup automatically.

Follow-up questions to expect

  • How would you create a custom useAsyncEffect hook?
  • What happens if you ignore this rule and make useEffect async anyway?
  • How do you handle errors in async operations within useEffect?
Practice this question with AI feedback →
What happens if you return a Promise from useEffect?
medium

What they're really asking

This tests understanding of useEffect's return value contract and React's execution model. The interviewer wants to see if you understand why returning Promises breaks React's cleanup system.

How you'll be scored

Weak

Doesn't understand the issue or thinks returning a Promise is acceptable.

Average

Knows it causes problems but can't explain the specific mechanism or proper alternatives.

Strong

Explains that React tries to call the Promise as a cleanup function, shows the error that occurs, and demonstrates correct async patterns.

How to structure your answer

  1. Explain React's expectation for useEffect return values.
  2. Describe what happens when a Promise is returned.
  3. Show the specific error or warning React generates.
  4. Demonstrate the correct pattern for async operations.
  5. Explain why React's design works this way.

Key points to hit

  • React treats any return value from useEffect as a cleanup function and tries to call it.
  • Returning a Promise causes React to attempt calling the Promise as a function, which fails.
  • React will show a warning about cleanup functions needing to be functions or undefined.
  • The correct pattern is to create and call async functions inside useEffect without returning their Promises.

Common mistakes

  • Returning the Promise from an async operation directly from useEffect.
  • Not understanding that React's warning about cleanup functions is related to Promise returns.

Sample answer

When you return a Promise from useEffect, React treats it as a cleanup function and tries to call it like a function when cleaning up. Since Promises aren't callable, this causes an error. React expects useEffect to return either nothing or a function for cleanup.

If I need async operations, I create an async function inside useEffect, call it immediately without awaiting, and return a proper cleanup function that can cancel the async operation. This keeps the useEffect callback synchronous while allowing async work inside it.

How to level up

  • The React DevTools will show warnings about invalid cleanup functions when Promises are returned.
  • This design ensures cleanup always runs synchronously, preventing race conditions during unmounting.
  • Modern linting rules like exhaustive-deps will often catch these patterns and suggest corrections.

Follow-up questions to expect

  • What specific error message does React show when you return a Promise?
  • How would you refactor existing code that returns Promises from useEffect?
  • Why does React require cleanup functions to be synchronous?
Practice this question with AI feedback →
Why does useEffect run twice in development mode (React 18 Strict Mode)?
medium

What they're really asking

This tests understanding of React 18's Strict Mode behavior and component lifecycle intentionality. The interviewer wants to see if you can write effects that handle double execution properly.

How you'll be scored

Weak

Doesn't know about the behavior change or suggests disabling Strict Mode to fix it.

Average

Knows it's for testing effect cleanup but can't explain the specific benefits or how to handle it.

Strong

Explains that it simulates remounting to catch cleanup bugs, shows how to write effects that handle double execution, and understands the production implications.

How to structure your answer

  1. Explain that React 18 Strict Mode intentionally runs effects twice.
  2. Describe why this helps catch bugs in effect cleanup.
  3. Show how to write effects that handle double execution.
  4. Explain that this only happens in development, not production.
  5. Discuss the benefits for code quality and future React features.

Key points to hit

  • React 18 Strict Mode mounts, unmounts, and remounts components to simulate real-world scenarios where components might be hidden and restored.
  • This catches bugs where effects don't properly clean up subscriptions, event listeners, or API calls.
  • Well-written effects should be idempotent and handle being run multiple times safely.
  • This behavior prepares code for future React features like Offscreen components that can unmount and remount.

Common mistakes

  • Disabling Strict Mode instead of fixing the underlying effect cleanup issues.
  • Writing effects that break when run twice, like incrementing counters or making duplicate API calls without proper guards.

Sample answer

React 18's Strict Mode intentionally runs effects twice in development to catch cleanup bugs. It mounts the component, runs the effect, unmounts it, runs cleanup, then mounts again and runs the effect again. This simulates scenarios where React might unmount components for performance and remount them later.

It exposes bugs where effects don't clean up properly, like forgotten event listeners or API subscriptions. The solution isn't to disable Strict Mode but to write effects that are idempotent and handle multiple executions safely. This only happens in development, and it makes my code more robust for production.

How to level up

  • Use this behavior as a testing tool - if your effect breaks when run twice, it has a cleanup bug.
  • Consider future React features like concurrent rendering that might unmount and remount components in production.
  • Write integration tests that simulate component unmounting and remounting to catch these issues.

Follow-up questions to expect

  • How do you write an effect that safely handles being run multiple times?
  • What kinds of bugs does this behavior typically expose?
  • How does this relate to React's upcoming Offscreen component features?
Practice this question with AI feedback →
Can you have multiple useEffect hooks in a single component?
easy

What they're really asking

This tests understanding of the hooks mental model and separation of concerns. The interviewer wants to see if you know that hooks are designed to be split by concern rather than by lifecycle method.

How you'll be scored

Weak

Doesn't know multiple useEffect hooks are possible or says it's bad practice.

Average

Knows you can use multiple useEffect hooks and that it's encouraged.

Strong

Explains why splitting effects by concern is better than one giant effect, connects this to the hooks philosophy of grouping related logic together, and discusses dependency array implications.

How to structure your answer

  1. Confirm that yes, multiple useEffect hooks are both allowed and encouraged.
  2. Explain the philosophy behind splitting by concern.
  3. Contrast with class component lifecycle methods that forced grouping unrelated logic.
  4. Show practical examples of when to split versus combine effects.

Key points to hit

  • Yes, you can and should have multiple useEffect hooks. React runs them in the order they are defined.
  • Each useEffect should handle one specific concern like data fetching, event subscriptions, or document title updates.
  • This is a deliberate improvement over class components where componentDidMount forced unrelated logic into a single method.
  • Each effect has its own dependency array, so unrelated state changes don't trigger unrelated side effects.

Common mistakes

  • Combining all side effects into a single useEffect with a bloated dependency array that fires too often.
  • Not understanding that React guarantees effects run in declaration order, which matters when effects depend on each other.

Sample answer

Yes, absolutely. Having multiple useEffect hooks is not just allowed, it's the recommended pattern. The whole philosophy of hooks is to group code by concern rather than by lifecycle method. In class components, you might set up a WebSocket and also update the document title in componentDidMount. Those are unrelated concerns forced together.

With hooks, I write separate useEffect calls. One handles the WebSocket connection with its own cleanup. Another updates the document title based on a specific piece of state. Each has its own dependency array, so updating the title doesn't accidentally reconnect the WebSocket.

React runs them in declaration order after every render that matches their dependency arrays.

How to level up

  • Mention that having many useEffect hooks in one component might signal it's time to extract some into custom hooks for better organization.
  • Discuss that effect execution order is guaranteed to be the same as declaration order, which is important when effects have implicit dependencies on each other.
  • Point out that each effect gets its own closure over the current render's state and props values.

Follow-up questions to expect

  • In what order do multiple useEffect hooks run?
  • When would you combine logic into a single useEffect versus splitting it?
  • How do cleanup functions work when you have multiple effects?
Practice this question with AI feedback →
How do you prevent infinite loops with useEffect?
medium

What they're really asking

This tests practical debugging skills with one of the most common hooks mistakes. The interviewer wants to see if you understand why infinite loops happen and can systematically prevent them.

How you'll be scored

Weak

Cannot identify what causes infinite loops or suggests removing the dependency array entirely.

Average

Knows that setting state inside useEffect without proper dependencies causes infinite loops.

Strong

Explains multiple causes including missing dependency arrays, object/array recreation in dependencies, and state updates that trigger the effect, plus gives specific solutions for each.

How to structure your answer

  1. Explain the most common cause: missing or incorrect dependency arrays.
  2. Describe the set-state-inside-effect loop pattern.
  3. Show the object/array reference identity trap.
  4. Provide specific solutions for each case.
  5. Mention tools that help catch these issues.

Key points to hit

  • An effect without a dependency array runs after every render, and if it sets state, it triggers another render creating an infinite loop.
  • Objects and arrays created during render are new references each time, so including them in dependencies causes the effect to fire every render.
  • The solution is using the correct dependency array, memoizing dependencies with useMemo/useCallback, or moving object creation inside the effect.
  • The exhaustive-deps ESLint rule catches most of these issues before they become runtime problems.

Common mistakes

  • Suppressing the exhaustive-deps lint rule to hide the problem instead of properly structuring the effect and its dependencies.
  • Using an empty dependency array as a blanket fix without understanding that it might cause stale data bugs.

Sample answer

Infinite loops with useEffect usually come from three patterns. The most basic one is having no dependency array at all while setting state inside the effect. The effect runs, sets state, triggers a re-render, effect runs again, and it loops forever. The fix is adding a dependency array. The second pattern is trickier.

You include an object or array in the dependency array, but it gets recreated every render. Even if the values inside are identical, the reference is new, so the effect fires again.

I fix this by moving the object creation inside the effect, using useMemo to stabilize the reference, or extracting the specific primitive values I need into the dependency array. The third pattern is setting the same state that's in your dependency array.

For that, I use the functional updater form of setState so I don't need the current value in the dependency array.

How to level up

  • Mention that the useEffectEvent proposal (currently experimental) would solve many stale closure issues by letting you read latest values without adding them to dependencies.
  • Discuss using useRef to break the loop when you need to track a value without triggering the effect.
  • Point out that React StrictMode double-invoking effects in development helps surface infinite loop bugs early.

Follow-up questions to expect

  • How does the functional updater pattern for setState help avoid dependency issues?
  • What does the exhaustive-deps ESLint rule do and should you ever disable it?
  • How would you debug an infinite loop in a complex component with multiple effects?
Practice this question with AI feedback →
What is useImperativeHandle and when would you use it?
hard

What they're really asking

This tests understanding of imperative patterns in React's declarative model and when breaking convention is justified. The interviewer wants to see if you know how to expose a controlled API from a child component through refs.

How you'll be scored

Weak

Has never used or heard of useImperativeHandle or confuses it with useRef.

Average

Knows it customizes the ref value exposed to parent components when using forwardRef.

Strong

Explains the use case for component libraries, shows how it pairs with forwardRef, explains why you limit the exposed API, and gives practical examples like exposing focus or scroll methods.

How to structure your answer

  1. Define useImperativeHandle and its relationship with forwardRef.
  2. Explain why you would want to customize the ref value.
  3. Show a practical example like a custom input component.
  4. Discuss when this pattern is appropriate versus props/callbacks.
  5. Mention the optional dependency array parameter.

Key points to hit

  • useImperativeHandle lets you customize the instance value exposed through a ref when a parent component uses ref on your component.
  • It must be used with forwardRef so the parent's ref can be intercepted and customized.
  • You should only expose the minimum API the parent needs, not the entire DOM node, to maintain encapsulation.
  • Common use cases are component libraries exposing methods like focus, scrollTo, or reset without exposing internal DOM structure.

Common mistakes

  • Exposing too many methods through useImperativeHandle instead of using declarative props, turning the component into an imperative API.
  • Forgetting to wrap the component with forwardRef, which is required for useImperativeHandle to work.

Sample answer

useImperativeHandle customizes what a parent component sees when it attaches a ref to your component. Normally, if you use forwardRef, the parent gets direct access to the underlying DOM node. But sometimes you want to expose a controlled API instead.

For example, I built a rich text editor component where I didn't want parents directly manipulating the internal DOM. Using useImperativeHandle, I exposed only three methods: focus(), clear(), and getContent(). The parent calls editorRef.current.focus() and my component handles the details internally.

You pair it with forwardRef, and it accepts a dependency array as the third argument to control when the exposed methods are recreated. It is an escape hatch. Most of the time, declarative props are better. But for component libraries that need to expose imperative actions, it's the right tool.

How to level up

  • Mention that React 19 removes the need for forwardRef entirely, making useImperativeHandle simpler to use with the new ref prop behavior.
  • Discuss how useImperativeHandle is useful for abstracting platform differences in cross-platform React Native components.
  • Point out that the dependency array controls when the handle object is recreated, similar to useMemo, so expensive methods can be memoized.

Follow-up questions to expect

  • How does useImperativeHandle work with forwardRef under the hood?
  • Can you give an example of when useImperativeHandle is better than passing callback props?
  • How would this pattern change with React 19's ref handling improvements?
Practice this question with AI feedback →
What is the useId hook and when should it be used?
medium

What they're really asking

This tests awareness of React 18 additions and understanding of hydration-safe ID generation. The interviewer wants to see if you know why generating IDs in React is harder than it seems, especially with server-side rendering.

How you'll be scored

Weak

Has not heard of useId or suggests using Math.random() for generating IDs in components.

Average

Knows useId generates unique IDs and is useful for accessibility attributes.

Strong

Explains the SSR hydration mismatch problem useId solves, shows usage with aria attributes and htmlFor/id pairs, and understands that IDs are stable across server and client renders.

How to structure your answer

  1. Define useId and when it was introduced.
  2. Explain the hydration mismatch problem with manually generated IDs.
  3. Show practical use cases with form labels and ARIA attributes.
  4. Clarify what useId should not be used for.

Key points to hit

  • useId generates a unique, stable ID string that is consistent between server and client renders.
  • It solves the hydration mismatch problem where Math.random or incrementing counters produce different IDs on server versus client.
  • Primary use cases are connecting form labels to inputs with htmlFor/id and linking ARIA attributes like aria-describedby.
  • useId should not be used for list keys since keys need to come from your data, not be generated per render.

Common mistakes

  • Using useId to generate keys for list items, which is a different problem that requires stable data-derived identifiers.
  • Not understanding that the main value of useId is hydration safety, making it seem unnecessary if you've only worked with client-side rendering.

Sample answer

useId is a React 18 hook that generates unique ID strings that are stable between server and client renders. The problem it solves is subtle. If you generate IDs with Math.random() or a counter, the server renders one ID and the client renders a different one during hydration.

React throws a mismatch error. useId generates the same deterministic ID on both sides based on the component's position in the tree. I use it primarily for accessibility. When I have a form input, I call const id = useId() and then use id for the input's id attribute and the label's htmlFor attribute.

Same pattern for aria-describedby linking an input to its error message. One important note: don't use useId for list keys. Keys should come from your data.

How to level up

  • Mention that useId works correctly even with multiple React roots on the same page by using the identifierPrefix option in createRoot.
  • Discuss how useId can generate a prefix that you append to for multiple related elements, like id + '-name' and id + '-email' in the same form.
  • Point out that useId IDs contain colons, which can't be used in CSS selectors, so you should avoid using them for styling purposes.

Follow-up questions to expect

  • Why can't you use Math.random() to generate IDs in server-rendered React apps?
  • How does useId guarantee the same ID on server and client?
  • What is the identifierPrefix option in createRoot and when would you use it?
Practice this question with AI feedback →
Can Hooks replace Redux?
medium

What they're really asking

This tests your ability to evaluate tools pragmatically rather than following trends. The interviewer wants to see if you understand what Redux actually provides and which parts hooks can replicate versus which require dedicated libraries.

How you'll be scored

Weak

Gives a binary yes or no without nuance, or thinks useContext is identical to Redux.

Average

Knows hooks cover some Redux use cases but acknowledges Redux offers additional features.

Strong

Clearly identifies what hooks can replace (simple shared state), what Redux uniquely provides (middleware, devtools, predictable patterns), and gives decision criteria based on app complexity.

How to structure your answer

  1. Acknowledge the nuance instead of giving a yes/no answer.
  2. Identify what hooks can replicate: useReducer plus useContext for shared state.
  3. Identify what Redux uniquely provides: middleware, time-travel debugging, devtools, ecosystem.
  4. Give practical decision criteria.
  5. Mention modern lightweight alternatives.

Key points to hit

  • useReducer plus useContext can replace Redux for simple to moderate shared state needs.
  • Redux provides middleware for side effects, time-travel debugging, DevTools, and established patterns that hooks alone don't offer.
  • Hooks don't provide built-in solutions for normalized caching, optimistic updates, or selector-based re-render optimization.
  • The answer depends on your app's complexity, team size, and whether you need Redux's specific features.

Common mistakes

  • Saying hooks completely replace Redux without understanding the middleware ecosystem and debugging tooling Redux provides.
  • Recommending Redux for every app regardless of size, when useReducer plus useContext is sufficient for many small and medium projects.

Sample answer

It depends on what you're using Redux for. If you're just sharing state across a few components, useReducer combined with useContext can absolutely replace Redux. You get a reducer for predictable state updates and context for distribution, without the boilerplate. But Redux offers things hooks don't.

Middleware like Redux Thunk and Saga give you structured side effect handling. The Redux DevTools let you time-travel debug and inspect every action. The Redux ecosystem includes patterns for normalized caching and selector-based re-render optimization with Reselect. For a small app with a few pieces of shared state, hooks are enough.

For a large app with complex async flows, multiple developers, and debugging needs, Redux or a modern alternative like Zustand still provides real value.

How to level up

  • Mention that Zustand, Jotai, and Recoil are modern alternatives that provide Redux-like features with less boilerplate and better hooks integration.
  • Discuss how RTK Query and TanStack Query have largely replaced the need for Redux in data fetching scenarios.
  • Point out that the decision often comes down to team conventions and debugging needs rather than purely technical capability.

Follow-up questions to expect

  • How would you architect shared state with just hooks for a medium-sized app?
  • What specific Redux features are hardest to replicate with hooks alone?
  • When would you choose Zustand or Jotai over Redux and useContext?
Practice this question with AI feedback →
Do Hooks replace render props and higher-order components?
medium

What they're really asking

This tests understanding of React's evolution from older patterns to hooks and whether you can make architectural decisions about when to refactor existing code versus using modern patterns.

How you'll be scored

Weak

Claims hooks completely replace all patterns without understanding when render props or HOCs might still be useful.

Average

Correctly states that hooks provide better alternatives but doesn't explain specific trade-offs or migration considerations.

Strong

Explains that hooks solve most use cases better while acknowledging specific scenarios where older patterns might still have value, plus practical migration advice.

How to structure your answer

  1. Acknowledge that hooks solve the main problems these patterns addressed.
  2. Explain the advantages hooks provide over render props and HOCs.
  3. Identify edge cases where older patterns might still be relevant.
  4. Discuss migration strategy for existing codebases.

Key points to hit

  • Hooks eliminate wrapper hell and prop drilling that HOCs and render props often create.
  • Custom hooks provide cleaner reusable logic compared to render props.
  • Some third-party libraries still use render props effectively.
  • Migration should be gradual, not a complete rewrite.

Common mistakes

  • Claiming you should immediately refactor all existing render props and HOCs to hooks.
  • Not recognizing that some render prop patterns are still elegant for specific use cases.

Sample answer

Hooks solve most of the problems that render props and HOCs were designed to address, but they don't completely replace them. Hooks eliminate the wrapper hell you get with HOCs and make sharing stateful logic much cleaner than render props. For example, a custom useWindowSize hook is way simpler than a WindowSize render prop component.

However, some libraries like React Router still use render props effectively, and there's no rush to refactor working code. I'd introduce hooks for new features and gradually migrate older patterns when you're already touching that code.

How to level up

  • Mention that hooks compose better than HOCs because there's no nesting.
  • Explain how custom hooks can encapsulate complex state logic that would be awkward with render props.

Follow-up questions to expect

  • How would you migrate a complex HOC to a custom hook?
  • What are the performance implications of switching from HOCs to hooks?
  • Can you show an example where a render prop might still be the better choice?
Practice this question with AI feedback →
Can Hooks be used in class components?
easy

What they're really asking

This tests basic understanding of React's architecture and whether you know the fundamental constraint that hooks only work with functional components.

How you'll be scored

Weak

Incorrectly claims hooks can be used in class components or shows confusion about component types.

Average

Correctly states hooks cannot be used in class components but doesn't explain why or mention alternatives.

Strong

Clearly explains that hooks are exclusive to functional components, understands the technical reason why, and can discuss migration strategies.

How to structure your answer

  1. Give a direct no answer.
  2. Explain that hooks are designed specifically for functional components.
  3. Mention what class components use instead.
  4. Discuss migration path if needed.

Key points to hit

  • Hooks can only be called from functional components or other custom hooks.
  • Class components use lifecycle methods and this.setState instead.
  • You cannot mix hooks and class component patterns in the same component.
  • Migration requires converting the class to a function component.

Common mistakes

  • Thinking you can somehow import hooks into class components.
  • Confusing hooks with class lifecycle methods.

Sample answer

No, hooks cannot be used in class components at all. Hooks are specifically designed for functional components and rely on React's internal call order to maintain state between renders. Class components have their own patterns like lifecycle methods and this.setState.

If you need hook functionality in a class component, you'd need to convert it to a functional component first, which usually means replacing componentDidMount with useEffect and this.state with useState.

How to level up

  • Explain that React's internal hook implementation depends on call order which doesn't work with class render methods.
  • Mention that you can wrap class components with functional components that use hooks if partial migration is needed.

Follow-up questions to expect

  • How would you convert a class component with componentDidMount and componentWillUnmount to hooks?
  • What's the equivalent of componentDidUpdate using hooks?
  • Can you mix functional and class components in the same app?
Practice this question with AI feedback →
Can useState take a function as an initial value (lazy initialization)?
medium

What they're really asking

This tests understanding of React's performance optimization features and whether you know about lazy initialization to avoid expensive computations on every render.

How you'll be scored

Weak

Doesn't know about lazy initialization or incorrectly explains how initial values work.

Average

Knows useState can take a function but doesn't explain when or why you'd use it.

Strong

Correctly explains lazy initialization with useState, provides a practical example, and understands the performance implications.

How to structure your answer

  1. Confirm that useState supports lazy initialization.
  2. Explain when and why you'd use a function instead of a direct value.
  3. Provide a concrete example.
  4. Mention the performance benefit.

Key points to hit

  • useState accepts either a value or a function that returns the initial value.
  • The function form prevents expensive calculations on every render.
  • Lazy initialization only runs once when the component mounts.
  • Use it when initial state requires computation like reading from localStorage or complex calculations.

Common mistakes

  • Thinking the function runs on every render instead of just once.
  • Using lazy initialization for simple values where it adds unnecessary complexity.

Sample answer

Yes, useState can take a function for lazy initialization. Instead of useState(expensiveCalculation()), you'd write useState(() => expensiveCalculation()). The function version only runs once when the component first mounts, while the direct value version would run the calculation on every render even though React ignores it after the first time.

I use this pattern when reading from localStorage or doing initial data processing that I don't want happening on every re-render.

How to level up

  • Emphasize that this is most important when the initial calculation is actually expensive, not for simple operations.
  • Mention that this is similar to lazy evaluation patterns in other languages.

Follow-up questions to expect

  • When would you choose lazy initialization over just calculating the value directly?
  • How does React know to only call the initialization function once?
  • Can you show an example of reading from localStorage with lazy initialization?
Practice this question with AI feedback →
Is useState synchronous or asynchronous?
medium

What they're really asking

This tests understanding of React's rendering behavior and whether you know that state updates are asynchronous and batched for performance reasons.

How you'll be scored

Weak

Incorrectly claims useState updates are synchronous or shows confusion about when state changes take effect.

Average

Correctly states that useState is asynchronous but doesn't explain batching or practical implications.

Strong

Explains asynchronous nature, understands batching behavior, and can discuss practical implications for accessing updated state.

How to structure your answer

  1. State that useState updates are asynchronous.
  2. Explain React's batching behavior.
  3. Show how to access updated state when needed.
  4. Mention React 18 automatic batching changes.

Key points to hit

  • useState updates are asynchronous and may be batched with other state updates.
  • You cannot immediately read the new state value after calling setState.
  • Use useEffect or the functional update pattern to work with updated state.
  • React 18 introduced automatic batching for all updates, not just event handlers.

Common mistakes

  • Trying to read state immediately after calling setState and expecting the new value.
  • Not understanding that multiple setState calls in the same event handler get batched.

Sample answer

useState is asynchronous. When you call setCount(5), the count variable doesn't immediately become 5 in the same render cycle. React batches state updates for performance and triggers a re-render with the new values. If I need to do something after state updates, I use useEffect with the state variable as a dependency.

For updates based on previous state, I use the functional form like setCount(prev => prev + 1) to avoid stale closures.

How to level up

  • Explain that React 18's automatic batching changed when batching occurs compared to React 17.
  • Mention that you can use flushSync to force synchronous updates in rare cases where needed.

Follow-up questions to expect

  • How would you handle a situation where you need to perform an action immediately after state updates?
  • What's the difference between setState(value) and setState(prev => newValue)?
  • How does batching behavior differ between React 17 and React 18?
Practice this question with AI feedback →
What is the purpose of the callback function format of setState?
medium

What they're really asking

This tests understanding of functional state updates and whether you know how to avoid stale closure problems when state updates depend on previous state values.

How you'll be scored

Weak

Doesn't understand functional updates or incorrectly explains when to use them.

Average

Knows about functional updates but doesn't explain the stale closure problem they solve.

Strong

Explains functional updates clearly, understands the stale closure issue, and can provide practical examples of when this matters.

How to structure your answer

  1. Explain what functional updates are.
  2. Describe the stale closure problem they solve.
  3. Provide a concrete example.
  4. Mention when functional updates are necessary.

Key points to hit

  • Functional updates receive the current state value as an argument and return the new state.
  • They solve stale closure issues when state updates depend on previous values.
  • Particularly important in event handlers, timeouts, or effects that capture state variables.
  • Always use functional updates when the new state depends on the previous state.

Common mistakes

  • Using direct state values in closures that might become stale.
  • Not recognizing when functional updates are necessary to avoid bugs.

Sample answer

The callback function format like setState(prevState => prevState + 1) ensures you're always working with the most current state value. This solves stale closure problems where you might capture an old state value in an event handler or timeout.

For example, if you have multiple button clicks that increment a counter, using setCount(count + 1) might use a stale count value, but setCount(prev => prev + 1) always gets the latest value. I use functional updates whenever the new state depends on the previous state.

How to level up

  • Explain that this is especially critical in rapid user interactions or when using setTimeout/setInterval.
  • Mention that functional updates also help with React's concurrent features by ensuring consistency.

Follow-up questions to expect

  • Can you show an example where not using functional updates would cause a bug?
  • How do functional updates help with React's concurrent rendering?
  • When might you choose direct state updates over functional updates?
Practice this question with AI feedback →
How does React batch multiple state updates? What changed in React 18?
hard

What they're really asking

This tests deep understanding of React's state update scheduling and awareness of a significant React 18 behavior change. The interviewer wants to see if you understand the performance implications and can explain the before/after.

How you'll be scored

Weak

Doesn't know what batching means or is unaware of the React 18 change.

Average

Knows batching means combining multiple setState calls into one re-render and that React 18 expanded it.

Strong

Explains exactly which contexts were batched before React 18 (only event handlers), what changed (automatic batching everywhere), how flushSync opts out, and the performance implications.

How to structure your answer

  1. Define what state update batching means and why it matters.
  2. Explain React 17 batching behavior and its limitations.
  3. Describe what React 18 automatic batching changed.
  4. Show how flushSync can opt out of batching when needed.
  5. Discuss the performance impact of this change.

Key points to hit

  • Batching means React groups multiple state updates into a single re-render instead of re-rendering after each one.
  • Before React 18, batching only worked inside React event handlers. Updates in setTimeout, promises, and native events triggered separate re-renders.
  • React 18 introduced automatic batching with createRoot, batching all state updates regardless of where they originate.
  • flushSync from react-dom lets you opt out of batching and force a synchronous re-render when you need the DOM updated immediately.

Common mistakes

  • Not knowing that React 17 did not batch updates in promises and timeouts, which was a significant source of unnecessary re-renders.
  • Using flushSync unnecessarily, which defeats the performance benefits of batching and should only be used in rare DOM measurement scenarios.

Sample answer

Batching is when React groups multiple state updates into a single re-render. If you call setName and setAge in the same event handler, React doesn't re-render twice. It waits until the handler finishes and does one render with both updates. Before React 18, this only worked inside React event handlers.

If you had setState calls inside a setTimeout, a promise .then callback, or a native event listener, each one triggered a separate re-render. React 18 changed this with automatic batching. Using createRoot, all state updates are batched regardless of context. Promise callbacks, setTimeout, native events, they all get batched now.

This was a significant performance win for apps with async state updates. If you ever need to force an immediate re-render, React provides flushSync to opt out, but I almost never need it.

How to level up

  • Mention that automatic batching works with both useState and useReducer updates, even when they are mixed in the same batch.
  • Discuss that the legacy ReactDOM.render API does not get automatic batching, only the new createRoot API does.
  • Explain that batching interacts with concurrent features like useTransition, where transitions can be interrupted and rebatched with higher priority updates.

Follow-up questions to expect

  • Can you show an example where React 17 would cause two re-renders but React 18 would only cause one?
  • When would you actually need to use flushSync?
  • How does batching interact with concurrent rendering features?
Practice this question with AI feedback →
What is useTransition and how does it improve UI responsiveness?
hard

What they're really asking

This tests understanding of React 18 concurrent features and the concept of prioritizing updates. The interviewer wants to see if you grasp the difference between urgent and non-urgent updates and how transitions keep the UI responsive.

How you'll be scored

Weak

Has not used useTransition or confuses it with CSS transitions.

Average

Knows useTransition marks updates as non-urgent so the UI stays responsive.

Strong

Explains the isPending/startTransition API, how React interrupts transition renders for urgent updates, real use cases like search filtering, and the relationship to concurrent rendering.

How to structure your answer

  1. Define useTransition and the problem it solves.
  2. Explain the isPending and startTransition return values.
  3. Describe how React prioritizes urgent updates over transitions.
  4. Show a practical use case like filtering a large list.
  5. Connect to concurrent rendering concepts.

Key points to hit

  • useTransition returns [isPending, startTransition] where startTransition marks state updates as low-priority transitions.
  • Urgent updates like typing in an input are processed immediately while transition updates like filtering a list can be interrupted.
  • If a new urgent update arrives during a transition render, React abandons the in-progress transition and handles the urgent update first.
  • isPending gives you a boolean to show loading indicators while the transition is processing.

Common mistakes

  • Using startTransition for every state update, which dilutes the benefit and can make the UI feel sluggish when updates should be immediate.
  • Not understanding that startTransition only works with state updates. You cannot wrap API calls or other side effects in it.

Sample answer

useTransition is a React 18 hook that lets you mark certain state updates as non-urgent. It returns an isPending boolean and a startTransition function. The classic use case is a search input with a filtered list. When the user types, you want the input to update immediately. But filtering thousands of items can be slow.

Without useTransition, the input feels laggy because React processes everything at the same priority. With useTransition, I wrap the filter state update in startTransition. React processes the input change immediately and renders the filtered list in the background.

If the user types another character before filtering finishes, React abandons the stale transition and starts fresh with the new input. isPending lets me show a spinner or dim the results while the transition is in progress.

How to level up

  • Mention that startTransition is also available as a standalone import from React for use outside components where you don't need the isPending state.
  • Discuss how useTransition works under the hood with React's priority lanes system in the Fiber architecture.
  • Point out that transitions pair well with Suspense, where a transition can delay showing a fallback by keeping the old UI visible until the new content is ready.

Follow-up questions to expect

  • How does useTransition differ from debouncing the state update?
  • What happens if multiple transitions are started in rapid succession?
  • How does useTransition interact with Suspense boundaries?
Practice this question with AI feedback →
What is useDeferredValue and when would you use it?
hard

What they're really asking

This tests understanding of React 18 concurrent features and the specific pattern of deferring a value to keep the UI responsive. The interviewer wants to see if you know how useDeferredValue differs from useTransition and when to choose it.

How you'll be scored

Weak

Cannot explain what useDeferredValue does or confuses it entirely with useTransition.

Average

Knows useDeferredValue creates a deferred copy of a value that updates with lower priority.

Strong

Explains how it works with stale-while-revalidate semantics, contrasts with useTransition, and identifies when you use it versus useTransition based on whether you control the state update.

How to structure your answer

  1. Define useDeferredValue and what it returns.
  2. Explain the stale-while-revalidate behavior.
  3. Compare with useTransition and clarify when to use each.
  4. Show a practical use case.
  5. Discuss the memoization requirement for performance benefits.

Key points to hit

  • useDeferredValue accepts a value and returns a deferred version that lags behind the original during heavy renders.
  • React first renders with the old deferred value (keeping the UI responsive) then re-renders in the background with the new value.
  • Use useDeferredValue when you don't control the state update, like receiving a prop from a parent. Use useTransition when you control the setState call.
  • For useDeferredValue to actually skip expensive work, the child receiving the deferred value must be wrapped in React.memo.

Common mistakes

  • Not wrapping the consuming component in React.memo, which means it re-renders with the new value immediately, defeating the purpose.
  • Using useDeferredValue and useTransition together for the same value, which is redundant since they solve the same problem from different angles.

Sample answer

useDeferredValue takes a value and returns a deferred copy of it. When the original value changes, React first renders with the old deferred value so the UI stays responsive, then renders again in the background with the new value. It works like a stale-while-revalidate pattern. The key distinction from useTransition is about control.

If I own the state setter, I use useTransition to wrap the update. But if the value comes from a prop or a parent I don't control, useDeferredValue is the right tool. For example, a SearchResults component receives a query prop. I can't wrap the parent's setState in startTransition.

But I can call useDeferredValue(query) and pass the deferred value to an expensive results list wrapped in React.memo. The list renders with the old query while the new query processes in the background.

How to level up

  • Mention that during the initial mount, the deferred value equals the original value with no lag, which avoids issues on first render.
  • Discuss that you can compare the original value to the deferred value to show loading indicators: if value !== deferredValue, show a spinner.
  • Point out that useDeferredValue has no fixed timeout. React renders the deferred update as soon as the main thread is free.

Follow-up questions to expect

  • How would you show a loading state while useDeferredValue is processing?
  • Why is React.memo required for useDeferredValue to be effective?
  • Can you use useDeferredValue with server components?
Practice this question with AI feedback →
How do you share hook logic across components without prop drilling?
medium

What they're really asking

This tests understanding of composition patterns in React and how hooks, context, and custom hooks work together to share logic. The interviewer wants to see if you can architect solutions that avoid prop drilling while maintaining clean component boundaries.

How you'll be scored

Weak

Only knows about prop drilling and cannot suggest alternatives.

Average

Mentions Context API and custom hooks as solutions.

Strong

Explains custom hooks for shared logic, Context for shared state, composition patterns, and when each approach is appropriate based on the type of sharing needed.

How to structure your answer

  1. Distinguish between sharing logic versus sharing state.
  2. Explain custom hooks for reusable stateful logic.
  3. Explain Context API for shared state access.
  4. Mention composition patterns like compound components.
  5. Give criteria for choosing between approaches.

Key points to hit

  • Custom hooks extract and share stateful logic without sharing state instances. Each consumer gets its own state.
  • Context API shares actual state values across a component tree without passing props through intermediary components.
  • Component composition with children or render props can reduce prop drilling by restructuring the component tree.
  • The right approach depends on whether you need shared logic (custom hooks) or shared state (context or state management library)

Common mistakes

  • Confusing shared logic with shared state. Custom hooks give independent state to each consumer, which is different from sharing the same state value via context.
  • Defaulting to context for everything when simple component composition or lifting state up would be simpler and more performant.

Sample answer

There are two different problems here: sharing logic and sharing state. For shared logic, custom hooks are the primary tool. A useFormValidation hook gives each form its own validation state, but they all share the same validation rules and patterns. Each component that calls the hook gets an independent state instance.

For shared state where multiple components need the same data, Context API works well. I create a context with the shared state and a Provider that wraps the consuming components. They all read and update the same state.

For cases where prop drilling only goes two or three levels, I often restructure with component composition instead. By passing components as children or render props, I can skip intermediate layers entirely. The key decision is: do I need the same state or just the same logic?

How to level up

  • Mention that libraries like Zustand provide hook-based global state without Context's re-render overhead on all consumers.
  • Discuss the compound component pattern where a parent manages shared state and children communicate through context without exposing the state to the tree between them.
  • Point out that the use hook in React 19 enables reading context and promises more ergonomically, further reducing the need for prop drilling.

Follow-up questions to expect

  • When would you prefer Zustand or Jotai over Context for shared state?
  • How do compound components reduce prop drilling?
  • What are the performance trade-offs between context-based sharing and prop-based sharing?
Practice this question with AI feedback →

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Performance & Optimization Questions (15)

How do you prevent unnecessary re-renders in React?
medium

What they're really asking

This tests practical knowledge of React performance optimization techniques. The interviewer wants to see if you can identify the common causes of unnecessary re-renders and apply the right fixes without over-optimizing.

How you'll be scored

Weak

Only suggests adding useMemo everywhere without understanding why re-renders happen or whether they're actually problematic.

Average

Lists React.memo, useMemo, and useCallback with basic understanding of when each applies.

Strong

Explains the re-render cascade from parent to children, demonstrates targeted solutions, discusses measurement-first approach, and warns against premature optimization.

How to structure your answer

  1. Explain why components re-render unnecessarily by default.
  2. Cover React.memo for preventing child re-renders.
  3. Explain useMemo and useCallback for stabilizing references.
  4. Discuss structural solutions like lifting state down or composition.
  5. Emphasize measuring before optimizing.

Key points to hit

  • By default, when a parent re-renders, all its children re-render too, even if their props haven't changed.
  • React.memo wraps a component to skip re-renders when props are shallowly equal.
  • useMemo and useCallback stabilize object and function references so React.memo children can detect unchanged props.
  • Structural changes like moving state closer to where it's used or using composition to avoid re-rendering large subtrees are often more effective than memoization.

Common mistakes

  • Wrapping every component in React.memo and every value in useMemo as a default practice, which adds overhead and complexity without measured benefit.
  • Not considering structural solutions first, which often eliminate the problem entirely without any memoization.

Sample answer

The first thing I do is understand why the re-render is happening. By default, when a parent re-renders, all children re-render regardless of props. The most impactful fix is often structural. Moving state closer to where it's needed means fewer components are in the re-render path.

Using composition by passing components as children can bypass intermediate re-renders. When structural changes aren't enough, React.memo prevents a child from re-rendering when its props haven't changed by shallow comparison.

But React.memo only helps if the props are actually stable, which is why you pair it with useMemo for objects and useCallback for functions passed as props. I always measure first using React DevTools Profiler to identify which re-renders are actually expensive before adding optimization. Most re-renders are fast and don't need optimization.

How to level up

  • Mention that the React compiler (React Forget) will eventually auto-memoize components and values, reducing the need for manual useMemo and useCallback.
  • Discuss how context splitting into multiple contexts by update frequency prevents unrelated consumers from re-rendering.
  • Point out that virtualizing long lists with react-window or react-virtuoso eliminates the cost of re-rendering thousands of off-screen items.

Follow-up questions to expect

  • How do you identify which re-renders are actually causing performance problems?
  • What is the React compiler and how will it change memoization patterns?
  • Can you explain a time you improved performance with structural changes instead of memoization?
Practice this question with AI feedback →
What techniques would you use to optimize a slow React application?
medium

What they're really asking

This tests your ability to systematically diagnose and fix performance bottlenecks in React applications. The interviewer wants to see if you understand the most impactful optimization techniques and can prioritize them correctly.

How you'll be scored

Weak

Lists generic optimizations like 'use useMemo' without understanding when or why to apply them.

Average

Mentions correct techniques like React.memo and code splitting but lacks systematic approach to identifying bottlenecks.

Strong

Demonstrates a methodical process starting with profiling, then applying targeted optimizations based on actual measurements.

How to structure your answer

  1. Start with profiling to identify actual bottlenecks using React DevTools.
  2. Optimize re-renders with React.memo, useMemo, and useCallback where needed.
  3. Implement code splitting for bundle size reduction.
  4. Consider virtualization for large lists.
  5. Optimize images and other assets.

Key points to hit

  • Always profile first using React DevTools Profiler to find real performance issues, not assumed ones.
  • Focus on preventing unnecessary re-renders through React.memo for components and useMemo/useCallback for expensive calculations.
  • Implement lazy loading with React.lazy() and Suspense to reduce initial bundle size.
  • Use virtualization libraries like react-window for lists with thousands of items to only render visible elements.

Common mistakes

  • Applying optimizations blindly without measuring first, which adds complexity without proven benefit.
  • Wrapping every component in React.memo or every function in useCallback, creating overhead instead of gains.

Sample answer

I always start by profiling with React DevTools Profiler to identify which components are actually causing slowdowns. Usually I find unnecessary re-renders are the biggest culprit, so I'll wrap expensive components in React.memo and use useMemo for heavy calculations. For bundle size, I implement code splitting with React.lazy() for routes that aren't immediately needed.

If there are large lists, I'll use react-window to virtualize them so only visible items render. The key is measuring before and after each change to ensure the optimization actually helps.

How to level up

  • Use the React DevTools Profiler's interaction tracing to see which user actions trigger the most expensive renders.
  • Consider using React.startTransition for non-urgent updates to keep the UI responsive during heavy operations.
  • Implement proper error boundaries around lazy-loaded components to handle loading failures gracefully.

Follow-up questions to expect

  • How would you handle a situation where React.memo isn't preventing re-renders as expected?
  • What's your approach to optimizing a component that receives frequently changing props?
  • How do you decide between client-side and server-side rendering for performance?
Practice this question with AI feedback →
How does React.memo help improve performance? When does it NOT prevent re-renders?
medium

What they're really asking

This tests your understanding of React.memo's memoization mechanism and edge cases where it fails. The interviewer wants to see if you know when shallow comparison breaks down.

How you'll be scored

Weak

Says React.memo prevents all re-renders without understanding shallow comparison limitations.

Average

Correctly explains React.memo does shallow comparison but gives vague examples of when it fails.

Strong

Explains shallow comparison clearly with specific examples of object/function props that break memoization.

How to structure your answer

  1. Explain React.memo performs shallow comparison of props.
  2. Show how it prevents re-renders when props haven't changed.
  3. Identify when it fails: new objects, inline functions, or reference changes.
  4. Demonstrate solutions like useCallback and useMemo.
  5. Mention custom comparison function option.

Key points to hit

  • React.memo only does shallow comparison, so if props reference new objects or functions, the component will still re-render.
  • Inline functions and objects created during render always have new references, breaking React.memo optimization.
  • Use useCallback for functions and useMemo for objects passed as props to memoized components.
  • You can provide a custom comparison function as the second argument to React.memo for deep comparison if needed.

Common mistakes

  • Passing inline functions or newly created objects as props to React.memo components, negating the optimization.
  • Assuming React.memo will work automatically without considering prop reference stability.

Sample answer

React.memo wraps a component and only re-renders it if its props have changed based on shallow comparison. It fails when props are new objects or functions created during each render, like onClick={() => handleClick()} or style={{color: 'red'}}. Even though the content is the same, the reference is new, so React.memo sees it as changed.

I fix this by using useCallback for event handlers and useMemo for objects, or moving static objects outside the component. For complex scenarios, I can pass a custom comparison function as React.memo's second argument.

How to level up

  • Consider using React.memo with a custom equalityFn that only compares specific props you care about, ignoring frequently changing but irrelevant ones.
  • Use React DevTools Profiler to verify React.memo is actually preventing re-renders and not being bypassed by reference changes.
  • Remember that React.memo adds its own overhead, so only use it for components with expensive rendering or frequent parent updates.

Follow-up questions to expect

  • When would you choose PureComponent over React.memo, or vice versa?
  • How do you handle props drilling when it breaks React.memo optimizations?
  • What's your strategy for debugging why a memoized component is still re-rendering?
Practice this question with AI feedback →
What is code splitting and lazy loading in React? How do you implement them?
medium

What they're really asking

This tests your knowledge of performance optimization through bundle splitting and whether you understand the trade-offs between initial load time and runtime complexity.

How you'll be scored

Weak

Vague explanation of 'splitting code' without concrete implementation details or understanding of when to use it.

Average

Correctly mentions React.lazy and Suspense but doesn't explain the bundling benefits or loading states.

Strong

Explains both the bundling optimization and implementation details, including error handling and loading UX considerations.

How to structure your answer

  1. Define code splitting as breaking bundles into smaller chunks.
  2. Explain React.lazy() for dynamic imports of components.
  3. Show Suspense for handling loading states.
  4. Discuss route-based vs component-based splitting strategies.
  5. Cover error boundaries for failed chunk loading.

Key points to hit

  • Code splitting reduces initial bundle size by loading code only when needed, improving first page load performance.
  • Use React.lazy() with dynamic import() to create components that load asynchronously when first rendered.
  • Wrap lazy components in Suspense boundaries to show loading fallbacks while chunks download.
  • Route-based splitting is usually most effective since users don't visit all routes in one session.

Common mistakes

  • Forgetting to wrap lazy components in Suspense, which causes errors when the component tries to render before loading.
  • Over-splitting into tiny chunks that create more network requests than necessary, hurting performance.

Sample answer

Code splitting breaks your bundle into smaller chunks that load on demand instead of upfront. I use React.lazy() with dynamic imports to create components that only load when needed. For example, const Dashboard = lazy(() => import('./Dashboard')) creates a split point. I wrap these in Suspense with a loading fallback like a spinner.

This is huge for initial page load since users might never visit certain routes. I typically split at the route level first, then consider component-level splitting for heavy features like charts or editors that aren't immediately visible.

How to level up

  • Use webpack's magic comments like /* webpackChunkName: "dashboard" */ in dynamic imports to control chunk naming and grouping.
  • Implement preloading strategies with React.lazy() and intersection observers to load chunks just before users need them.
  • Set up proper error boundaries specifically for lazy components to handle network failures or missing chunks gracefully.

Follow-up questions to expect

  • How would you implement preloading for routes the user is likely to visit next?
  • What's your approach to handling code splitting in a server-side rendered application?
  • How do you measure the effectiveness of your code splitting strategy?
Practice this question with AI feedback →
What is the windowing technique (virtualization) for rendering large lists?
hard

What they're really asking

This tests your knowledge of advanced performance optimization for large datasets and whether you understand the memory and rendering implications of massive DOM trees.

How you'll be scored

Weak

Doesn't understand the concept or suggests rendering all items with basic pagination.

Average

Knows virtualization renders only visible items but lacks implementation details or library knowledge.

Strong

Explains viewport rendering clearly with specific library recommendations and discusses trade-offs like scroll behavior and accessibility.

How to structure your answer

  1. Define windowing as rendering only visible items in viewport.
  2. Explain the performance problem with large DOM trees.
  3. Recommend specific libraries like react-window or react-virtualized.
  4. Discuss implementation considerations like item height calculation.
  5. Address accessibility and scroll behavior challenges.

Key points to hit

  • Windowing renders only the items visible in the viewport plus a small buffer, keeping DOM size constant regardless of list length.
  • Essential for lists with thousands of items since large DOM trees cause memory issues and slow scrolling performance.
  • react-window is the modern, lighter alternative to react-virtualized for most use cases.
  • Requires knowing or calculating item heights beforehand, which can be tricky with dynamic content.

Common mistakes

  • Trying to implement windowing from scratch instead of using proven libraries that handle edge cases.
  • Not considering accessibility implications since screen readers can't navigate items that aren't in the DOM.

Sample answer

Windowing or virtualization only renders the list items currently visible in the viewport, plus a small buffer above and below. Instead of having 10,000 DOM nodes for a large list, you might only have 20 rendered at any time. I use react-window for most cases since it's lighter than react-virtualized.

The tricky part is handling dynamic item heights - you either need fixed heights or use react-window's VariableSizeList with a function that calculates heights. It's crucial for performance when you have thousands of rows, but you lose some accessibility since screen readers can't see unrendered items.

How to level up

  • Use react-window-infinite-loader to combine virtualization with infinite scrolling for truly massive datasets.
  • Implement proper ARIA labels and roles to help screen readers understand the total list size even with virtualization.
  • Consider using ResizeObserver to dynamically measure item heights for content that changes size after rendering.

Follow-up questions to expect

  • How would you handle keyboard navigation in a virtualized list?
  • What's your approach to maintaining scroll position when list items change dynamically?
  • How do you test virtualized components to ensure they work correctly with different viewport sizes?
Practice this question with AI feedback →
Why do inline functions or objects in JSX hurt performance?
medium

What they're really asking

This tests whether you understand how React's reconciliation works and why reference equality matters for preventing unnecessary re-renders in child components.

How you'll be scored

Weak

Doesn't understand that inline functions create new references on every render, causing child re-renders.

Average

Knows inline functions cause re-renders but explanation lacks clarity about reference equality and when it matters.

Strong

Clearly explains reference equality impact on child components with concrete examples and appropriate solutions.

How to structure your answer

  1. Explain that inline functions/objects create new references each render.
  2. Show how this breaks React.memo and PureComponent optimizations.
  3. Demonstrate the problem with a concrete code example.
  4. Present solutions: useCallback, useMemo, or moving definitions outside render.
  5. Clarify when this optimization actually matters.

Key points to hit

  • Inline functions and objects get new references on every render, so child components see them as 'changed' props even when functionally identical.
  • This breaks optimizations in React.memo, PureComponent, and useMemo dependency arrays, causing unnecessary re-renders.
  • Use useCallback for inline functions and useMemo for inline objects passed to optimized child components.
  • Only optimize when you have actual performance problems - the overhead isn't worth it for simple components.

Common mistakes

  • Using useCallback and useMemo everywhere 'just in case', creating more overhead than the problems they solve.
  • Not understanding that the performance issue only matters when passing props to memoized components.

Sample answer

Every time a component renders, inline functions like onClick={() => doSomething()} create brand new function references, even though they do the same thing. When you pass these to child components wrapped in React.memo, the shallow comparison sees a new function and triggers re-renders unnecessarily. Same thing happens with inline objects like style={{color: 'red'}}.

I fix this by using useCallback for functions and useMemo for objects, or moving static values outside the component. But I only do this when I'm actually passing props to memoized components - otherwise the optimization overhead isn't worth it.

How to level up

  • Use ESLint's exhaustive-deps rule to catch missing dependencies in useCallback and useMemo that could cause stale closures.
  • Consider extracting inline handlers to component methods or module-level functions for static behavior that doesn't need closure over props/state.
  • Profile with React DevTools before and after optimization to ensure useCallback/useMemo actually improve performance rather than just adding complexity.

Follow-up questions to expect

  • How do you decide when the overhead of useCallback is worth the optimization benefit?
  • What happens when you forget to include a dependency in useCallback's dependency array?
  • How would you refactor a component that has many inline functions without overusing useCallback?
Practice this question with AI feedback →
How would you optimize the performance of React contexts to reduce re-renders?
hard

What they're really asking

This tests understanding of Context API limitations and advanced optimization patterns. The interviewer wants to see if you can identify that Context re-renders all consumers when value changes and know strategies to prevent unnecessary renders.

How you'll be scored

Weak

Suggests splitting contexts or mentions React.memo without understanding when Context actually causes re-renders.

Average

Correctly identifies that Context re-renders all consumers and mentions splitting contexts or memoization.

Strong

Explains Context re-render behavior, demonstrates multiple optimization strategies with trade-offs, and shows understanding of when optimization is needed.

How to structure your answer

  1. Explain why Context causes performance issues.
  2. Describe the split context pattern.
  3. Show how to use React.memo with Context consumers.
  4. Discuss useMemo for context values.
  5. Explain when these optimizations are worth the complexity.

Key points to hit

  • Context re-renders all consumers when any part of the value object changes, even if components only use specific properties.
  • Split contexts by update frequency - separate read-only data from frequently changing state.
  • Wrap context values in useMemo to prevent new object creation on every render.
  • Use React.memo on consumer components to prevent renders when their specific data hasn't changed.

Common mistakes

  • Creating new objects in Context Provider value prop on every render, causing all consumers to re-render unnecessarily.
  • Over-optimizing by splitting contexts too granularly, making the code harder to maintain than the performance benefit justifies.

Sample answer

Context re-renders all consumers whenever the value changes, which can cause performance issues. I typically split contexts by update frequency - for example, separating user profile data that rarely changes from UI state that updates frequently.

I also wrap the context value in useMemo to prevent creating new objects on every render, and use React.memo on consumer components so they only re-render when their specific data changes. The key is measuring first though, because these optimizations add complexity.

How to level up

  • Consider using a state management library like Zustand or Jotai when you find yourself splitting contexts extensively.
  • Use React DevTools Profiler to identify which context updates are actually causing performance problems before optimizing.
  • Implement a custom hook that selects only the needed data from context to minimize re-renders.

Follow-up questions to expect

  • When would you choose Context over a dedicated state management library like Redux?
  • How would you implement a selector pattern for Context to only re-render when specific data changes?
  • What are the trade-offs between splitting contexts and using a single large context with selectors?
Practice this question with AI feedback →
What is the difference between React.PureComponent and React.Component?
medium

What they're really asking

This tests knowledge of React's built-in optimization tools and understanding of shallow comparison for re-render prevention. The interviewer wants to see if you know when and how to use class component optimization patterns.

How you'll be scored

Weak

Incorrectly explains the difference or doesn't understand shallow comparison concepts.

Average

Correctly states that PureComponent implements shouldComponentUpdate with shallow comparison.

Strong

Explains shallow comparison behavior, when PureComponent helps performance, and potential pitfalls with nested objects.

How to structure your answer

  1. Define what React.Component does by default.
  2. Explain PureComponent's automatic shallow comparison.
  3. Show when shallow comparison prevents unnecessary renders.
  4. Discuss limitations with nested objects and arrays.
  5. Compare to functional component alternatives like React.memo.

Key points to hit

  • React.Component re-renders whenever parent re-renders, regardless of whether props or state actually changed.
  • PureComponent automatically implements shouldComponentUpdate with shallow comparison of props and state.
  • Shallow comparison only checks if object references changed, not deep equality of nested properties.
  • PureComponent can actually hurt performance if you frequently pass new objects or arrays as props.

Common mistakes

  • Using PureComponent while passing new objects or functions as props on every render, which defeats the optimization.
  • Assuming PureComponent will catch changes in nested object properties when only the reference stays the same.

Sample answer

React.Component re-renders whenever its parent re-renders, even if props haven't changed. PureComponent automatically implements shouldComponentUpdate with shallow comparison, so it only re-renders if prop or state references change. This works great for primitive values and prevents unnecessary renders, but it won't catch changes inside nested objects since it only compares references.

If you're passing new objects as props every render, PureComponent can actually slow things down because it's doing extra comparison work for no benefit.

How to level up

  • Use React.memo for functional components instead of converting to PureComponent class components.
  • Consider implementing custom shouldComponentUpdate logic when you need more control than shallow comparison provides.
  • Profile your components to verify that PureComponent actually improves performance in your specific use case.

Follow-up questions to expect

  • How would you implement the equivalent of PureComponent behavior in a functional component?
  • What would happen if you used PureComponent with props that are always new objects?
  • When might you want to implement a custom shouldComponentUpdate instead of using PureComponent?
Practice this question with AI feedback →
How do useMemo and useCallback help improve performance?
medium

What they're really asking

This tests understanding of React's memoization hooks and when expensive computations or function recreation cause performance issues. The interviewer wants to see if you can identify appropriate use cases and avoid over-optimization.

How you'll be scored

Weak

Confuses the two hooks or suggests using them everywhere without understanding the performance trade-offs.

Average

Correctly explains that useMemo caches values and useCallback caches functions to prevent re-creation.

Strong

Explains specific use cases, understands dependency arrays, knows when these optimizations are counterproductive, and can identify performance bottlenecks.

How to structure your answer

  1. Explain what each hook memoizes and why.
  2. Show concrete examples of when they help performance.
  3. Discuss dependency arrays and when memoization breaks.
  4. Explain the cost of memoization itself.
  5. Provide guidance on when to use vs avoid these hooks.

Key points to hit

  • useMemo caches expensive computation results between renders, only recalculating when dependencies change.
  • useCallback caches function references to prevent child components from re-rendering when passed as props.
  • Both hooks have overhead - memoization is only beneficial when the cost of recalculation exceeds the cost of comparison.
  • Missing dependencies or dependencies that change frequently make memoization ineffective.

Common mistakes

  • Wrapping every function with useCallback or every calculation with useMemo without measuring if it actually improves performance.
  • Forgetting dependencies in the dependency array, causing stale closures or missed updates.

Sample answer

useMemo caches the result of expensive calculations so they don't run on every render, while useCallback caches function references to prevent child components from re-rendering unnecessarily. For example, I use useMemo for filtering large lists or complex transformations, and useCallback when passing functions to optimized child components wrapped in React.memo.

The key is only using them when the computation cost or re-render prevention actually outweighs the memoization overhead, because these hooks aren't free.

How to level up

  • Use React DevTools Profiler to measure whether your memoization actually reduces render time before keeping it.
  • Consider moving expensive calculations outside components or to a web worker instead of just memoizing them.
  • Create custom hooks that encapsulate related useMemo and useCallback logic for cleaner component code.

Follow-up questions to expect

  • How would you decide whether a calculation is expensive enough to warrant useMemo?
  • What happens if you omit a dependency from the dependency array in useMemo?
  • Can you give an example where useCallback would be counterproductive?
Practice this question with AI feedback →
How can you optimize state updates for performance in React?
medium

What they're really asking

This tests knowledge of React's batching behavior and state update patterns that affect performance. The interviewer wants to see if you understand how state updates trigger re-renders and can minimize unnecessary updates.

How you'll be scored

Weak

Doesn't understand batching or suggests incorrect patterns like multiple setState calls.

Average

Knows about batching in event handlers and mentions functional updates for multiple state changes.

Strong

Explains automatic batching, functional updates, state structure optimization, and can identify when state updates cause performance problems.

How to structure your answer

  1. Explain React's automatic batching behavior.
  2. Show how to batch updates outside event handlers.
  3. Discuss functional updates for state that depends on previous state.
  4. Cover state structure optimization strategies.
  5. Mention when to separate vs combine state variables.

Key points to hit

  • React automatically batches state updates in event handlers, but requires flushSync or unstable_batchedUpdates for batching in async operations.
  • Use functional updates when new state depends on previous state to avoid stale closure bugs.
  • Flatten state structure and separate frequently changing values from stable ones to reduce re-render scope.
  • Consider useReducer for complex state updates that involve multiple related changes.

Common mistakes

  • Calling setState multiple times with values that depend on current state instead of using functional updates.
  • Creating deeply nested state objects that cause entire subtrees to re-render when only small parts change.

Sample answer

React automatically batches state updates in event handlers, so multiple setState calls only cause one re-render. For complex state, I use functional updates like setState(prev => prev + 1) to avoid stale closure issues. I also structure state carefully - separating frequently changing values from stable ones and keeping related data together.

For really complex state logic with multiple related updates, I switch to useReducer since it naturally batches all changes in a single action.

How to level up

  • Use React 18's automatic batching with startTransition to mark non-urgent updates and keep the UI responsive.
  • Profile state updates with React DevTools to identify which updates cause expensive re-render cascades.
  • Consider state colocation - moving state closer to where it's used can prevent unnecessary re-renders in parent components.

Follow-up questions to expect

  • How does React 18's automatic batching differ from previous versions?
  • When would you choose useReducer over multiple useState calls?
  • How would you optimize a component that updates state very frequently, like during drag operations?
Practice this question with AI feedback →
What causes an infinite re-render loop and how do you debug it?
medium

What they're really asking

This tests debugging skills and understanding of what triggers re-renders in React. The interviewer wants to see if you can systematically identify and fix render loops, which are common but tricky bugs.

How you'll be scored

Weak

Can't identify common causes like missing dependencies or doesn't know how to debug systematically.

Average

Names a few causes like missing useEffect dependencies and mentions using console.log to debug.

Strong

Systematically explains debugging process, identifies multiple root causes, and shows how to use React DevTools effectively for diagnosis.

How to structure your answer

  1. Identify common root causes of infinite renders.
  2. Explain systematic debugging approach.
  3. Show how to use React DevTools and console logging.
  4. Demonstrate fixing patterns for each cause.
  5. Discuss prevention strategies.

Key points to hit

  • Missing or incorrect dependencies in useEffect often cause infinite loops when effects update state they depend on.
  • Creating new objects or functions inside render without memoization can trigger child re-renders that update parent state.
  • State updates inside render (not in effects or handlers) immediately trigger another render cycle.
  • Use React DevTools Profiler to see which components are re-rendering and what's causing the updates.

Common mistakes

  • Adding every variable to useEffect dependencies without understanding why the effect is running repeatedly.
  • Using console.log without also checking React DevTools, missing the component tree context that shows the render cycle.

Sample answer

Infinite re-renders usually happen when a component updates state that triggers its own re-render. I debug systematically by first checking useEffect dependencies - missing dependencies often cause effects to run and update state continuously. I also look for objects or functions created in render that cause child components to re-render and update parent state.

React DevTools Profiler shows me exactly which components are re-rendering, and I add strategic console.logs to trace the update cycle and find where it starts.

How to level up

  • Use React Strict Mode in development to catch side effects that might cause render loops in production.
  • Create a custom hook for debugging re-renders that logs prop and state changes to identify exactly what's triggering updates.
  • Set up ESLint with react-hooks/exhaustive-deps to catch missing dependencies before they cause runtime loops.

Follow-up questions to expect

  • How would you prevent infinite loops when you need to update state based on prop changes?
  • What's the difference between putting an object in useEffect dependencies versus using a ref?
  • How do you handle cases where you intentionally want some dependencies to not trigger the effect?
Practice this question with AI feedback →
What are some performance tips when rendering large lists in React?
medium

What they're really asking

This tests practical experience with real-world performance bottlenecks in React applications. The interviewer wants to see if you can identify list rendering as a common performance problem and apply appropriate solutions.

How you'll be scored

Weak

Only mentions using keys without understanding virtualization or memoization strategies.

Average

Knows about virtualization libraries and basic memoization for list items.

Strong

Covers virtualization, memoization of list items, stable key strategies, pagination versus infinite scroll, and useDeferredValue for search filtering of large lists.

How to structure your answer

  1. Identify why large lists are a performance problem in React.
  2. Introduce virtualization as the primary solution.
  3. Discuss memoization of individual list items.
  4. Cover pagination and infinite scroll alternatives.
  5. Mention concurrent features for list filtering.

Key points to hit

  • Virtualization (windowing) only renders items visible in the viewport using libraries like react-window or react-virtuoso, reducing DOM nodes from thousands to dozens.
  • Wrapping list item components in React.memo prevents re-rendering unchanged items when the list state updates.
  • Stable keys from data IDs prevent unnecessary unmount/remount cycles that destroy state and hurt performance.
  • Pagination or infinite scroll limits the total number of rendered items instead of loading everything at once.

Common mistakes

  • Not considering virtualization first, which provides the biggest performance gain for large lists by orders of magnitude.
  • Using array indices as keys for lists that can be reordered, filtered, or modified, which causes incorrect component reuse and state bugs.

Sample answer

The biggest win for large lists is virtualization. Libraries like react-window and react-virtuoso only render the items currently visible in the viewport plus a small buffer. Instead of mounting 10,000 DOM nodes, you might render 20 at a time. That alone transforms performance.

Beyond that, I wrap list item components in React.memo so unchanged items don't re-render when the list data updates. I always use stable keys from the data like database IDs rather than array indices. For search or filter functionality on large lists, useDeferredValue keeps the input responsive while the filtered list renders in the background.

And depending on the use case, pagination or infinite scroll can replace rendering the full list entirely. I usually start with virtualization since it gives the most dramatic improvement.

How to level up

  • Mention that react-virtuoso handles dynamic row heights automatically while react-window requires known heights, which affects library choice.
  • Discuss using requestAnimationFrame chunking to break up initial rendering of large lists across multiple frames when virtualization isn't feasible.
  • Point out that the content-visibility CSS property can provide native browser-level virtualization for simpler cases without a library.

Follow-up questions to expect

  • How does virtualization work under the hood?
  • When would you choose pagination over infinite scroll?
  • How would you handle variable-height items in a virtualized list?
Practice this question with AI feedback →
What causes the "Too many re-renders" error?
medium

What they're really asking

This tests debugging skills and understanding of React's render cycle protection. The interviewer wants to see if you can identify the common patterns that trigger this error and fix them correctly.

How you'll be scored

Weak

Cannot explain what triggers the error or suggests ineffective fixes.

Average

Knows that calling setState during render causes the error.

Strong

Identifies multiple causes including direct setState calls in render, inline function calls in JSX event handlers, and useEffect without dependencies, and shows the correct fix for each.

How to structure your answer

  1. Explain what the error means: React detected an infinite render loop.
  2. Show the most common cause: calling setState directly in the render body.
  3. Show the event handler mistake: calling a function instead of passing a reference.
  4. Explain the useEffect cause with missing or incorrect dependencies.
  5. Provide the correct pattern for each case.

Key points to hit

  • React limits the number of nested renders to prevent infinite loops. This error means your component entered a set-state-then-render cycle.
  • The most common cause is calling setState directly in the component body, not inside an event handler or effect.
  • Writing onClick={handleClick()} with parentheses calls the function during render instead of passing it as a callback.
  • useEffect without a dependency array that sets state also triggers this when the state change causes the effect to run again.

Common mistakes

  • Not distinguishing between passing a function reference (onClick={handleClick}) and calling a function (onClick={handleClick()}) in JSX.
  • Fixing the error by adding a condition around setState instead of fixing the root cause of why it's called during render.

Sample answer

This error means React detected an infinite render loop and stopped it. The most common cause I see is calling a state setter directly in the component body. Something like setCount(count + 1) at the top level of your function component runs during render, triggers a re-render, which runs it again, and so on.

The fix is moving it into a useEffect with appropriate dependencies. The second common cause is an event handler mistake. Writing onClick={setCount(count + 1)} with parentheses calls setCount immediately during render. The fix is onClick={() => setCount(count + 1)} or onClick={handleClick} without parentheses.

The third cause is a useEffect that sets state without a dependency array, or with dependencies that change on every render. I debug this by looking for setState calls that aren't wrapped in event handlers or effects with correct dependencies.

How to level up

  • Mention that React's render limit is typically around 50 nested updates, which helps distinguish infinite loops from legitimate deep component trees.
  • Discuss how useReducer can sometimes prevent this error by combining related state updates that would otherwise cascade.
  • Point out that React StrictMode double-rendering in development can make this error appear when the component has subtle side effects during render.

Follow-up questions to expect

  • How would you debug this error in a complex component with many state updates?
  • What is the difference between onClick={fn} and onClick={fn()} in JSX?
  • Can conditional setState calls during render ever be valid in React?
Practice this question with AI feedback →
Why does a child component lose input focus after typing, and how do you fix it?
hard

What they're really asking

This tests deep understanding of React's reconciliation and component identity. The interviewer wants to see if you can diagnose a common but tricky bug caused by component definitions inside render functions or unstable keys.

How you'll be scored

Weak

Cannot identify the cause or suggests workarounds like autoFocus instead of fixing the root problem.

Average

Knows it's related to the component being remounted but can't explain why.

Strong

Identifies component definition inside render or unstable keys as the root causes, explains how React's reconciliation unmounts and remounts components with new identity, and provides the correct structural fix.

How to structure your answer

  1. Describe the symptom: input loses focus on every keystroke.
  2. Explain the root cause: component remounting instead of re-rendering.
  3. Show how defining components inside render functions causes this.
  4. Show how unstable keys cause this.
  5. Provide the correct fix for each cause.

Key points to hit

  • When a component is remounted instead of re-rendered, its DOM elements are destroyed and recreated, which resets focus.
  • Defining a component inside another component's render function creates a new function reference every render, so React treats it as a different component type.
  • Using unstable keys like Math.random() or index on reorderable lists forces React to unmount and remount elements.
  • The fix is to move component definitions outside of render functions and use stable data-based keys.

Common mistakes

  • Using autoFocus as a band-aid instead of fixing the structural issue that causes remounting.
  • Not recognizing that inline component definitions are the issue when the component seems to be correctly structured.

Sample answer

This is almost always caused by the component being remounted instead of re-rendered. When React sees what it thinks is a new component type at the same position, it unmounts the old one and mounts a fresh one. That destroys the DOM node and focus is lost.

The most common cause is defining a component inside another component's render function. Every render creates a new function, so React sees a new component type each time. The input mounts fresh on every keystroke. The fix is simple: move the component definition outside the parent component. The second common cause is unstable keys.

If you use Math.random() or something that changes on each render as a key, React remounts the element. Use stable IDs from your data instead. I once spent an hour debugging this only to find a FormField component was defined inline inside a Form component. Moving it to its own file fixed it immediately.

How to level up

  • Mention that React DevTools shows mount versus update in the Profiler, which helps distinguish remounting from re-rendering.
  • Discuss how dynamic component creation with React.createElement(componentMap[type]) can also cause this if the map is recreated each render.
  • Point out that this bug is especially common in form builders or dynamic layout systems where component types are determined at runtime.

Follow-up questions to expect

  • How would you use React DevTools to confirm a component is remounting versus re-rendering?
  • What other problems does component remounting cause besides losing focus?
  • How does React determine component identity during reconciliation?
Practice this question with AI feedback →
How does useLayoutEffect cause layout thrashing?
hard

What they're really asking

This tests understanding of browser rendering pipeline interactions with React's effect model. The interviewer wants to see if you know when useLayoutEffect is appropriate versus harmful, and understand the concept of forced synchronous layouts.

How you'll be scored

Weak

Cannot explain the difference between useEffect and useLayoutEffect or what layout thrashing means.

Average

Knows useLayoutEffect runs synchronously before paint and can block rendering.

Strong

Explains the browser layout/paint cycle, how reading and writing DOM measurements in useLayoutEffect can force repeated layouts, and when useLayoutEffect is the right choice despite the risks.

How to structure your answer

  1. Explain when useLayoutEffect runs versus useEffect.
  2. Define layout thrashing and forced synchronous layouts.
  3. Show how reading then writing DOM properties in a loop causes thrashing.
  4. Explain when useLayoutEffect is necessary and appropriate.
  5. Provide guidelines for safe usage.

Key points to hit

  • useLayoutEffect fires synchronously after DOM mutations but before the browser paints, blocking visual updates until it completes.
  • Layout thrashing happens when you alternate between reading layout properties (offsetHeight, getBoundingClientRect) and writing style changes, forcing the browser to recalculate layout multiple times.
  • Each read after a write forces a synchronous layout recalculation because the browser needs accurate values that reflect the pending changes.
  • useLayoutEffect is correct when you need to measure DOM and apply changes before the user sees the initial render, like positioning tooltips or preventing visual flicker.

Common mistakes

  • Using useLayoutEffect by default instead of useEffect, blocking paint for work that doesn't need synchronous DOM measurement.
  • Reading and writing DOM properties in alternating patterns inside useLayoutEffect instead of batching all reads first and then all writes.

Sample answer

useLayoutEffect runs synchronously after React updates the DOM but before the browser paints. That means anything inside it blocks the visual update. Layout thrashing happens when you alternate between reading and writing DOM properties. Say you read element.offsetHeight, then set element.style.height, then read another element.offsetWidth.

Each read after a write forces the browser to synchronously recalculate layout to give you accurate numbers. If you do this in a loop or across many elements, you can trigger dozens of layout recalculations in a single frame.

The correct approach is to batch all reads first, then batch all writes. useLayoutEffect itself is the right tool when you need to measure the DOM and apply changes before paint, like positioning a tooltip relative to its target.

But for most effects, useEffect is better because it runs after paint and doesn't block the visual update.

How to level up

  • Mention that the Performance panel in Chrome DevTools shows forced reflows with a purple "Layout" event that has a warning icon, making thrashing visible.
  • Discuss using requestAnimationFrame inside useLayoutEffect to defer writes to the next frame when you can't batch reads and writes together.
  • Point out that useLayoutEffect causes a warning during SSR because it can't run on the server. Use useEffect with a mounted check for SSR-compatible code.

Follow-up questions to expect

  • When is useLayoutEffect the correct choice over useEffect?
  • How would you batch DOM reads and writes to avoid layout thrashing?
  • What does the useLayoutEffect SSR warning mean and how do you handle it?
Practice this question with AI feedback →

State Management Questions (20)

Explain the Context API in React. What are its use cases?
medium

What they're really asking

This tests understanding of React's built-in mechanism for sharing data across the component tree. The interviewer wants to see if you understand the full API surface, appropriate use cases, and the performance characteristics that limit when context is a good choice.

How you'll be scored

Weak

Vaguely describes context as a way to pass data without props but cannot explain the API or limitations.

Average

Explains createContext, Provider, and useContext correctly with basic use cases like theme and auth.

Strong

Covers the full API including default values, multiple contexts, consumer re-render behavior, and when context is not the right choice due to performance concerns.

How to structure your answer

  1. Explain the problem context solves: prop drilling.
  2. Walk through the createContext, Provider, useContext workflow.
  3. List appropriate use cases.
  4. Explain re-render behavior and performance implications.
  5. Mention when context is not the right solution.

Key points to hit

  • Context provides a way to share values across a component tree without explicitly passing props through every intermediate level.
  • The workflow is createContext with a default value, wrap consumers in a Provider with a value prop, and read with useContext in any descendant.
  • Best use cases are theme, locale, auth status, and other values that are read by many components but change infrequently.
  • When the context value changes, all components calling useContext for that context re-render, regardless of whether they use the specific part that changed.

Common mistakes

  • Using context for frequently-changing values like form state or animation values, which causes excessive re-renders across all consumers.
  • Not understanding that the default value in createContext is only used when a component has no matching Provider above it in the tree.

Sample answer

The Context API solves prop drilling by letting you share data across a component tree without passing props through every level. You start with createContext to create a context object with an optional default value. Then you wrap part of your tree with a Provider component that supplies a value.

Any descendant component can call useContext to read that value directly, no matter how deep it is. I use it for values that many components need but that change rarely. Theme preferences, authentication state, locale settings, and feature flags are classic examples. The important limitation is performance.

When the Provider's value changes, every component that consumes that context re-renders. This is why you should not put rapidly changing state like search queries or mouse positions into context. For high-frequency updates, a state management library like Zustand handles selective re-rendering much better.

How to level up

  • Mention splitting context by update frequency, like having a ThemeContext and a UserContext instead of one AppContext, to minimize unnecessary re-renders.
  • Discuss memoizing the value object with useMemo to prevent consumer re-renders when the Provider's parent re-renders but the value hasn't actually changed.
  • Point out that the displayName property on context objects improves debugging by showing meaningful names in React DevTools.

Follow-up questions to expect

  • How would you optimize a context that causes too many re-renders?
  • What happens if a component uses useContext but there is no Provider above it?
  • How do you test components that depend on context values?
Practice this question with AI feedback →
When should you use Redux over the Context API?
medium

What they're really asking

This tests your understanding of when complexity justifies tooling overhead and whether you can make practical architecture decisions based on app scale and team needs.

How you'll be scored

Weak

Says Redux is always better or always worse, or confuses technical capabilities with practical decision-making.

Average

Lists correct technical differences but doesn't connect them to real decision criteria like team size or app complexity.

Strong

Explains decision criteria based on app scale, team experience, and maintenance trade-offs with specific examples.

How to structure your answer

  1. Acknowledge both are valid state management solutions.
  2. Define the complexity threshold where Redux becomes worthwhile.
  3. Compare developer experience and learning curve considerations.
  4. Give specific scenarios for each choice.

Key points to hit

  • Context API is simpler for basic state sharing but can cause performance issues with frequent updates.
  • Redux shines with complex state logic, time-travel debugging, and predictable updates across large teams.
  • Consider team familiarity and onboarding costs when choosing between them.
  • Context works well for theme, auth, or configuration data that changes infrequently.

Common mistakes

  • Claiming Context API always causes performance problems or that Redux is always overkill.
  • Not considering team experience and maintenance burden in the decision.

Sample answer

I choose Redux when the app has complex state interactions, like an e-commerce cart with inventory updates, user preferences, and real-time pricing. Redux's predictable state updates and debugging tools become valuable here. For simpler cases like sharing user authentication or theme settings, Context API is sufficient and keeps the bundle smaller.

The key factor is whether your state logic benefits from Redux's structured approach to updates, or if you just need to avoid prop drilling.

How to level up

  • Consider Redux Toolkit as the modern default for Redux implementation to reduce boilerplate.
  • Mention that Context can be combined with useReducer for Redux-like patterns without the library overhead.

Follow-up questions to expect

  • How would you handle performance issues with Context API if you encountered them?
  • What would make you migrate from Context to Redux in an existing application?
  • How do you structure multiple contexts to avoid provider hell?
Practice this question with AI feedback →
What is the difference between React Context and React Redux?
medium

What they're really asking

This tests whether you understand the architectural differences between React's built-in state sharing and Redux's external state management model.

How you'll be scored

Weak

Confuses Context with Redux or gives vague answers about 'global state' without explaining the mechanisms.

Average

Correctly explains that Context is React built-in and Redux is external but lacks detail on implementation differences.

Strong

Explains provider vs store patterns, subscription mechanisms, and how each handles updates and re-renders.

How to structure your answer

  1. Explain Context as React's built-in state sharing mechanism.
  2. Describe Redux as an external predictable state container.
  3. Compare how each handles state updates and subscriptions.
  4. Contrast their debugging and development tools.

Key points to hit

  • Context uses provider-consumer pattern within React's component tree and triggers re-renders through normal React mechanisms.
  • Redux maintains state outside React in a single store and uses subscriptions to trigger updates.
  • Context values change through setState or useReducer, while Redux state changes only through dispatched actions and reducers.
  • Redux provides time-travel debugging and middleware support that Context lacks natively.

Common mistakes

  • Saying Context and Redux solve exactly the same problems with the same trade-offs.
  • Confusing Context's re-render behavior with Redux's subscription model.

Sample answer

Context API is React's built-in way to share state down the component tree using providers and consumers. When context value changes, all consuming components re-render automatically. Redux is an external library that maintains state in a single store outside of React.

Components subscribe to specific parts of the Redux state and only re-render when those parts change. Redux requires actions and reducers for all state changes, making updates more predictable but requiring more setup than Context's direct state updates.

How to level up

  • Explain that Context can cause performance issues because all consumers re-render when any part of the context value changes.
  • Mention that Redux's connect or useSelector can prevent unnecessary re-renders through shallow equality checks.

Follow-up questions to expect

  • How would you optimize Context API to prevent unnecessary re-renders?
  • What middleware would you use with Redux and why?
  • How does Redux handle async actions compared to useEffect with Context?
Practice this question with AI feedback →
How do you decide between using React state, context, and external state managers?
hard

What they're really asking

This tests your ability to make architectural decisions based on state complexity, sharing requirements, and long-term maintainability across different application scales.

How you'll be scored

Weak

Provides generic rules without considering specific use cases or gives contradictory advice about when to use each approach.

Average

Lists valid criteria but doesn't explain how to evaluate trade-offs or provide decision frameworks.

Strong

Provides clear decision criteria with examples and explains how requirements evolution affects the choice over time.

How to structure your answer

  1. Start with local component state as the default choice.
  2. Define when to lift state up vs using Context for sharing.
  3. Identify complexity thresholds that justify external state managers.
  4. Explain how team size and app lifecycle affect the decision.

Key points to hit

  • Start with useState and only lift state when multiple components need the same data.
  • Use Context for data that many components need but changes infrequently, like user authentication or app configuration.
  • Choose external state managers when you need complex state logic, optimistic updates, or sophisticated caching.
  • Consider team experience and debugging requirements when deciding between solutions.

Common mistakes

  • Jumping to complex solutions too early instead of starting simple and evolving.
  • Ignoring performance implications of Context with frequently changing values.

Sample answer

I start with local useState and only move state up when components need to share it. If I'm passing props through multiple levels without using them, I'll consider Context, especially for things like user settings that don't change often.

When I have complex state interactions, like coordinating between real-time data, form state, and API caching, I'll reach for something like Zustand or Redux Toolkit. The key is starting simple and adding complexity only when the current solution becomes painful to maintain.

How to level up

  • Consider modern alternatives like Zustand or Jotai that provide Redux benefits with less boilerplate.
  • Mention that you can mix approaches - local state for UI, Context for configuration, and external managers for business logic.

Follow-up questions to expect

  • How do you handle state that needs to persist across page refreshes?
  • What patterns do you use to avoid prop drilling without Context?
  • How do you decide when to split state into multiple stores or contexts?
Practice this question with AI feedback →
What is Redux? What are its core principles?
medium

What they're really asking

This tests your understanding of Redux fundamentals and whether you can explain the predictable state management principles that make Redux valuable for complex applications.

How you'll be scored

Weak

Vague explanation of Redux as 'global state' without mentioning actions, reducers, or the unidirectional flow.

Average

Correctly identifies Redux components (store, actions, reducers) but doesn't explain why these principles matter.

Strong

Explains the three core principles with examples and connects them to benefits like predictability and debugging.

How to structure your answer

  1. Define Redux as a predictable state container.
  2. Explain the three core principles with examples.
  3. Describe the unidirectional data flow pattern.
  4. Connect principles to practical benefits like debugging and testing.

Key points to hit

  • Single source of truth means all state lives in one store, making it easier to track and debug.
  • State is read-only and can only change through actions, making updates predictable and traceable.
  • Changes are made with pure functions (reducers) that take current state and action, returning new state.
  • This pattern enables time-travel debugging, easy testing, and predictable state transitions.

Common mistakes

  • Confusing Redux principles with implementation details like middleware or React bindings.
  • Not explaining why these constraints are beneficial rather than just restrictive.

Sample answer

Redux is a predictable state container based on three principles. First, single source of truth means your entire app state lives in one store object. Second, state is read-only and only changes through dispatching actions, so you can trace exactly what caused each state change.

Third, changes happen through pure reducer functions that take the current state and an action, then return a new state without mutations. These constraints make your app's behavior predictable and enable powerful debugging tools like time-travel debugging.

How to level up

  • Mention Redux Toolkit as the recommended modern way to use Redux with less boilerplate.
  • Explain how these principles enable features like optimistic updates and undo/redo functionality.

Follow-up questions to expect

  • How do you handle async operations in Redux?
  • What middleware have you used with Redux and why?
  • How do you structure your reducer logic for complex state updates?
Practice this question with AI feedback →
What is the Flux pattern? How is Redux different from Flux?
medium

What they're really asking

This tests your understanding of the evolution from Flux architecture to Redux and whether you know how Redux simplified the original Flux pattern while keeping its benefits.

How you'll be scored

Weak

Confuses Flux and Redux or can't explain the dispatcher concept and why Redux removed it.

Average

Identifies basic differences like single vs multiple stores but doesn't explain the architectural improvements.

Strong

Explains Flux's dispatcher pattern, how Redux simplified it, and why the changes improve developer experience.

How to structure your answer

  1. Explain Flux as the architectural pattern with four components.
  2. Describe Redux as a simplified implementation of Flux principles.
  3. Compare key differences like single store vs multiple stores.
  4. Explain why Redux's simplifications are beneficial.

Key points to hit

  • Flux is an architecture pattern with Actions, Dispatcher, Stores, and Views in unidirectional flow.
  • Redux eliminates the dispatcher by having actions go directly to reducers, simplifying the flow.
  • Flux typically uses multiple stores while Redux uses a single store with multiple reducers.
  • Redux makes the pattern more predictable by removing store interdependencies and waitFor complexity.

Common mistakes

  • Thinking Redux and Flux are completely different concepts rather than Redux being an evolution of Flux.
  • Not understanding why eliminating the dispatcher simplifies state management.

Sample answer

Flux is Facebook's architecture pattern with Actions, Dispatcher, Stores, and Views in unidirectional flow. The dispatcher coordinates between multiple stores and handles dependencies with waitFor. Redux simplifies this by removing the dispatcher entirely - actions go directly to reducers. Instead of multiple stores, Redux uses one store with multiple reducers.

This eliminates the complexity of store interdependencies while keeping Flux's predictable unidirectional flow. Redux's approach makes state changes more straightforward to reason about and debug.

How to level up

  • Mention that Redux's single store makes hot reloading and time-travel debugging much simpler than with multiple Flux stores.
  • Explain that Redux reducers are pure functions, which makes testing easier than Flux stores with internal state.

Follow-up questions to expect

  • What problems did the Flux dispatcher solve that Redux handles differently?
  • How would you implement something like waitFor in Redux if you needed it?
  • What other Flux implementations have you worked with besides Redux?
Practice this question with AI feedback →
What is the difference between local state and global state?
medium

What they're really asking

This tests architectural thinking about state management and where different types of data should live. The interviewer wants to see if you can make practical decisions about state placement based on scope and usage patterns.

How you'll be scored

Weak

Cannot clearly differentiate or says all state should be global for convenience.

Average

Correctly defines local state as component-specific and global state as app-wide, with basic examples.

Strong

Explains scope, lifetime, and access patterns for each, gives clear decision criteria, and discusses the performance and maintainability implications of misplacing state.

How to structure your answer

  1. Define local state and its scope.
  2. Define global state and its scope.
  3. Give concrete examples of each.
  4. Provide decision criteria for choosing between them.
  5. Discuss consequences of misplacing state.

Key points to hit

  • Local state lives in a single component (useState/useReducer) and is only accessible to that component and its children via props.
  • Global state is accessible across the entire application or large sections of it, typically managed by Context, Redux, Zustand, or similar tools.
  • Local state examples: form input values, toggle states, component-specific UI state like dropdown open/closed.
  • Global state examples: authenticated user data, theme preference, shopping cart, notification queue.

Common mistakes

  • Making everything global for convenience, which couples unrelated components and makes the app harder to test and reason about.
  • Keeping state local when multiple unrelated components need it, leading to prop drilling or duplicated state that gets out of sync.

Sample answer

Local state is owned by a single component and managed with useState or useReducer. It exists only while that component is mounted, and other components can only access it through props. Things like whether a dropdown is open, the current value of a text input, or a form's validation errors are local state.

Global state is accessible across the entire app or a large section of it. It persists independent of any single component's lifecycle. User authentication data, theme preferences, a shopping cart, or notification queues are global state. My rule of thumb is to start local and lift only when needed.

If only one component and its direct children need the data, keep it local. If unrelated parts of the app need the same data, promote it to global. Making too much state global creates tight coupling and makes components harder to reuse and test independently.

How to level up

  • Mention that some state is best described as "shared local" where it lives in a common ancestor and passes down through a subtree, which is different from true global state.
  • Discuss how server state (data from APIs) is a separate category that tools like TanStack Query handle better than either local or global state patterns.
  • Point out that collocating state with the components that use it is a key principle that improves both performance and maintainability.

Follow-up questions to expect

  • How do you decide when to lift local state up versus making it global?
  • What happens to global state when the component that created it unmounts?
  • How does server state fit into the local versus global distinction?
Practice this question with AI feedback →
What is the difference between client state and server state?
hard

What they're really asking

This tests modern state management thinking and whether you understand the paradigm shift toward treating remote data differently from local UI state. The interviewer wants to see if you know why dedicated tools like TanStack Query exist.

How you'll be scored

Weak

Treats all state the same or doesn't understand why server state is fundamentally different.

Average

Knows server state comes from APIs and needs caching, but can't articulate the specific challenges.

Strong

Explains ownership, staleness, caching, synchronization, and deduplication challenges of server state, and names appropriate tools for each category.

How to structure your answer

  1. Define client state and its characteristics.
  2. Define server state and its unique challenges.
  3. Explain why they need different management approaches.
  4. Name appropriate tools for each category.
  5. Discuss the impact of this distinction on architecture.

Key points to hit

  • Client state is fully owned by the frontend: UI state, form inputs, modal visibility. It's synchronous, ephemeral, and always up-to-date by definition.
  • Server state is owned by the backend: user profiles, product lists, order history. It's asynchronous, potentially stale, and shared across clients.
  • Server state has unique challenges: caching, background refetching, stale data, optimistic updates, deduplication of concurrent requests, and pagination.
  • Tools like TanStack Query, SWR, and RTK Query are specifically designed for server state, while Redux/Zustand/useState handle client state.

Common mistakes

  • Storing fetched API data in Redux or useState without caching, refetching, or staleness logic, leading to outdated UI and redundant network requests.
  • Not recognizing that server state is shared across the application and should be deduplicated rather than fetched independently in each component.

Sample answer

Client state and server state have fundamentally different characteristics that need different management approaches. Client state is synchronous and fully owned by the frontend. Things like whether a modal is open, which tab is selected, or what the user typed in a search box. It's always current because the client is the source of truth.

Server state is asynchronous data owned by a remote source. User profiles, product listings, comments.

It comes with challenges that client state doesn't have: it can be stale the moment you receive it, multiple users can change it simultaneously, you need caching to avoid redundant requests, and you need strategies for optimistic updates and error rollback. This is why tools like TanStack Query exist.

They handle caching, background refetching, stale time windows, request deduplication, and pagination out of the box. Trying to manage server state with plain useState or Redux means reimplementing all of those features yourself.

How to level up

  • Mention that the staleTime and gcTime (formerly cacheTime) settings in TanStack Query give you fine-grained control over how long data is considered fresh.
  • Discuss how optimistic updates in server state tools let you update the UI immediately while the request is in flight, rolling back if it fails.
  • Point out that React Server Components blur this line further by letting the server own the data fetching and rendering, eliminating client-side server state management for some use cases.

Follow-up questions to expect

  • How does TanStack Query handle cache invalidation and background refetching?
  • What are optimistic updates and when would you use them?
  • How do React Server Components change the client/server state distinction?
Practice this question with AI feedback →
What are some popular state management solutions in React?
medium

What they're really asking

This tests awareness of the React ecosystem and ability to evaluate tools based on trade-offs rather than popularity alone. The interviewer wants to see if you can recommend the right tool for different scenarios.

How you'll be scored

Weak

Only knows Redux or lists tools without understanding their differences.

Average

Names several tools and can describe basic differences between them.

Strong

Categorizes tools by approach (flux, atomic, proxy, server state), explains trade-offs, and gives decision criteria for choosing between them based on project needs.

How to structure your answer

  1. Categorize state management tools by approach.
  2. Cover the major options in each category.
  3. Explain trade-offs between approaches.
  4. Give recommendations based on project size and needs.

Key points to hit

  • Redux/RTK follows the flux pattern with a single store, actions, and reducers. Best for large teams that need predictable patterns and powerful devtools.
  • Zustand is a lightweight hook-based store with minimal boilerplate. Good for medium apps that need shared state without Redux complexity.
  • Jotai and Recoil use an atomic approach where each piece of state is independent. Great for fine-grained reactivity without global store overhead.
  • TanStack Query and SWR handle server state specifically, with caching, refetching, and deduplication built in.

Common mistakes

  • Recommending Redux for every project regardless of size, when simpler tools like Zustand or even useContext work better for smaller apps.
  • Not distinguishing between client state tools and server state tools, which solve fundamentally different problems.

Sample answer

I think about state management in categories. For client state, Redux Toolkit is the established choice for large applications. It gives you predictable patterns, middleware for side effects, and excellent devtools. But it has boilerplate overhead. Zustand is my go-to for medium-sized apps. It's a tiny hook-based store with minimal setup.

You create a store with create, define your state and actions, and use the store hook in components. Very clean. Jotai takes an atomic approach where each piece of state is an independent atom. Components only re-render when the specific atoms they use change. For server state, TanStack Query is the standard.

It handles caching, background refetching, pagination, and optimistic updates. I'd never manage API data with Redux anymore. For small apps, useReducer with useContext is often enough. The decision depends on app complexity, team size, and whether you need the tooling.

How to level up

  • Mention that MobX uses observable proxy objects for automatic reactivity, which is a completely different paradigm from Redux and appeals to developers coming from Vue or Angular.
  • Discuss how Zustand's selector pattern provides fine-grained re-render control similar to Redux selectors but with less boilerplate.
  • Point out that the trend is toward smaller, more focused tools rather than monolithic solutions, with many apps using Zustand for client state and TanStack Query for server state together.

Follow-up questions to expect

  • How would you migrate a Redux app to a simpler state management solution?
  • What makes Zustand different from using useContext for global state?
  • When would you combine multiple state management tools in one app?
Practice this question with AI feedback →
What is MobX and how does it differ from Redux?
medium

What they're really asking

This tests understanding of different state management paradigms, specifically the observable/reactive approach versus the flux/action dispatch pattern. The interviewer wants to see if you can compare architectural philosophies, not just syntax.

How you'll be scored

Weak

Cannot explain MobX or only knows that it's an alternative to Redux without understanding how it works.

Average

Knows MobX uses observables and is more automatic while Redux uses actions and reducers.

Strong

Contrasts the imperative mutable approach of MobX with Redux's immutable action-dispatch pattern, discusses automatic versus explicit reactivity, and explains when each shines.

How to structure your answer

  1. Define MobX and its core concepts: observables, actions, computed values, reactions.
  2. Contrast with Redux's core concepts: store, actions, reducers, selectors.
  3. Compare mutability approaches.
  4. Compare developer experience and boilerplate.
  5. Discuss when each is the better choice.

Key points to hit

  • MobX uses observable state that components automatically track. When an observable changes, only the components that read it re-render, with no manual optimization needed.
  • Redux requires immutable updates through action dispatch and reducers, giving you a complete history of state changes and predictable updates.
  • MobX lets you mutate state directly (within actions), while Redux requires creating new state objects with each update.
  • MobX has less boilerplate and feels more intuitive, while Redux has better debugging tools and more predictable data flow for large teams.

Common mistakes

  • Saying one is strictly better than the other without considering team size, project complexity, and developer experience trade-offs.
  • Not understanding that MobX's automatic tracking means components re-render precisely when their observed data changes, which can be more efficient than Redux selectors for complex dependency graphs.

Sample answer

MobX and Redux solve the same problem with fundamentally different philosophies. MobX is based on observable state. You mark state as observable, and MobX automatically tracks which components read which values. When a value changes, only the components that actually use it re-render. You can mutate state directly inside action functions.

It feels very natural and has minimal boilerplate. Redux takes an immutable, explicit approach. Every change goes through an action, processed by a reducer that returns a new state object. Nothing happens automatically. You explicitly connect components to the store with selectors.

The trade-off is clear: MobX is faster to write and more intuitive for small teams. Redux gives you predictability, time-travel debugging, and clear patterns that scale across large teams. Redux makes every state change traceable. MobX makes state management feel invisible.

How to level up

  • Mention that MobX computed values are like Redux selectors but automatically cached and recomputed only when their dependencies change.
  • Discuss how MobX-State-Tree (MST) adds Redux-like features to MobX including snapshots, time-travel, and middleware while keeping the observable model.
  • Point out that MobX's proxy-based tracking in version 6 eliminated the need for decorators, making it simpler to set up in modern projects.

Follow-up questions to expect

  • How does MobX know which components to re-render when state changes?
  • What are the debugging trade-offs between MobX and Redux?
  • When would you choose MobX over Redux for a new project?
Practice this question with AI feedback →
What are Redux selectors and why should you use them (Reselect)?
medium

What they're really asking

This tests understanding of derived state patterns and memoization in Redux. The interviewer wants to see if you know why selectors matter for both code organization and performance.

How you'll be scored

Weak

Cannot explain what selectors are or why they exist.

Average

Knows selectors extract data from the store and Reselect provides memoization.

Strong

Explains selector composition, memoization to prevent unnecessary re-renders, derived state computation, and how createSelector works with input and output selectors.

How to structure your answer

  1. Define selectors as functions that extract specific data from the Redux store.
  2. Explain why direct store access in components is problematic.
  3. Introduce Reselect and memoized selectors.
  4. Show how createSelector composes input selectors with a result function.
  5. Discuss performance and maintainability benefits.

Key points to hit

  • Selectors are functions that take the Redux state and return a derived or extracted piece of data.
  • Without selectors, components are tightly coupled to the store shape, making refactoring painful.
  • Reselect's createSelector memoizes the output. It only recomputes when its input selectors return new values, preventing unnecessary re-renders.
  • Selectors compose together. You build complex selectors from simple ones, keeping each selector focused and testable.

Common mistakes

  • Computing derived state inside components instead of selectors, which duplicates logic and loses the memoization benefit.
  • Creating a new selector instance inside a component's render function, which defeats memoization because each render gets a fresh cache.

Sample answer

Selectors are functions that extract or derive data from the Redux store. Instead of accessing state.users.byId[state.currentUser.id] directly in a component, you write a selector like selectCurrentUser that encapsulates that logic. This decouples components from the store shape. If you restructure the store, you update the selector, not every component. Reselect adds memoization through createSelector.

You define input selectors that pull raw data from the store, and a result function that computes derived data. If the inputs haven't changed, createSelector returns the cached result without recomputing. This matters because useSelector calls the selector on every dispatch.

Without memoization, a selector that filters an array creates a new reference each time, causing unnecessary re-renders. With createSelector, the filtered array only changes when the source data changes.

How to level up

  • Mention that Redux Toolkit includes createSelector from Reselect by default, so there is no separate installation needed.
  • Discuss using createSelector factories for parameterized selectors, like selectUserById(id), where each ID gets its own memoized selector instance.
  • Point out that RTK's createEntityAdapter provides pre-built selectors for normalized state like selectAll, selectById, and selectIds.

Follow-up questions to expect

  • How does memoization in createSelector prevent unnecessary re-renders?
  • How would you create a parameterized selector that accepts arguments?
  • What happens to selector memoization when the store is restructured?
Practice this question with AI feedback →
What is Redux Thunk vs Redux Saga? What are the differences?
medium

What they're really asking

This tests understanding of middleware approaches for handling side effects in Redux. The interviewer wants to see if you can compare architectural patterns and choose the right tool based on complexity requirements.

How you'll be scored

Weak

Confuses the two or only gives surface-level descriptions without understanding when to use each.

Average

Correctly explains that Thunk uses functions and Saga uses generators but doesn't discuss trade-offs.

Strong

Explains both patterns with examples, discusses when each is appropriate, and mentions testing implications.

How to structure your answer

  1. Explain what each middleware does.
  2. Show code examples of both.
  3. Compare complexity and use cases.
  4. Discuss testing and debugging differences.

Key points to hit

  • Redux Thunk allows action creators to return functions instead of plain objects for async operations.
  • Redux Saga uses generator functions and effects to create more complex async flows.
  • Thunk is simpler for basic async needs, Saga excels at complex orchestration like race conditions or cancellation.
  • Saga provides better testing story through declarative effects.

Common mistakes

  • Thinking you need Saga for all async operations when Thunk handles most cases fine.
  • Not considering team complexity when choosing between them.

Sample answer

Redux Thunk lets action creators return functions instead of plain objects, so you can dispatch async operations. For example, `const fetchUser = (id) => dispatch => fetch('/users/' + id).then(user => dispatch(setUser(user)))`. Redux Saga uses generator functions with effects like `call` and `put` to handle more complex async flows.

I'd use Thunk for simple API calls and user interactions, but Saga when I need to cancel requests, handle race conditions, or coordinate multiple async operations. Saga also makes testing easier because you can step through effects without actually calling APIs.

How to level up

  • Mention Redux Toolkit Query as a modern alternative that handles most async state needs.
  • Discuss how Saga's effects make it easier to reason about complex async flows.

Follow-up questions to expect

  • Have you used Redux Toolkit Query? How does it compare?
  • How would you handle request cancellation in each approach?
  • What testing strategies work best with each middleware?
Practice this question with AI feedback →
How do you handle persistent state in React apps?
medium

What they're really asking

This tests practical knowledge of state persistence patterns and storage APIs. The interviewer wants to see if you understand different persistence strategies and can handle edge cases like storage quotas and synchronization.

How you'll be scored

Weak

Only mentions localStorage without considering edge cases or different persistence needs.

Average

Explains localStorage/sessionStorage usage with basic serialization but misses sync issues.

Strong

Covers multiple storage options, handles edge cases like storage failures, and discusses synchronization between tabs.

How to structure your answer

  1. Identify what needs to persist.
  2. Choose appropriate storage mechanism.
  3. Handle serialization and errors.
  4. Sync state between tabs if needed.

Key points to hit

  • Use localStorage for data that should persist across browser sessions, sessionStorage for tab-specific data.
  • Always wrap storage operations in try-catch blocks because storage can fail or be disabled.
  • Consider using libraries like Redux Persist or custom hooks to abstract storage logic.
  • Handle synchronization between tabs using storage events or broadcast channels.

Common mistakes

  • Not handling storage exceptions which can crash your app in private browsing mode.
  • Forgetting to sync state between tabs when using localStorage.

Sample answer

I typically use localStorage for user preferences and sessionStorage for temporary data like form drafts. I always wrap storage calls in try-catch because private browsing can disable storage. For example, I'll create a custom hook that serializes state to JSON and handles errors gracefully.

For complex apps, I use Redux Persist to automatically sync specific reducers to storage. I also listen for storage events to keep multiple tabs synchronized when users change settings in one tab.

How to level up

  • Consider IndexedDB for larger datasets or complex data structures.
  • Implement storage quotas and cleanup strategies for long-running applications.

Follow-up questions to expect

  • How would you handle storage quota exceeded errors?
  • What's your strategy for migrating persistent state when your app structure changes?
  • How do you test components that depend on persistent state?
Practice this question with AI feedback →
What is the difference between derived state and computed state?
hard

What they're really asking

This tests deep understanding of state patterns and React's rendering model. The interviewer wants to see if you can distinguish between state that should trigger re-renders versus values that are calculated from existing state.

How you'll be scored

Weak

Confuses the concepts or thinks they're the same thing.

Average

Correctly identifies that derived state comes from props/state but doesn't explain performance implications.

Strong

Explains both concepts clearly, shows when to use useMemo vs useState, and discusses anti-patterns like syncing state in useEffect.

How to structure your answer

  1. Define derived state as calculations from existing state/props.
  2. Define computed state as cached expensive calculations.
  3. Show examples using useMemo and useState patterns.
  4. Explain when each approach is appropriate.

Key points to hit

  • Derived state is calculated directly from props or state during render, like filtering a list.
  • Computed state uses useMemo to cache expensive calculations and only recalculates when dependencies change.
  • Avoid syncing derived state into useState with useEffect as this creates bugs and extra renders.
  • Use useMemo for expensive operations, direct calculation for simple transformations.

Common mistakes

  • Using useEffect to sync derived state into useState instead of calculating during render.
  • Overusing useMemo for simple calculations that aren't actually expensive.

Sample answer

Derived state is calculated directly from existing state or props during render, like `const filteredUsers = users.filter(u => u.active)`. Computed state uses useMemo to cache expensive calculations, like `const expensiveValue = useMemo(() => heavyCalculation(data), [data])`. The key difference is that derived state recalculates every render while computed state only recalculates when dependencies change.

I avoid putting derived state into useState with useEffect because that creates unnecessary renders and potential bugs from stale state.

How to level up

  • Consider using selectors with libraries like Reselect for complex derived state patterns.
  • Profile your calculations before adding useMemo, as the memoization itself has overhead.

Follow-up questions to expect

  • How do you decide when a calculation is expensive enough to memoize?
  • What problems arise when you sync derived state with useEffect?
  • How would you handle derived state that depends on multiple components' state?
Practice this question with AI feedback →
How do you handle asynchronous state updates in React?
medium

What they're really asking

This tests understanding of async patterns in React and common pitfalls with state updates. The interviewer wants to see if you can handle race conditions, stale closures, and proper cleanup in async operations.

How you'll be scored

Weak

Only shows basic async patterns without considering race conditions or cleanup.

Average

Correctly uses useEffect for async operations but doesn't handle edge cases like component unmounting.

Strong

Shows proper cleanup with AbortController, handles race conditions, and explains stale closure issues.

How to structure your answer

  1. Set up useEffect for async operations.
  2. Handle race conditions and stale state.
  3. Implement proper cleanup.
  4. Show error handling patterns.

Key points to hit

  • Use useEffect with async functions inside, not async useEffect directly.
  • Implement cleanup with AbortController or boolean flags to prevent state updates after unmount.
  • Handle race conditions where multiple async operations could complete out of order.
  • Always include loading and error states for better user experience.

Common mistakes

  • Making useEffect itself async instead of calling async functions inside it.
  • Not cleaning up async operations leading to memory leaks and state updates on unmounted components.

Sample answer

I handle async state updates in useEffect by calling async functions inside the effect, not making the effect itself async. I use AbortController to cancel requests when the component unmounts or dependencies change.

For example, I'll set a loading flag before the request, use a cleanup function to abort the request, and check if the component is still mounted before setting state. I also handle race conditions by using a boolean flag or the latest request ID to ignore stale responses.

How to level up

  • Consider using libraries like React Query or SWR that handle most async state complexity automatically.
  • Use useCallback for async functions that are dependencies of other hooks to prevent unnecessary effect runs.

Follow-up questions to expect

  • How do you handle optimistic updates in async operations?
  • What's your approach to handling multiple concurrent async requests?
  • How do you test components with complex async state logic?
Practice this question with AI feedback →
What's a common pitfall when using useContext with objects?
medium

What they're really asking

This tests understanding of React's rendering behavior and reference equality. The interviewer wants to see if you know that passing new object references through Context causes all consumers to re-render unnecessarily.

How you'll be scored

Weak

Doesn't recognize that object references matter for Context re-rendering.

Average

Knows that new objects cause re-renders but doesn't show how to fix it properly.

Strong

Explains the reference equality issue, shows useMemo solution, and discusses Context splitting patterns.

How to structure your answer

  1. Explain that Context uses referential equality for re-render decisions.
  2. Show the problem with inline objects.
  3. Demonstrate useMemo solution.
  4. Discuss splitting Context values.

Key points to hit

  • React Context compares values using Object.is, so new object references trigger re-renders in all consumers.
  • Avoid passing inline objects like `value={{user, setUser}}` directly to Context providers.
  • Use useMemo to stabilize object references: `useMemo(() => ({user, setUser}), [user])`.
  • Consider splitting frequently changing values into separate Contexts to minimize re-renders.

Common mistakes

  • Passing inline objects to Context providers causing performance issues.
  • Not considering that even consumers that don't use the changed part of the object will still re-render.

Sample answer

The main pitfall is passing new object references to Context providers, like `value={{user, setUser}}`. Since React uses Object.is to compare Context values, this creates a new object every render and forces all consumers to re-render even if the actual data hasn't changed.

I fix this by wrapping the value in useMemo: `const value = useMemo(() => ({user, setUser}), [user])`. For complex state, I also consider splitting into separate Contexts so components only subscribe to the data they actually need.

How to level up

  • Use React DevTools Profiler to identify unnecessary re-renders caused by Context.
  • Consider using state management libraries like Zustand for complex shared state instead of Context.

Follow-up questions to expect

  • How would you optimize a Context that has both frequently and infrequently changing values?
  • What are the performance implications of deeply nested Context providers?
  • When would you choose Context over prop drilling or external state management?
Practice this question with AI feedback →
How do you combine useReducer with useContext for state management?
medium

What they're really asking

This tests understanding of React's Context API pattern for state management and whether you can architect scalable state solutions. The interviewer wants to see if you understand when this pattern is appropriate and can implement it correctly.

How you'll be scored

Weak

Vague explanation about combining hooks without showing the actual pattern or understanding when to use it.

Average

Correct implementation of the pattern with basic reducer and context setup.

Strong

Complete implementation with proper TypeScript types, error handling, and clear explanation of when this pattern beats simpler alternatives.

How to structure your answer

  1. Create a reducer with actions and state shape.
  2. Set up Context with createContext.
  3. Create a provider component that uses useReducer.
  4. Export custom hooks for consuming the context.
  5. Explain when this pattern is worth the complexity.

Key points to hit

  • Use useReducer for complex state logic with multiple related values.
  • Wrap the reducer and dispatch in separate contexts to prevent unnecessary re-renders.
  • Create custom hooks to encapsulate the context consumption logic.
  • This pattern works best for medium-complexity state that doesn't need external persistence.

Common mistakes

  • Putting both state and dispatch in the same context causes all consumers to re-render when either changes.
  • Using this pattern for simple state that could be handled with useState and prop drilling.

Sample answer

I combine useReducer with useContext by creating a reducer for complex state logic, then providing both the state and dispatch through context. I actually split them into two separate contexts - one for state and one for dispatch - so components only re-render when they actually need to.

I'll create a custom provider component that uses useReducer internally, then export custom hooks like useAppState and useAppDispatch so components don't need to import useContext directly. This pattern works really well for features like a shopping cart or form wizard where you have related state that multiple components need to access.

How to level up

  • Split state and dispatch into separate contexts to minimize re-renders.
  • Use TypeScript to strongly type your actions and state shape.
  • Consider React Query or SWR if your state includes server data.

Follow-up questions to expect

  • When would you choose this over Redux?
  • How do you handle async actions with this pattern?
  • How would you add middleware like logging to this setup?
Practice this question with AI feedback →
How do you update objects and nested objects inside state?
medium

What they're really asking

This tests whether you understand React's immutability requirements and can update nested state correctly. The interviewer wants to see if you avoid common mutation bugs that cause components not to re-render.

How you'll be scored

Weak

Mutates objects directly or shows confusion about why immutability matters in React.

Average

Uses spread operator correctly for shallow updates but struggles with deeply nested objects.

Strong

Demonstrates multiple approaches including spread syntax, functional updates, and discusses when to flatten state structure.

How to structure your answer

  1. Explain why immutability is required in React.
  2. Show spread operator for shallow object updates.
  3. Demonstrate functional updates for dependent changes.
  4. Handle nested objects with multiple spread operations.
  5. Mention when to consider flattening state structure.

Key points to hit

  • Always return new object references, never mutate existing state directly.
  • Use spread operator for shallow updates: setState({...prev, field: newValue})
  • For nested objects, spread at each level: setState({...prev, nested: {...prev.nested, field: value}})
  • Use functional updates when new state depends on previous state to avoid stale closures.

Common mistakes

  • Mutating objects directly which prevents React from detecting changes and re-rendering.
  • Forgetting to spread intermediate levels when updating deeply nested objects.

Sample answer

I always create new object references when updating state because React uses Object.is comparison to detect changes. For shallow updates, I use the spread operator like setState({...user, name: newName}). For nested objects, I spread at each level, so updating a nested address would be setState({...user, address: {...user.address, city: newCity}}).

When the update depends on previous state, I use the functional form to avoid stale closure issues. If I find myself spreading through many nested levels, that's usually a sign I should flatten my state structure.

How to level up

  • Use functional updates when new state depends on current state to avoid race conditions.
  • Consider flattening deeply nested state or using a state management library.
  • Use Object.assign as an alternative to spread for dynamic property updates.

Follow-up questions to expect

  • How would you handle updating an array of objects?
  • When would you consider using useReducer instead?
  • What are the performance implications of deep object spreading?
Practice this question with AI feedback →
How do you update arrays inside state without mutation?
medium

What they're really asking

This tests understanding of array immutability in React state and whether you can perform common array operations without mutation. The interviewer wants to see if you know the correct patterns for adding, removing, and updating array elements.

How you'll be scored

Weak

Uses mutating array methods like push, splice, or sort directly on state arrays.

Average

Uses spread operator and non-mutating methods correctly for basic operations like adding items.

Strong

Demonstrates all array operations (add, remove, update, sort) with immutable patterns and explains when to use map vs filter.

How to structure your answer

  1. Explain why array mutation breaks React's change detection.
  2. Show adding items with spread operator.
  3. Demonstrate removing items with filter.
  4. Show updating specific items with map.
  5. Cover sorting and other operations.

Key points to hit

  • Use spread operator to add items: setItems([...items, newItem]) or [...items.slice(0, index), newItem, ...items.slice(index)]
  • Use filter to remove items: setItems(items.filter(item => item.id !== targetId))
  • Use map to update specific items: setItems(items.map(item => item.id === targetId ? {...item, field: newValue} : item))
  • For sorting, use toSorted() or [...items].sort() to avoid mutating the original array.

Common mistakes

  • Using mutating methods like push, splice, pop, or sort directly on state arrays.
  • Forgetting to return new object references when updating objects within arrays.

Sample answer

I never mutate arrays in React state directly because React won't detect the change. To add items, I use the spread operator like setItems([...items, newItem]). To remove items, I use filter: setItems(items.filter(item => item.id !== deleteId)).

To update a specific item, I use map and only change the target item: setItems(items.map(item => item.id === targetId ? {...item, completed: true} : item)). For sorting, I either use the new toSorted method or spread into a new array first: setItems([...items].sort()).

How to level up

  • Use the functional update pattern when new state depends on current state.
  • Consider useReducer for complex array operations that involve multiple steps.
  • For large arrays, consider virtualization or pagination instead of keeping everything in state.

Follow-up questions to expect

  • How would you handle reordering items in an array?
  • What's the performance impact of these immutable updates?
  • How do you handle arrays of objects with nested properties?
Practice this question with AI feedback →
What is the Immer library and how does it help with state updates?
medium

What they're really asking

This tests knowledge of modern state management tools and whether you understand how Immer solves React's immutability challenges. The interviewer wants to see if you know when additional tooling is worth the complexity.

How you'll be scored

Weak

Never heard of Immer or gives incorrect explanation of how it works.

Average

Understands that Immer allows mutation-like syntax while maintaining immutability but lacks practical examples.

Strong

Explains Immer's proxy-based approach, shows practical examples, and discusses trade-offs including bundle size and learning curve.

How to structure your answer

  1. Explain what Immer is and the problem it solves.
  2. Show how Immer's produce function works.
  3. Compare Immer syntax to manual immutable updates.
  4. Demonstrate useImmer hook for React integration.
  5. Discuss when Immer is worth adding to a project.

Key points to hit

  • Immer uses JavaScript Proxies to track mutations and create immutable copies automatically.
  • The produce function takes current state and a draft function where you can write mutation-like code.
  • useImmer hook replaces useState and lets you mutate state directly in the setter.
  • Immer shines with deeply nested objects but adds bundle size and complexity.

Common mistakes

  • Thinking Immer actually mutates the original objects instead of creating new ones.
  • Using Immer for simple state that doesn't need deep updates.

Sample answer

Immer is a library that lets you write state updates that look like mutations but actually produce immutable copies. It uses JavaScript Proxies to track changes to a draft object, then efficiently creates a new immutable state. Instead of setState({...user, address: {...user.address, city: newCity}}), I can write produce(user, draft => { draft.address.city = newCity }).

React integration is seamless with the useImmer hook. I typically reach for Immer when I'm dealing with complex nested state where the manual spreading gets unwieldy, but I avoid it for simple state since it adds bundle size.

How to level up

  • Use Immer's built-in integration with Redux Toolkit for reducer logic.
  • Immer works well with TypeScript and preserves type safety.
  • Consider the bundle size impact - Immer adds about 14KB minified.

Follow-up questions to expect

  • How does Immer's performance compare to manual immutable updates?
  • Would you use Immer with useReducer?
  • What are the debugging implications of using Immer?
Practice this question with AI feedback →

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Practical / Coding Questions (24)

How do you handle forms in React?
medium

What they're really asking

This tests practical React knowledge for common UI patterns and whether you understand controlled vs uncontrolled components. The interviewer wants to see if you can handle form state, validation, and submission correctly.

How you'll be scored

Weak

Mixes controlled and uncontrolled patterns or doesn't understand the difference between them.

Average

Implements basic controlled forms with useState but lacks validation or error handling.

Strong

Demonstrates both controlled and uncontrolled patterns, includes validation, error handling, and mentions form libraries for complex cases.

How to structure your answer

  1. Choose between controlled and uncontrolled components.
  2. Set up form state management.
  3. Handle form submission and prevent default.
  4. Implement validation and error display.
  5. Discuss when to use form libraries.

Key points to hit

  • Controlled components use React state and onChange handlers for each input.
  • Uncontrolled components use refs and defaultValue, letting the DOM handle state.
  • Always prevent default on form submission and handle async submission states.
  • Form libraries like React Hook Form or Formik are worth it for complex forms with validation.

Common mistakes

  • Mixing controlled and uncontrolled patterns in the same form.
  • Forgetting to prevent default on form submission.

Sample answer

For simple forms, I use controlled components with useState to manage each input's value and onChange handler. I create a handleSubmit function that prevents default and processes the form data. For validation, I typically validate on blur and submission, storing errors in state and displaying them near the relevant fields.

For complex forms with lots of validation rules, I reach for React Hook Form because it reduces re-renders and has great built-in validation. I avoid mixing controlled and uncontrolled patterns in the same form since that creates inconsistent behavior.

How to level up

  • Use React Hook Form for complex forms to minimize re-renders and get better performance.
  • Consider validation libraries like Yup or Zod for schema-based validation.
  • Implement proper loading and error states for async form submissions.

Follow-up questions to expect

  • How do you handle file uploads in forms?
  • What's your approach to form validation timing?
  • How do you handle multi-step forms or wizards?
Practice this question with AI feedback →
How do you handle multiple input fields in a single form?
medium

What they're really asking

This tests your understanding of controlled components and whether you can efficiently manage form state without creating performance bottlenecks or overly complex code.

How you'll be scored

Weak

Suggests creating separate useState for each field or doesn't understand controlled components.

Average

Shows single state object approach with basic onChange handler but lacks optimization awareness.

Strong

Demonstrates single state object, efficient onChange pattern, and mentions validation or performance considerations.

How to structure your answer

  1. Create single state object for all form data.
  2. Build reusable onChange handler using computed property names.
  3. Show validation strategy.
  4. Explain when to optimize further.

Key points to hit

  • Use single state object instead of multiple useState calls to reduce re-renders.
  • Leverage computed property names in onChange handler for clean, maintainable code.
  • Consider useCallback for onChange handler if form is large or frequently re-renders.
  • Validate fields appropriately without blocking user input.

Common mistakes

  • Creating separate useState for each field creates unnecessary complexity and potential performance issues.
  • Forgetting to use computed property names leads to repetitive onChange handlers.

Sample answer

I use a single state object to hold all form fields and create one reusable onChange handler. For example, I'd have const [formData, setFormData] = useState({name: '', email: '', phone: ''}), then const handleChange = (e) => setFormData(prev => ({...prev, [e.target.name]: e.target.value})).

This keeps the component clean and performs well because we're only managing one piece of state. For larger forms, I'd wrap handleChange in useCallback to prevent unnecessary re-renders of child components.

How to level up

  • Use useCallback for the onChange handler in complex forms to prevent child component re-renders.
  • Consider useReducer instead of useState for forms with complex validation logic or multiple related actions.

Follow-up questions to expect

  • How would you handle form validation with this approach?
  • When might you choose useReducer over useState for form management?
  • How would you optimize this for a form with 20+ fields?
Practice this question with AI feedback →
How do you prevent default form submission behavior in React?
easy

What they're really asking

This tests basic React event handling knowledge and whether you understand the difference between React's synthetic events and native DOM events.

How you'll be scored

Weak

Doesn't know about preventDefault() or suggests incorrect approaches like returning false.

Average

Knows to use e.preventDefault() in the onSubmit handler but explanation lacks depth.

Strong

Correctly explains e.preventDefault(), mentions it works on React's SyntheticEvent, and shows proper form submission handling.

How to structure your answer

  1. Use preventDefault() method on the event object.
  2. Show proper onSubmit handler setup.
  3. Explain when and why this is needed.
  4. Demonstrate complete form submission flow.

Key points to hit

  • Call e.preventDefault() in your onSubmit handler to stop the default browser form submission.
  • React's SyntheticEvent works the same as native events for preventDefault()
  • Always handle form submission through React handlers rather than relying on browser defaults.
  • preventDefault() must be called before any async operations in your handler.

Common mistakes

  • Forgetting that React events are SyntheticEvents but preventDefault() works the same way.
  • Trying to return false from the handler instead of using preventDefault()

Sample answer

I call e.preventDefault() in my onSubmit handler to stop the browser's default form submission behavior. So I'd have something like const handleSubmit = (e) => { e.preventDefault(); // then my custom logic like API calls }.

This prevents the page from refreshing and lets me handle the submission entirely through React, whether I'm making an API call or updating local state. The preventDefault() works on React's SyntheticEvent just like it would on a native DOM event.

How to level up

  • Remember that preventDefault() must be called synchronously, before any async operations in your handler.
  • Consider using form libraries like Formik or React Hook Form for complex forms with built-in submission handling.

Follow-up questions to expect

  • What's the difference between preventDefault() and stopPropagation()?
  • How would you handle form submission with validation?
  • When might you want the default form submission behavior?
Practice this question with AI feedback →
How do you pass data between sibling components?
medium

What they're really asking

This tests your understanding of React's unidirectional data flow and whether you know the common patterns for component communication without prop drilling.

How you'll be scored

Weak

Suggests direct communication between siblings or doesn't understand the need for a common parent.

Average

Knows to lift state to common parent but doesn't mention alternative patterns for complex cases.

Strong

Explains lifting state up clearly, mentions callback props for updates, and knows when to consider Context or state management libraries.

How to structure your answer

  1. Lift state to the nearest common parent component.
  2. Pass data down as props and callbacks up for updates.
  3. Show concrete example with two sibling components.
  4. Mention alternatives for complex scenarios.

Key points to hit

  • Move shared state to the closest common parent component that needs to coordinate the siblings.
  • Pass data down through props and use callback functions to let children update the shared state.
  • For deeply nested components, consider Context API to avoid excessive prop drilling.
  • Use state management libraries like Redux or Zustand when sibling communication becomes complex across multiple levels.

Common mistakes

  • Trying to directly pass data between siblings without involving a parent component.
  • Overusing Context for simple sibling communication that could be solved with basic state lifting.

Sample answer

I lift the shared state up to the nearest common parent component. For example, if I have a ProductList and ShoppingCart as siblings, I'd move the cart state to their parent, then pass the cart data down to ShoppingCart as props and pass an addToCart callback down to ProductList.

When a product is clicked, ProductList calls the callback, parent updates state, and ShoppingCart re-renders with new data. For more complex scenarios across many components, I'd consider Context API or a state management library.

How to level up

  • Use Context API when lifting state up creates excessive prop drilling through multiple component levels.
  • Consider custom hooks to encapsulate complex sibling communication logic and make it reusable.

Follow-up questions to expect

  • When would you choose Context API over lifting state up?
  • How would you handle this if the siblings are deeply nested in different parts of the component tree?
  • What are the performance implications of lifting state too high in the component tree?
Practice this question with AI feedback →
How do you lift state up in a React application and why is it necessary?
medium

What they're really asking

This tests your understanding of React's unidirectional data flow principle and whether you recognize when shared state needs to be accessible to multiple components.

How you'll be scored

Weak

Doesn't understand why state needs to move up or suggests incorrect patterns like direct child-to-child communication.

Average

Knows state should move to common parent but explanation lacks clarity on the data flow benefits.

Strong

Clearly explains the concept, shows before/after example, and articulates why this maintains predictable data flow.

How to structure your answer

  1. Define what lifting state up means.
  2. Explain when it's necessary with a concrete example.
  3. Show the transformation from local to lifted state.
  4. Highlight the benefits for maintainability and debugging.

Key points to hit

  • Lift state up when multiple components need to share or synchronize the same data.
  • Move state to the lowest common ancestor that needs to coordinate the child components.
  • This maintains React's unidirectional data flow and keeps state changes predictable.
  • Makes debugging easier because state mutations happen in one place rather than being scattered across components.

Common mistakes

  • Lifting state higher than necessary creates unnecessary re-renders and makes components less reusable.
  • Not understanding that lifting state up is about sharing data, not just moving it randomly.

Sample answer

Lifting state up means moving state from a child component to a parent component when multiple components need to share that data. For example, if I have a temperature converter with separate Celsius and Fahrenheit input components, I'd move the temperature state up to their parent so both inputs stay synchronized.

Instead of each input managing its own state, the parent holds the temperature and passes down values and onChange handlers. This is necessary because it maintains React's unidirectional data flow and ensures a single source of truth.

How to level up

  • Only lift state as high as necessary, lifting too high creates unnecessary re-renders and reduces component reusability.
  • Consider using useReducer instead of useState when lifted state has complex update logic that involves multiple related values.

Follow-up questions to expect

  • How do you decide how high to lift state in the component tree?
  • What are the performance trade-offs of lifting state up?
  • When might you choose Context API instead of lifting state up?
Practice this question with AI feedback →
How do you conditionally render components?
easy

What they're really asking

This tests your knowledge of JSX conditional rendering patterns and whether you understand the trade-offs between different approaches for showing and hiding components.

How you'll be scored

Weak

Only knows one basic pattern or suggests incorrect approaches like CSS display none for conditional logic.

Average

Shows ternary operator and && operator but doesn't explain when to use each.

Strong

Demonstrates multiple patterns, explains use cases for each, and mentions potential pitfalls like falsy values with &&.

How to structure your answer

  1. Show ternary operator for if-else scenarios.
  2. Demonstrate && operator for simple show/hide.
  3. Explain when to use each pattern.
  4. Mention common pitfalls and alternatives.

Key points to hit

  • Use ternary operator (condition ? <ComponentA /> : <ComponentB />) when you need if-else rendering.
  • Use && operator (condition && <Component />) for simple show/hide, but watch for falsy values.
  • Extract complex conditional logic to variables or functions for better readability.
  • Be careful with numbers and strings in && conditions as they can render unexpected values.

Common mistakes

  • Using && operator with numbers can render 0 to the screen instead of nothing.
  • Making JSX unreadable with deeply nested ternary operators instead of extracting logic.

Sample answer

I use the ternary operator for if-else scenarios, like {isLoggedIn ? <Dashboard /> : <LoginForm />}. For simple show/hide, I use the && operator like {showModal && <Modal />}.

However, I'm careful with && because falsy values like 0 can render to the screen, so I'd write {items.length > 0 && <ItemList />} instead of {items.length && <ItemList />}. For complex conditions, I extract the logic to variables first to keep the JSX clean and readable.

How to level up

  • Use Boolean conversion like {!!count && <Component />} to safely handle potentially falsy numbers with &&.
  • Consider moving complex conditional rendering logic to custom hooks or separate functions to keep components clean.

Follow-up questions to expect

  • What happens if you use a number with the && operator?
  • How would you handle conditional rendering with more than two conditions?
  • When might you choose to conditionally render vs conditionally style with CSS?
Practice this question with AI feedback →
How do you render a list of items in React?
easy

What they're really asking

This tests fundamental React skills for transforming data into UI elements. The interviewer wants to see if you understand the map pattern, key prop requirements, and how React handles dynamic lists.

How you'll be scored

Weak

Cannot demonstrate the map pattern or doesn't know about keys.

Average

Shows the array.map pattern with JSX and knows keys are required.

Strong

Explains map with proper key usage, discusses why keys matter for reconciliation, handles edge cases like empty arrays and conditional rendering, and knows when to extract list items into components.

How to structure your answer

  1. Show the basic array.map pattern in JSX.
  2. Explain the key prop requirement and why it exists.
  3. Discuss good key choices versus bad ones.
  4. Cover edge cases like empty lists.
  5. Mention when to extract list items into separate components.

Key points to hit

  • Use array.map() inside JSX to transform data arrays into arrays of React elements.
  • Every element in a mapped list needs a unique key prop so React can efficiently track insertions, deletions, and reordering.
  • Keys should be stable, unique identifiers from your data like database IDs, not array indices or random values.
  • For empty arrays, map returns an empty array which renders nothing. Add conditional rendering for empty state messages.

Common mistakes

  • Using array index as key for lists that can be reordered, filtered, or modified, which causes state bugs and incorrect component reuse.
  • Forgetting to handle the empty list case, leaving users with a blank screen and no indication of what happened.

Sample answer

You render lists in React using the array.map() method inside JSX. You take your data array and transform each item into a React element. For example, items.map(item =>
  • {item.name}
  • ). The key prop is critical. React uses it to identify which items changed, were added, or were removed during reconciliation. Without stable keys, React can't efficiently update the list and might reuse component instances incorrectly, causing state bugs. Always use unique identifiers from your data as keys, like database IDs. Array indices work only for static lists that never reorder or filter. For empty arrays, I add a conditional check to show an empty state message. When list items get complex, I extract them into their own component for readability and to take advantage of React.memo optimization.

    How to level up

    • Mention that you can render multiple elements per list item by wrapping them in a Fragment with a key: <Fragment key={id}>
    • Discuss that React will warn in the console about missing keys but the app still works, making it easy to miss in large codebases.
    • Point out that for very long lists, combining map with virtualization from react-window gives you both clean code and good performance.

    Follow-up questions to expect

    • Why are array indices bad keys for dynamic lists?
    • What happens if two list items have the same key?
    • How would you handle rendering a list that comes from an async API call?
    Practice this question with AI feedback →
    How do you re-render the view when the browser is resized?
    medium

    What they're really asking

    This tests practical knowledge of combining browser APIs with React hooks. The interviewer wants to see if you can handle DOM events properly in React's lifecycle, including cleanup and performance considerations.

    How you'll be scored

    Weak

    Suggests manually calling forceUpdate or doesn't know how to listen for resize events in React.

    Average

    Shows a useEffect with a resize event listener that updates state with window dimensions.

    Strong

    Implements the pattern correctly with cleanup, adds debouncing or throttling for performance, and suggests extracting it into a custom useWindowSize hook.

    How to structure your answer

    1. Set up state to track window dimensions.
    2. Use useEffect to add a resize event listener.
    3. Include cleanup to remove the listener on unmount.
    4. Add debouncing for performance.
    5. Extract into a reusable custom hook.

    Key points to hit

    • Store window dimensions in useState and update them from a resize event handler inside useEffect.
    • The useEffect cleanup function must remove the event listener to prevent memory leaks when the component unmounts.
    • Debounce or throttle the resize handler because the resize event fires at very high frequency and each setState triggers a re-render.
    • Extract this into a useWindowSize custom hook since multiple components often need responsive behavior.

    Common mistakes

    • Forgetting to remove the event listener in the useEffect cleanup, causing memory leaks and state updates on unmounted components.
    • Not debouncing the resize handler, which can cause hundreds of re-renders per second during a resize drag.

    Sample answer

    I use a combination of useState and useEffect. I create state for the window width and height, then in a useEffect I attach a resize event listener to the window. The handler updates the state with the new dimensions. Critically, I return a cleanup function that removes the listener when the component unmounts.

    Since the resize event fires rapidly during a drag, I debounce the handler. Using a 150ms debounce means the component re-renders once after the user stops resizing rather than hundreds of times during. I almost always extract this into a custom useWindowSize hook that returns {width, height}.

    That way any component that needs responsive behavior just calls const {width} = useWindowSize() and reacts to the values. The hook owns the event listener lifecycle completely.

    How to level up

    • Mention ResizeObserver as a modern alternative when you need to track a specific element's size rather than the whole window.
    • Discuss using CSS container queries or media queries for purely visual responsive changes instead of JavaScript re-renders.
    • Point out that matchMedia with useEffect can be more efficient when you only need to know if a breakpoint was crossed, not the exact pixel dimensions.

    Follow-up questions to expect

    • How would you debounce the resize handler without a library?
    • When would you use ResizeObserver instead of window resize events?
    • How does this pattern change with server-side rendering?
    Practice this question with AI feedback →
    How do you fetch data with React Hooks?
    medium

    What they're really asking

    This tests practical knowledge of async operations in React and whether you handle all the states correctly. The interviewer wants to see if you understand the loading/error/data lifecycle and cleanup for abandoned requests.

    How you'll be scored

    Weak

    Shows a basic fetch inside useEffect without handling loading, errors, or cleanup.

    Average

    Handles loading and error states with useEffect and fetch, but doesn't address cleanup or race conditions.

    Strong

    Implements complete data fetching with loading, error, and success states, handles cleanup with AbortController, addresses race conditions, and mentions when to use a dedicated library like TanStack Query.

    How to structure your answer

    1. Set up state for data, loading, and error.
    2. Use useEffect with an async function inside it.
    3. Handle all three states: loading, success, error.
    4. Implement cleanup with AbortController for race conditions.
    5. Mention dedicated data fetching libraries as the production solution.

    Key points to hit

    • Never make the useEffect callback itself async. Instead, define an async function inside it and call it immediately.
    • Track three states: loading (boolean), data (the response), and error (any caught exception)
    • Use AbortController to cancel in-flight requests when the component unmounts or dependencies change, preventing state updates on unmounted components.
    • For production apps, TanStack Query or SWR handle caching, deduplication, refetching, and error retry much better than manual useEffect.

    Common mistakes

    • Making the useEffect callback async directly, which causes the cleanup function to be a Promise instead of a function.
    • Not handling cleanup for in-flight requests, leading to the "can't perform a state update on an unmounted component" warning and potential race conditions.

    Sample answer

    The basic pattern uses useState for data, loading, and error states, plus useEffect to trigger the fetch. You can't make the useEffect callback itself async, so I define an async function inside and call it.

    I set loading to true before the fetch, update data on success, catch errors, and set loading to false in a finally block. The critical part most people miss is cleanup. I create an AbortController, pass its signal to fetch, and abort it in the useEffect cleanup function.

    This handles two problems: cancelling requests when the component unmounts, and preventing race conditions when dependencies change before a request completes. That said, for production code I use TanStack Query. It handles caching, background refetching, retry logic, and request deduplication out of the box. Manual useEffect fetching is good for learning but doesn't scale.

    How to level up

    • Mention that the use hook in React 19 allows reading promises directly during render, simplifying the data fetching pattern with Suspense.
    • Discuss how custom hooks like useFetch can encapsulate the loading/error/data pattern so components stay clean.
    • Point out that AbortController.abort() with a reason argument lets you distinguish between user cancellation and cleanup cancellation in error handling.

    Follow-up questions to expect

    • How does AbortController prevent race conditions in data fetching?
    • Why can't the useEffect callback be async directly?
    • How would TanStack Query simplify this compared to manual useEffect?
    Practice this question with AI feedback →
    How do you implement a debounced search input in React?
    medium

    What they're really asking

    This tests practical knowledge of performance optimization for user inputs and understanding of timing in React's rendering model. The interviewer wants to see if you can implement debouncing correctly with hooks.

    How you'll be scored

    Weak

    Suggests adding a setTimeout directly in the onChange handler without proper cleanup or understanding of debouncing.

    Average

    Implements debouncing with useEffect and a setTimeout, clearing the timeout on cleanup.

    Strong

    Shows multiple approaches including useEffect with cleanup, useDeferredValue as a React-native alternative, and discusses when to debounce the API call versus debounce the state update.

    How to structure your answer

    1. Explain what debouncing means and why search inputs need it.
    2. Show the useEffect approach with setTimeout and cleanup.
    3. Show the useRef approach for storing the timeout ID.
    4. Mention useDeferredValue as a React 18 alternative.
    5. Discuss where to place the debounce: input state vs API call.

    Key points to hit

    • Debouncing delays execution until the user stops typing for a specified duration, preventing an API call on every keystroke.
    • The useEffect approach watches the search term and sets a timeout, with the cleanup function clearing the previous timeout on each new keystroke.
    • Keep the input state updating immediately for responsiveness, and debounce only the API call or filtered result computation.
    • useDeferredValue in React 18 provides a built-in way to defer expensive computations without explicit debounce timing.

    Common mistakes

    • Debouncing the input state itself, which makes the input feel laggy because the typed characters appear with a delay.
    • Not cleaning up the timeout in useEffect, which can result in stale searches executing after the user has typed new characters.

    Sample answer

    I keep two pieces of state: the raw input value that updates on every keystroke for a responsive typing experience, and a debounced value that triggers the actual search. In my useEffect, I watch the input value and set a setTimeout for 300ms. The cleanup function clears the timeout.

    So each keystroke cancels the previous timer and starts a new one. Only when the user pauses for 300ms does the debounced value update and trigger the search. The input always feels instant because it updates synchronously. Only the expensive operation is delayed. In React 18, useDeferredValue can replace this for filtering operations.

    Instead of a timer, React defers the computation and keeps the input responsive. But for API calls, I still prefer explicit debouncing because I want control over the exact delay and I don't want to fire unnecessary network requests.

    How to level up

    • Mention that AbortController should be used with the debounced fetch to cancel in-flight requests when a new search starts.
    • Discuss using a custom useDebounce hook that abstracts the pattern: const debouncedQuery = useDebounce(query, 300)
    • Point out that lodash.debounce stored in a useRef gives you more control including leading/trailing edge execution and cancel/flush methods.

    Follow-up questions to expect

    • What is the difference between debouncing and throttling?
    • How would you cancel an in-flight API request when the debounced value changes?
    • When would useDeferredValue be a better choice than manual debouncing?
    Practice this question with AI feedback →
    How do you implement infinite scroll in React?
    medium

    What they're really asking

    This tests knowledge of scroll-based data loading patterns and browser API integration with React. The interviewer wants to see if you understand the performance implications and can choose the right implementation approach.

    How you'll be scored

    Weak

    Suggests using scroll event listeners without understanding the performance problems or modern alternatives.

    Average

    Knows to use IntersectionObserver to detect when a sentinel element becomes visible and trigger loading.

    Strong

    Implements IntersectionObserver with proper cleanup, handles loading and error states, prevents duplicate requests, and mentions virtualization for long lists.

    How to structure your answer

    1. Explain the two implementation approaches: scroll events vs IntersectionObserver.
    2. Recommend IntersectionObserver as the modern approach.
    3. Describe the sentinel element pattern.
    4. Handle loading states and prevent duplicate fetches.
    5. Discuss combining with virtualization for very long lists.

    Key points to hit

    • IntersectionObserver is preferred over scroll event listeners because it's more performant and doesn't fire on every scroll pixel.
    • Place a sentinel element at the bottom of the list and observe it. When it enters the viewport, fetch the next page of data.
    • Prevent duplicate requests by checking if a fetch is already in progress and if there are more pages to load.
    • For very long lists, combine infinite scroll with virtualization so the DOM doesn't grow unbounded.

    Common mistakes

    • Using scroll event listeners without throttling, which fires hundreds of times per second and causes jank.
    • Not preventing duplicate fetch requests when the user scrolls fast, which can cause duplicated data or race conditions.

    Sample answer

    The modern approach uses IntersectionObserver instead of scroll events. I place an invisible sentinel div at the bottom of the list and use a useEffect to create an IntersectionObserver that watches it. When the sentinel enters the viewport, the observer callback fires and I fetch the next page.

    I track a loading boolean with useRef to prevent duplicate requests, and I check hasNextPage before fetching. The useEffect cleanup disconnects the observer. For the user experience, I show a loading spinner at the bottom while fetching and a "no more results" message when all pages are loaded.

    One important consideration is that as the user scrolls through hundreds of items, the DOM grows unbounded. For long lists, I combine infinite scroll with react-virtuoso, which supports infinite loading natively and only renders visible items.

    How to level up

    • Mention that TanStack Query's useInfiniteQuery hook handles pagination state, caching, and deduplication for infinite scroll out of the box.
    • Discuss using rootMargin on IntersectionObserver to trigger loading before the sentinel is actually visible, creating a seamless prefetch experience.
    • Point out that scroll restoration on navigation is tricky with infinite scroll and may require storing the scroll position and loaded page count in session state.

    Follow-up questions to expect

    • How does IntersectionObserver compare to scroll event listeners for performance?
    • How would you handle scroll position restoration when navigating back to an infinite scroll page?
    • When would you choose pagination over infinite scroll?
    Practice this question with AI feedback →
    How would you implement a custom hook for data fetching?
    medium

    What they're really asking

    This tests understanding of custom hooks patterns and data fetching lifecycle. The interviewer wants to see if you can encapsulate side effects properly and handle loading states, errors, and cleanup.

    How you'll be scored

    Weak

    Shows a basic function that fetches data without handling loading states, errors, or cleanup.

    Average

    Creates a custom hook with useEffect and useState that handles basic loading and error states.

    Strong

    Implements a robust custom hook with proper dependency management, cleanup, and considers edge cases like component unmounting during fetch.

    How to structure your answer

    1. Define the custom hook function with parameters.
    2. Set up state for data, loading, and error.
    3. Implement useEffect for the fetch operation.
    4. Handle cleanup and error cases.
    5. Return the state values and any control functions.

    Key points to hit

    • Use useState to manage data, loading, and error states separately.
    • Include proper dependency array in useEffect to control when fetching occurs.
    • Implement cleanup with AbortController to prevent memory leaks when component unmounts.
    • Return an object with data, loading, error states for easy destructuring.

    Common mistakes

    • Forgetting to handle the case where component unmounts before fetch completes, causing state updates on unmounted components.
    • Not including URL or dependencies in useEffect dependency array, causing stale closures or infinite re-renders.

    Sample answer

    I'd create a custom hook like useFetch that takes a URL and returns data, loading, and error states. Inside, I'd use useState for these three pieces of state, then useEffect to perform the actual fetch.

    The key is using AbortController to cancel the request if the component unmounts, and including the URL in the dependency array so it refetches when the URL changes. I'd return an object like {data, loading, error, refetch} so components can destructure what they need and handle each state appropriately.

    How to level up

    • Add a refetch function that components can call to manually trigger data refresh.
    • Consider adding caching logic to avoid refetching the same data multiple times.
    • Make the hook generic with TypeScript to provide proper typing for the expected data shape.

    Follow-up questions to expect

    • How would you add caching to this custom hook?
    • What happens if the same URL is used by multiple components?
    • How would you handle different HTTP methods like POST or PUT?
    Practice this question with AI feedback →
    How do you implement protected/private routes in React Router?
    medium

    What they're really asking

    This tests understanding of conditional rendering and React Router's component composition patterns. The interviewer wants to see if you can implement authentication flow and route protection properly.

    How you'll be scored

    Weak

    Suggests basic conditional rendering without understanding React Router's component patterns or authentication context.

    Average

    Creates a ProtectedRoute component that checks authentication and redirects, but may miss context integration.

    Strong

    Implements a clean ProtectedRoute wrapper with proper authentication context integration and handles edge cases like loading states.

    How to structure your answer

    1. Create a ProtectedRoute wrapper component.
    2. Check authentication status from context or state.
    3. Conditionally render the protected component or redirect.
    4. Handle loading states during auth checks.
    5. Integrate with React Router's navigation.

    Key points to hit

    • Use a wrapper component that takes children and checks authentication before rendering.
    • Integrate with authentication context to get current user state.
    • Use Navigate component from React Router v6 or Redirect from v5 for unauthorized access.
    • Handle loading states while authentication is being verified.

    Common mistakes

    • Not handling loading states, causing flickers or redirects before auth status is determined.
    • Forgetting to preserve the intended destination URL for redirect after successful login.

    Sample answer

    I'd create a ProtectedRoute component that wraps the protected content and checks authentication status from context. If the user is authenticated, it renders the children. If not authenticated, it redirects to the login page using React Router's Navigate component.

    I'd also handle the loading state while checking authentication to prevent flickering, and save the current location so users get redirected back after login. The component would look like function ProtectedRoute({children}) and use useAuth hook to get the authentication state.

    How to level up

    • Save the intended destination in location state so users return to their original target after login.
    • Create different protection levels for different user roles using the same pattern.
    • Consider using React Router's loader function in v6 for data-dependent route protection.

    Follow-up questions to expect

    • How would you handle role-based access control with this pattern?
    • What happens if the authentication token expires while the user is on a protected route?
    • How would you implement route protection for an entire section of your app?
    Practice this question with AI feedback →
    How do you reset a component's state in React?
    medium

    What they're really asking

    This tests understanding of React's state management and component lifecycle. The interviewer wants to see if you know multiple approaches to state resetting and when to use each.

    How you'll be scored

    Weak

    Suggests only one approach like setting state back to initial values without understanding key prop or other patterns.

    Average

    Mentions using key prop to force remount or manually resetting state with setter functions.

    Strong

    Explains multiple approaches including key prop, useEffect cleanup, and state management patterns, with trade-offs for each.

    How to structure your answer

    1. Identify the different approaches available.
    2. Explain the key prop method for forcing remount.
    3. Show manual state reset using setter functions.
    4. Discuss useEffect for automatic reset triggers.
    5. Compare trade-offs of each approach.

    Key points to hit

    • Use key prop with changing value to force complete component remount and state reset.
    • Call setState with initial values manually when you need programmatic reset.
    • Use useEffect with dependencies to automatically reset state when certain values change.
    • Consider extracting state to parent component if frequent resets are needed.

    Common mistakes

    • Using key prop unnecessarily when simple state updates would work, causing performance overhead from full remounts.
    • Forgetting to reset all related state pieces, leaving component in partially reset state.

    Sample answer

    There are several ways to reset component state. The most straightforward is using the key prop with a changing value, which forces React to unmount and remount the component completely, resetting all state. For more control, I can manually call setState functions to return state to initial values.

    I can also use useEffect to automatically reset state when certain props change. For example, if I have a form that should reset when switching between users, I'd either change the key based on user ID or use useEffect with user ID in the dependency array.

    How to level up

    • Create a custom hook like useResetState that returns both state and a reset function for reusable reset logic.
    • Consider lifting state up to parent component if the reset logic becomes complex or needs coordination.
    • Use useImperativeHandle with forwardRef if parent components need to trigger resets on child components.

    Follow-up questions to expect

    • When would you choose key prop reset versus manual state reset?
    • How would you reset state across multiple related components?
    • What performance implications does using key prop for reset have?
    Practice this question with AI feedback →
    How do you focus an input element on page load?
    easy

    What they're really asking

    This tests basic understanding of useRef hook and DOM manipulation in React. The interviewer wants to see if you can handle imperative DOM operations correctly within React's declarative paradigm.

    How you'll be scored

    Weak

    Suggests using document.getElementById or other DOM query methods instead of React patterns.

    Average

    Uses useRef and useEffect to focus the input element correctly.

    Strong

    Uses useRef with useEffect, explains why this approach fits React's model, and mentions when focus might not work.

    How to structure your answer

    1. Create a ref using useRef hook.
    2. Attach ref to the input element.
    3. Use useEffect to focus after component mounts.
    4. Explain why this timing is necessary.
    5. Mention any edge cases or accessibility considerations.

    Key points to hit

    • Use useRef to create a reference to the input DOM element.
    • Attach the ref to the input using ref prop.
    • Call inputRef.current.focus() inside useEffect with empty dependency array.
    • Empty dependency array ensures focus happens only after initial mount.

    Common mistakes

    • Calling focus directly in the component body instead of useEffect, which runs before DOM is ready.
    • Not checking if inputRef.current exists before calling focus, which can cause errors.

    Sample answer

    I'd use the useRef hook to create a reference to the input element, then attach it using the ref prop. In useEffect with an empty dependency array, I'd call inputRef.current.focus() to focus the element after the component mounts. The useEffect is crucial because it runs after the DOM is rendered, ensuring the element exists.

    I'd also add a null check before calling focus to be safe, like if(inputRef.current) inputRef.current.focus().

    How to level up

    • Consider accessibility implications and ensure focus management doesn't interfere with screen readers.
    • Add conditional logic to only focus on certain conditions, like not focusing if user is already interacting with another element.
    • For complex focus management, create a custom hook that handles multiple focus scenarios.

    Follow-up questions to expect

    • How would you focus a dynamically rendered input that appears after user interaction?
    • What accessibility concerns should you consider when automatically focusing elements?
    • How would you focus the first invalid input in a form validation scenario?
    Practice this question with AI feedback →
    How do you create a switching component for displaying different pages?
    medium

    What they're really asking

    This tests understanding of conditional rendering patterns and component composition. The interviewer wants to see if you can create reusable UI patterns that handle multiple content states cleanly.

    How you'll be scored

    Weak

    Shows basic conditional rendering with if statements without considering reusability or clean patterns.

    Average

    Creates a component that takes currentPage prop and renders different components based on the value.

    Strong

    Implements a flexible switching component with clean patterns, considers performance implications, and handles edge cases like invalid page states.

    How to structure your answer

    1. Define the component interface with current page and page definitions.
    2. Create a mapping of page keys to components or content.
    3. Implement the switching logic with conditional rendering.
    4. Handle invalid or undefined page states.
    5. Consider performance optimizations for complex pages.

    Key points to hit

    • Accept currentPage prop and pages configuration object that maps keys to components.
    • Use object lookup or switch statement for clean conditional rendering.
    • Provide fallback content for invalid page keys to prevent crashes.
    • Consider lazy loading with React.lazy() if page components are large.

    Common mistakes

    • Creating a long chain of if-else statements instead of using cleaner object mapping or switch patterns.
    • Not handling the case where currentPage doesn't match any available pages, causing blank renders or errors.

    Sample answer

    I'd create a PageSwitch component that takes a currentPage prop and a pages object mapping page names to components. Inside, I'd use object lookup like pages[currentPage] to get the right component, then render it. I'd include a fallback for invalid pages, maybe a NotFound component.

    For example, the pages prop might be {home: HomePage, about: AboutPage, contact: ContactPage}, and I'd render pages[currentPage] || NotFoundPage. This pattern is clean, extensible, and avoids long conditional chains.

    How to level up

    • Use React.lazy() and Suspense for code splitting if the page components are large bundles.
    • Consider animation libraries like Framer Motion to add smooth transitions between page switches.
    • Add TypeScript with union types to make currentPage type-safe and prevent invalid page references.

    Follow-up questions to expect

    • How would you add animations when switching between pages?
    • What if you needed to pass different props to each page component?
    • How would you implement lazy loading for the page components to improve performance?
    Practice this question with AI feedback →
    How do you perform an automatic redirect after login?
    medium

    What they're really asking

    This tests understanding of React Router's programmatic navigation and handling asynchronous authentication flows. The interviewer wants to see if you can manage navigation side effects properly without causing infinite loops or race conditions.

    How you'll be scored

    Weak

    Suggests window.location or doesn't understand how to trigger navigation from useEffect properly.

    Average

    Uses useNavigate correctly but doesn't consider cleanup or edge cases like already being on the target route.

    Strong

    Demonstrates proper useEffect usage with navigate, handles loading states, and considers race conditions from slow login requests.

    How to structure your answer

    1. Explain using useNavigate hook from React Router.
    2. Show useEffect pattern triggered by successful auth state change.
    3. Demonstrate proper dependency array to avoid infinite loops.
    4. Address cleanup for component unmounting during async operations.

    Key points to hit

    • Use useNavigate hook instead of history.push for React Router v6.
    • Trigger navigation in useEffect when authentication state changes to success.
    • Include proper dependencies in useEffect to avoid stale closures.
    • Handle the case where login is still pending to prevent premature redirects.

    Common mistakes

    • Calling navigate directly in render function instead of useEffect causes infinite re-renders.
    • Not checking if component is still mounted before navigating after async login completion.

    Sample answer

    I'd use the useNavigate hook from React Router inside a useEffect that watches the authentication state. After a successful login API call updates my auth state, the useEffect triggers and calls navigate('/dashboard').

    I make sure to include the auth state in the dependency array so it only runs when login actually succeeds, not on every render. I also add cleanup to handle cases where the user navigates away before login completes.

    How to level up

    • Use navigate with replace: true option so users can't hit back button to return to login page.
    • Consider storing intended destination before login and redirecting there instead of hardcoded route.
    • Implement navigation guards to prevent authenticated users from accessing login page.

    Follow-up questions to expect

    • How would you handle redirecting to the originally requested protected route after login?
    • What happens if the user closes the browser tab while the login request is still pending?
    • How would you prevent authenticated users from seeing the login page?
    Practice this question with AI feedback →
    How do you implement route-level code splitting (lazy loading routes)?
    medium

    What they're really asking

    This tests knowledge of React.lazy, Suspense, and dynamic imports for performance optimization. The interviewer wants to see if you understand code splitting benefits and can implement it without breaking user experience.

    How you'll be scored

    Weak

    Doesn't know about React.lazy or confuses it with component-level lazy loading.

    Average

    Shows basic React.lazy and Suspense usage but doesn't explain the performance benefits or fallback strategy.

    Strong

    Demonstrates complete pattern with error boundaries, explains bundle size impact, and considers loading states for better UX.

    How to structure your answer

    1. Explain React.lazy for dynamic imports of route components.
    2. Show Suspense wrapper with fallback for loading state.
    3. Demonstrate integration with React Router route definitions.
    4. Discuss error boundaries for failed chunk loading.

    Key points to hit

    • Use React.lazy with dynamic import syntax to create lazy-loaded components.
    • Wrap route components in Suspense with meaningful loading fallback.
    • Lazy components must be default exports for React.lazy to work.
    • Add error boundaries to handle network failures when loading chunks.

    Common mistakes

    • Forgetting Suspense wrapper causes React error when lazy component loads.
    • Not handling failed chunk loading errors leaves users with broken navigation.

    Sample answer

    I use React.lazy to wrap dynamic imports of my route components, like const Dashboard = lazy(() => import('./Dashboard')). Then I wrap my Routes in a Suspense component with a loading spinner fallback. This splits each route into separate JavaScript bundles that only load when users navigate there.

    I also add an error boundary around the Suspense to handle cases where chunk loading fails due to network issues.

    How to level up

    • Preload critical routes on hover or user intent signals to reduce perceived loading time.
    • Use webpack bundle analyzer to verify your code splitting is actually reducing initial bundle size.
    • Implement retry logic in error boundaries for failed chunk loads instead of showing permanent error.

    Follow-up questions to expect

    • How would you preload a route component before the user navigates to it?
    • What happens if a lazy-loaded component fails to load due to network issues?
    • How do you decide which routes should be lazy-loaded versus included in the main bundle?
    Practice this question with AI feedback →
    Why does console.log(state) show the old value right after setState?
    medium

    What they're really asking

    This tests understanding of React's asynchronous state updates and closure behavior. The interviewer wants to see if you grasp why setState is batched and how JavaScript closures capture state values at render time.

    How you'll be scored

    Weak

    Thinks setState is synchronous or doesn't understand why the console.log shows stale values.

    Average

    Explains that setState is asynchronous but doesn't connect it to closure behavior or batching.

    Strong

    Explains both asynchronous nature and closure capture, mentions batching in React 18, and shows how to access updated values correctly.

    How to structure your answer

    1. Explain that setState is asynchronous and state updates are batched.
    2. Describe how console.log captures state value from current closure.
    3. Show correct ways to access updated state (useEffect, functional updates)
    4. Mention React 18's automatic batching improvements.

    Key points to hit

    • setState calls are asynchronous and batched for performance, so state doesn't update immediately.
    • console.log captures the state value from the current render's closure, not the future updated value.
    • Use useEffect with state in dependency array to log updated values after re-render.
    • Functional state updates receive current state as parameter for reliable updates.

    Common mistakes

    • Expecting setState to be synchronous leads to bugs when chaining state-dependent logic.
    • Using multiple setState calls based on current state value instead of functional updates causes lost updates.

    Sample answer

    setState is asynchronous and batches updates for performance, so the state variable doesn't change immediately. When console.log runs right after setState, it's still in the same render cycle and captures the old state value from that closure. The actual state update happens later, triggering a re-render.

    To log the updated value, I'd put console.log in a useEffect with state in the dependency array, so it runs after the re-render with the new value.

    How to level up

    • React 18's automatic batching groups all state updates in promises and timeouts, not just event handlers.
    • Use flushSync from react-dom to force synchronous updates when you absolutely need immediate DOM updates.
    • Functional updates like setState(prev => prev + 1) are safer for state that depends on previous values.

    Follow-up questions to expect

    • How would you update state based on the previous state value reliably?
    • What changed about batching behavior in React 18 compared to earlier versions?
    • When might you need to force a synchronous state update and how would you do it?
    Practice this question with AI feedback →
    Why do components re-render even when props "look the same"?
    medium

    What they're really asking

    This tests understanding of React's reconciliation algorithm and object reference equality. The interviewer wants to see if you know why React re-renders and how to optimize with proper memoization techniques.

    How you'll be scored

    Weak

    Doesn't understand that React uses reference equality or suggests always using JSON.stringify for comparisons.

    Average

    Knows React uses reference equality but doesn't explain solutions or when optimization is needed.

    Strong

    Explains reference vs deep equality, shows React.memo with custom comparison, and discusses when optimization is worthwhile.

    How to structure your answer

    1. Explain React's reference equality check for props comparison.
    2. Show how object and array props create new references on each render.
    3. Demonstrate React.memo with custom comparison function.
    4. Discuss performance trade-offs of optimization techniques.

    Key points to hit

    • React uses Object.is reference equality to compare props, not deep equality.
    • New objects and arrays created in parent render always have different references.
    • React.memo prevents re-renders but only with shallow comparison by default.
    • Custom comparison functions in React.memo can implement deep equality when needed.

    Common mistakes

    • Overusing React.memo without measuring performance impact can slow down your app.
    • Creating objects or arrays inline as props defeats memoization and causes unnecessary re-renders.

    Sample answer

    React uses reference equality to compare props between renders. Even if an object prop has the same properties and values, if it's a new object instance, React sees it as changed and re-renders the component. This happens when parent components create new objects inline or don't memoize complex props.

    I can fix this by wrapping the child in React.memo and either memoizing the prop creation in the parent with useMemo, or providing a custom comparison function to React.memo for deep equality checking.

    How to level up

    • Use React DevTools Profiler to measure if React.memo actually improves performance before applying it everywhere.
    • Consider moving object creation outside render or using refs for stable references when appropriate.
    • Implement custom comparison functions carefully as deep equality checks can be expensive for large objects.

    Follow-up questions to expect

    • How would you optimize a component that receives a large array prop that rarely changes?
    • When might React.memo actually hurt performance instead of helping?
    • What's the difference between React.memo and useMemo for preventing re-renders?
    Practice this question with AI feedback →
    What happens when you update state based on previous state incorrectly?
    medium

    What they're really asking

    This tests understanding of state update timing, batching, and race conditions. The interviewer wants to see if you know when to use functional updates and can identify bugs from stale closure values.

    How you'll be scored

    Weak

    Doesn't recognize the difference between direct state updates and functional updates or why it matters.

    Average

    Knows functional updates exist but can't explain when they're necessary or what problems they solve.

    Strong

    Explains closure capture issues, shows functional update syntax, and identifies scenarios where race conditions occur.

    How to structure your answer

    1. Explain how direct state updates capture stale values from closure.
    2. Show functional update syntax that receives current state.
    3. Demonstrate scenarios where multiple rapid updates cause lost updates.
    4. Discuss async operations and race conditions with state updates.

    Key points to hit

    • Direct state updates like setState(count + 1) capture the count value from the current closure.
    • Multiple rapid updates based on stale values cause lost updates since they all reference the same old value.
    • Functional updates like setState(prev => prev + 1) always receive the most current state.
    • Async operations that update state based on captured values create race conditions.

    Common mistakes

    • Using captured state values for updates instead of functional updates leads to lost state changes.
    • Not considering that multiple event handlers or async operations might update state simultaneously.

    Sample answer

    When you update state based on the current state value directly, like setState(count + 1), it captures the count from that render's closure. If multiple updates happen quickly, they all use the same old count value and later updates overwrite earlier ones.

    For example, two clicks might both see count as 0 and set it to 1, instead of incrementing to 2. Using functional updates like setState(prev => prev + 1) fixes this because each update receives the actual current state value, not the captured closure value.

    How to level up

    • useReducer is often clearer than functional setState when you have complex state update logic.
    • Be especially careful with state updates inside async functions where significant time passes between capture and update.
    • Consider using useCallback with proper dependencies when passing state updater functions to child components.

    Follow-up questions to expect

    • How would you handle updating state from inside a setTimeout or async function safely?
    • When might you choose useReducer over useState for managing state updates?
    • What happens if you have multiple useState calls that depend on each other in the same event handler?
    Practice this question with AI feedback →
    How do you handle error handling in a React application?
    medium

    What they're really asking

    This tests whether you understand React's error handling mechanisms and can implement graceful failure recovery. The interviewer wants to see if you can prevent crashes and maintain user experience when components fail.

    How you'll be scored

    Weak

    Only mentions try-catch blocks without understanding React-specific error handling patterns.

    Average

    Knows about error boundaries but gives a basic implementation without considering user experience.

    Strong

    Demonstrates error boundaries with fallback UI, logging, and recovery strategies plus async error handling patterns.

    How to structure your answer

    1. Explain error boundaries as React's primary error handling mechanism.
    2. Show a practical error boundary implementation with fallback UI.
    3. Discuss handling async errors and promise rejections.
    4. Cover logging and error reporting strategies.
    5. Mention development vs production error handling differences.

    Key points to hit

    • Error boundaries catch JavaScript errors in component trees and display fallback UI instead of crashing the app.
    • Use componentDidCatch or static getDerivedStateFromError to implement error boundaries in class components.
    • Handle async errors separately since error boundaries don't catch promise rejections or event handler errors.
    • Implement proper error logging and user feedback for production applications.

    Common mistakes

    • Trying to use try-catch around JSX render methods, which won't catch React component errors.
    • Not handling async errors from API calls or event handlers, which error boundaries don't catch.

    Sample answer

    I use error boundaries as the main React pattern for handling component errors. I create an ErrorBoundary component with componentDidCatch to catch render errors and display a user-friendly fallback UI instead of a blank page.

    For async errors like failed API calls, I handle those separately in my components using try-catch in useEffect or with error states. I also integrate error reporting services like Sentry to track errors in production and include context like user actions and component props.

    How to level up

    • Create multiple granular error boundaries instead of one app-level boundary to isolate failures to specific features.
    • Implement error recovery mechanisms like retry buttons or reset functionality in your error boundary fallback UI.
    • Use React DevTools Profiler to identify components that frequently throw errors and need better error handling.

    Follow-up questions to expect

    • How would you test error boundaries in your application?
    • What information would you include when logging errors to help with debugging?
    • How do you handle errors that occur in event handlers or async operations?
    Practice this question with AI feedback →
    How do you handle dynamic addition, removal, and sorting of list items?
    medium

    What they're really asking

    This tests your understanding of React's reconciliation algorithm and whether you can implement list operations without causing rendering bugs. The interviewer wants to see if you understand the importance of stable keys and efficient list updates.

    How you'll be scored

    Weak

    Uses array indices as keys or doesn't understand why keys matter for list performance and correctness.

    Average

    Knows to use stable keys but doesn't explain the reconciliation benefits or handle edge cases.

    Strong

    Uses stable unique keys, explains reconciliation optimization, and handles sorting/filtering without losing component state.

    How to structure your answer

    1. Emphasize using stable unique keys instead of array indices.
    2. Show how to add and remove items while maintaining keys.
    3. Demonstrate sorting with proper key preservation.
    4. Explain how React's reconciliation works with keys.
    5. Cover performance considerations for large lists.

    Key points to hit

    • Use stable unique identifiers as keys, never array indices, because indices change when items are reordered or filtered.
    • Generate unique IDs when adding new items, typically using UUID or timestamp-based approaches.
    • Preserve existing keys when sorting to maintain component state and avoid unnecessary re-renders.
    • Consider virtualization for lists with hundreds or thousands of items to maintain performance.

    Common mistakes

    • Using array indices as keys, which causes React to lose component state and focus when items are reordered.
    • Regenerating keys on every render, which forces React to recreate DOM elements unnecessarily.

    Sample answer

    I always use stable unique keys for list items, typically the item's ID from the database or a generated UUID. When adding items, I create a new ID and append to the state array. For removal, I filter by ID rather than index.

    For sorting, I create a new sorted array but preserve the original keys so React can efficiently move DOM elements instead of recreating them. This prevents issues like losing input focus or component state when the list changes.

    How to level up

    • Implement optimistic updates for better UX by immediately showing changes while API calls are pending, then rolling back on errors.
    • Use React.memo on list item components to prevent unnecessary re-renders when only the list order changes.
    • Consider using libraries like react-window or react-virtualized for large lists to render only visible items.

    Follow-up questions to expect

    • What happens if you use array indices as keys when reordering items?
    • How would you handle optimistic updates when adding items to a list?
    • What performance optimizations would you consider for a list with 10,000 items?
    Practice this question with AI feedback →
    How do you prevent navigation when a form has unsaved changes?
    medium

    What they're really asking

    This tests whether you understand browser navigation APIs and can implement user experience patterns that prevent data loss. The interviewer wants to see if you can handle both programmatic and browser-level navigation interruption.

    How you'll be scored

    Weak

    Doesn't know about beforeunload events or React Router's navigation blocking patterns.

    Average

    Knows about blocking navigation but only implements one method without considering all navigation scenarios.

    Strong

    Implements both browser-level blocking with beforeunload and React Router blocking with proper user confirmation flow.

    How to structure your answer

    1. Identify the scenarios where navigation should be blocked.
    2. Show React Router's navigation blocking with useBlocker or Prompt.
    3. Implement browser beforeunload event handling for page refresh and close.
    4. Create user-friendly confirmation dialogs.
    5. Handle cleanup when form is saved or cancelled.

    Key points to hit

    • Use React Router's useBlocker hook or Prompt component to intercept route changes within the app.
    • Add beforeunload event listeners to catch browser refresh, close, or external navigation attempts.
    • Track form dirty state to determine when blocking is necessary, typically by comparing current values to initial values.
    • Provide clear user messaging about unsaved changes and options to save, discard, or cancel navigation.

    Common mistakes

    • Only blocking React Router navigation but forgetting about browser refresh and close buttons.
    • Not cleaning up event listeners properly, which can cause memory leaks or block navigation after form is submitted.

    Sample answer

    I track whether the form has unsaved changes by comparing current form values to the initial state. When there are unsaved changes, I use React Router's useBlocker hook to intercept route changes and show a confirmation dialog. I also add a beforeunload event listener to catch browser refresh or close attempts.

    The key is cleaning up these blockers when the form is successfully saved or when the component unmounts to avoid blocking legitimate navigation.

    How to level up

    • Implement auto-save functionality as a fallback so users don't lose work even if they navigate away accidentally.
    • Use a debounced effect to mark forms as dirty only after the user stops typing to avoid blocking navigation on every keystroke.
    • Consider persisting form data to localStorage as a backup recovery mechanism for critical forms.

    Follow-up questions to expect

    • How would you implement auto-save to reduce the need for navigation blocking?
    • What would you do if the user forces navigation despite unsaved changes?
    • How do you handle navigation blocking in a multi-step form wizard?
    Practice this question with AI feedback →

    Routing Questions (12)

    What is React Router and why is it used?
    easy

    What they're really asking

    This tests basic understanding of client-side routing concepts and whether you know why single-page applications need routing libraries. The interviewer wants to see if you understand the fundamentals before diving into more complex routing scenarios.

    How you'll be scored

    Weak

    Gives vague answers about navigation without understanding SPA routing challenges or React Router specifics.

    Average

    Knows React Router enables navigation in SPAs but doesn't explain the underlying browser API usage.

    Strong

    Explains how React Router uses browser History API to sync UI with URL and enables bookmarkable, shareable routes in SPAs.

    How to structure your answer

    1. Define React Router as a client-side routing library for React applications.
    2. Explain the problem it solves in single-page applications.
    3. Describe how it uses browser History API to manage navigation.
    4. Show basic usage with routes and navigation components.
    5. Mention benefits like bookmarkable URLs and browser back/forward support.

    Key points to hit

    • React Router enables navigation between different views in single-page applications without full page reloads.
    • It uses the browser's History API to update the URL and manage navigation state while keeping the app interactive.
    • Provides declarative routing with components like Route, Link, and Navigate instead of manual URL manipulation.
    • Enables features like bookmarkable URLs, browser back/forward buttons, and shareable links in SPAs.

    Common mistakes

    • Confusing client-side routing with server-side routing and not understanding that React Router runs in the browser.
    • Not understanding that React Router prevents full page reloads and maintains application state during navigation.

    Sample answer

    React Router is a library that enables client-side routing in React single-page applications. Without it, SPAs would show the same URL for all views and users couldn't bookmark or share specific pages. React Router uses the browser's History API to update the URL when users navigate, while React handles rendering the appropriate components.

    This gives us the benefits of traditional multi-page websites, like working back buttons and bookmarkable URLs, while maintaining the fast, interactive experience of a single-page app.

    How to level up

    • Understand that React Router is declarative, meaning you describe what should render for each route rather than imperatively managing navigation state.
    • Learn the difference between browser routing for web apps and memory routing for testing or non-browser environments.
    • Consider React Router as part of your app's state management since route parameters and search params are application state.

    Follow-up questions to expect

    • What's the difference between Link and anchor tags in React Router?
    • How do you handle route parameters and query strings?
    • What happens if a user directly visits a URL in a React Router application?
    Practice this question with AI feedback →
    What is the difference between BrowserRouter and HashRouter?
    medium

    What they're really asking

    This tests understanding of different browser routing strategies and their trade-offs. The interviewer wants to see if you can choose the appropriate router based on deployment constraints and user experience requirements.

    How you'll be scored

    Weak

    Doesn't understand the URL format differences or deployment implications of each router type.

    Average

    Knows BrowserRouter uses clean URLs and HashRouter uses hash fragments but doesn't explain when to use each.

    Strong

    Explains URL differences, server configuration requirements, and can recommend the right choice based on deployment scenario.

    How to structure your answer

    1. Compare URL formats between the two router types.
    2. Explain server configuration requirements for BrowserRouter.
    3. Describe HashRouter's compatibility advantages and limitations.
    4. Discuss SEO and user experience implications.
    5. Provide guidance on when to choose each option.

    Key points to hit

    • BrowserRouter creates clean URLs like '/products/123' while HashRouter uses hash fragments like '/#/products/123'
    • BrowserRouter requires server configuration to handle client-side routes, serving index.html for all routes.
    • HashRouter works without server configuration because hash fragments aren't sent to the server.
    • BrowserRouter provides better SEO and user experience with clean URLs, while HashRouter is easier to deploy on static hosts.

    Common mistakes

    • Using BrowserRouter on static hosting without configuring fallback routes, which causes 404 errors on direct URL access.
    • Choosing HashRouter by default without considering the SEO and UX implications of hash-based URLs.

    Sample answer

    BrowserRouter uses the HTML5 History API to create clean URLs like '/dashboard/settings', but requires server configuration to serve your index.html file for all routes since these URLs don't exist as actual files. HashRouter uses URL hash fragments like '/#/dashboard/settings' and works without server setup because browsers don't send the hash portion to the server.

    I prefer BrowserRouter for better user experience and SEO, but choose HashRouter when deploying to static hosts like GitHub Pages that can't configure custom routing rules.

    How to level up

    • Configure your build process to generate appropriate server redirects or rewrite rules when using BrowserRouter.
    • Consider that HashRouter URLs aren't ideal for social media sharing since some platforms treat hash fragments inconsistently.
    • Use basename prop with either router when deploying to subdirectories to handle relative path resolution correctly.

    Follow-up questions to expect

    • How would you configure a server to support BrowserRouter?
    • What are the SEO implications of using HashRouter?
    • Can you switch between BrowserRouter and HashRouter in an existing application?
    Practice this question with AI feedback →
    How do nested routes work? Why do we need Outlet?
    medium

    What they're really asking

    This tests understanding of React Router's component composition model and how parent-child route rendering works. The interviewer wants to see if you understand the Outlet pattern for nested UI structures.

    How you'll be scored

    Weak

    Confuses nested routes with conditional rendering or can't explain what Outlet does.

    Average

    Correctly explains that Outlet renders child routes but lacks detail about the composition pattern.

    Strong

    Explains the parent-child rendering relationship, shows practical Outlet usage, and understands when nested routes are appropriate.

    How to structure your answer

    1. Define nested routes as parent-child route relationships.
    2. Explain Outlet as the render location for child components.
    3. Show a concrete routing structure example.
    4. Demonstrate the URL-to-component mapping.
    5. Mention common use cases like dashboards or layouts.

    Key points to hit

    • Outlet acts as a placeholder where child route components render within their parent.
    • Parent route components stay mounted while child routes change, enabling persistent layouts.
    • URL segments map to the route hierarchy, like /dashboard/settings rendering Dashboard with Settings inside.
    • Without Outlet in the parent component, child routes won't render anywhere.

    Common mistakes

    • Forgetting to include Outlet in parent components causes child routes to not display.
    • Confusing nested routes with nested components or thinking you need manual conditional rendering.

    Sample answer

    Nested routes let you build hierarchical UI structures where parent components stay mounted while child components change. The Outlet component is like a slot where React Router renders the active child route.

    For example, if I have a Dashboard route with nested Settings and Profile routes, the Dashboard component needs an Outlet where those children will appear. When someone visits /dashboard/settings, React Router renders Dashboard with the Settings component inside the Outlet. This is perfect for layouts with sidebars or headers that should persist across different sections.

    How to level up

    • Use index routes for default child content when only the parent path is visited.
    • Consider relative paths in nested route navigation to make components more portable.
    • Leverage nested routes for code splitting at the route level rather than just component level.

    Follow-up questions to expect

    • How would you implement breadcrumbs with nested routes?
    • What happens if you forget to include Outlet in a parent route component?
    • How do you pass data from parent routes to child routes?
    Practice this question with AI feedback →
    What are the major changes between React Router v5 and v6?
    medium

    What they're really asking

    This tests knowledge of React Router evolution and migration experience. The interviewer wants to see if you can handle version upgrades and understand modern routing patterns.

    How you'll be scored

    Weak

    Can't identify key differences or confuses v6 features with other versions.

    Average

    Names some changes like Switch to Routes but lacks migration context.

    Strong

    Identifies major API changes, explains the philosophy shift toward declarative routing, and shows migration awareness.

    How to structure your answer

    1. Highlight the Switch to Routes component change.
    2. Explain the element prop replacing component and render props.
    3. Cover the relative routing and path matching improvements.
    4. Mention useNavigate replacing useHistory.
    5. Address bundle size and performance improvements.

    Key points to hit

    • Routes replaced Switch with simpler syntax and better path matching.
    • The element prop takes JSX directly instead of component references, making prop passing cleaner.
    • useNavigate replaced useHistory with a more intuitive API for programmatic navigation.
    • Relative routing became the default, making nested routes easier to work with.

    Common mistakes

    • Trying to use v5 patterns like useHistory in v6 will cause runtime errors.
    • Not updating Route syntax from component prop to element prop breaks routing.

    Sample answer

    The biggest change is Routes replacing Switch, with much cleaner syntax for route definitions. Instead of passing component props, you now use element with JSX directly, like element={<Dashboard />}. Navigation changed from useHistory to useNavigate, which feels more intuitive for programmatic routing.

    Path matching got smarter too, with relative routing as the default, so nested routes don't need full path definitions. I migrated a project last year and the bundle size actually decreased because v6 removed a lot of legacy API surface area.

    How to level up

    • Use the compat package during migration to gradually update large codebases.
    • Take advantage of v6's improved TypeScript support for better route typing.
    • Leverage the new data loading patterns if you're using React Router 6.4+ with loaders.

    Follow-up questions to expect

    • How would you approach migrating a large application from v5 to v6?
    • What are the benefits of the element prop over the component prop?
    • Have you used React Router 6.4's data loading features?
    Practice this question with AI feedback →
    What is the difference between useNavigate and the Navigate component?
    medium

    What they're really asking

    This tests understanding of imperative versus declarative navigation patterns in React Router. The interviewer wants to see if you know when to use each approach.

    How you'll be scored

    Weak

    Doesn't understand the distinction or thinks they're interchangeable in all cases.

    Average

    Knows useNavigate is for programmatic navigation and Navigate is for declarative but lacks nuance.

    Strong

    Explains the imperative vs declarative difference, shows appropriate use cases, and understands rendering implications.

    How to structure your answer

    1. Define useNavigate as the hook for imperative navigation.
    2. Explain Navigate component for declarative, render-based navigation.
    3. Show concrete examples of when to use each.
    4. Highlight the timing differences in when navigation occurs.
    5. Mention common patterns for each approach.

    Key points to hit

    • useNavigate returns a function you call in response to events or effects, giving you control over when navigation happens.
    • Navigate component triggers navigation during render, typically used for redirects or conditional routing.
    • Use useNavigate for user actions like form submissions or button clicks.
    • Use Navigate component for automatic redirects based on application state or authentication.

    Common mistakes

    • Using Navigate component in event handlers instead of useNavigate causes navigation during render cycles.
    • Calling navigate functions during render instead of in effects or event handlers violates React's rendering rules.

    Sample answer

    useNavigate gives you a function to call when you need programmatic navigation, like after a form submission or button click. Navigate is a component that navigates during render, perfect for conditional redirects. I use useNavigate when handling user actions, like navigate('/dashboard') after login success.

    I use Navigate component for things like redirecting unauthenticated users, where the navigation decision is based on render-time state. The key difference is timing: useNavigate responds to events, while Navigate happens automatically during component rendering.

    How to level up

    • Use Navigate with replace prop for authentication redirects to prevent back button issues.
    • Consider useNavigate with state for passing data between routes without URL parameters.
    • Combine Navigate with conditional rendering for complex redirect logic based on multiple state conditions.

    Follow-up questions to expect

    • How would you implement a protected route using these navigation methods?
    • What's the difference between navigate() and navigate() with replace option?
    • When might you use Navigate component inside a useEffect?
    Practice this question with AI feedback →
    How do you navigate programmatically in React Router?
    medium

    What they're really asking

    This tests knowledge of imperative navigation APIs and patterns. The interviewer wants to see if you can handle complex navigation scenarios beyond basic link clicking.

    How you'll be scored

    Weak

    Only knows about Link components or suggests non-React Router solutions.

    Average

    Mentions useNavigate but doesn't show practical usage patterns.

    Strong

    Demonstrates useNavigate with real scenarios, explains navigation options, and shows awareness of navigation timing.

    How to structure your answer

    1. Introduce useNavigate as the primary programmatic navigation tool.
    2. Show basic navigation with string paths.
    3. Demonstrate navigation with options like replace and state.
    4. Cover relative navigation and delta navigation.
    5. Mention common use cases and timing considerations.

    Key points to hit

    • useNavigate hook returns a navigate function for programmatic routing in event handlers and effects.
    • Pass replace: true option to replace current history entry instead of adding a new one.
    • Use state option to pass data to the destination route without URL parameters.
    • Navigate with numbers like navigate(-1) for browser-like back/forward behavior.

    Common mistakes

    • Calling navigate during render instead of in event handlers or effects violates React rendering rules.
    • Forgetting the replace option for logout redirects allows users to navigate back to protected pages.

    Sample answer

    I use the useNavigate hook for all programmatic navigation. After getting the navigate function, I can call it in event handlers or effects. For example, after form submission I might do navigate('/dashboard', { replace: true }) to prevent back navigation to the form.

    I can also pass state like navigate('/profile', { state: { from: 'settings' } }) to send data without URL parameters. For browser-like behavior, navigate(-1) goes back one page. The key is calling navigate in response to events or in effects, never during the render cycle itself.

    How to level up

    • Use navigate with state for passing complex objects between routes that shouldn't be in the URL.
    • Consider navigate with replace for form submissions to prevent duplicate submissions on back navigation.
    • Combine useNavigate with useEffect for redirects based on authentication or data loading states.

    Follow-up questions to expect

    • How would you navigate after an async operation like an API call?
    • What's the difference between navigate('/path') and navigate('/path', { replace: true })?
    • How do you access the state passed through navigate in the destination component?
    Practice this question with AI feedback →
    How do you handle 404 Not Found routes?
    medium

    What they're really asking

    This tests understanding of catch-all routing and error handling patterns. The interviewer wants to see if you can implement robust routing that handles unexpected URLs gracefully.

    How you'll be scored

    Weak

    Doesn't know about catch-all routes or suggests handling 404s outside the router.

    Average

    Mentions catch-all routes with asterisk but lacks implementation details.

    Strong

    Shows proper 404 route setup, understands route ordering importance, and considers user experience for unknown paths.

    How to structure your answer

    1. Explain catch-all routes using the asterisk path pattern.
    2. Show proper placement at the end of route definitions.
    3. Demonstrate a 404 component implementation.
    4. Cover nested route 404 handling.
    5. Mention user experience considerations for unknown paths.

    Key points to hit

    • Use path='*' as the last route to catch any unmatched URLs.
    • The catch-all route must come after all specific routes since React Router matches in order.
    • Create a user-friendly 404 component that helps users find what they're looking for.
    • Consider different 404 handling for nested routes versus top-level routes.

    Common mistakes

    • Placing the catch-all route too early in the route list causes it to match before specific routes.
    • Forgetting 404 routes in nested route sections leaves users with blank pages for invalid nested paths.

    Sample answer

    I handle 404s with a catch-all route using path='*' that must be placed last in my route definitions. This catches any URL that doesn't match earlier routes. I create a helpful 404 component that shows a clear message and navigation options, like a search bar or links to popular sections.

    For nested routes, I include catch-all routes within those sections too, so users don't see blank pages when they hit invalid nested paths. The key is making sure the asterisk route comes after all specific routes, otherwise it will intercept legitimate paths.

    How to level up

    • Include analytics tracking in your 404 component to identify broken links or user confusion patterns.
    • Consider using the location object in 404 components to show what URL was attempted.
    • Implement different 404 handling strategies for authenticated versus public sections of your app.

    Follow-up questions to expect

    • How would you implement different 404 pages for different sections of your app?
    • What information would you include in a 404 page to help users?
    • How do you handle 404s in server-side rendering with React Router?
    Practice this question with AI feedback →
    How do you get query parameters in React Router?
    medium

    What they're really asking

    This tests understanding of React Router's URL parameter handling and knowledge of the useSearchParams hook. The interviewer wants to see if you can extract query parameters correctly and understand the difference between search params and route params.

    How you'll be scored

    Weak

    Mentions window.location or manual URL parsing instead of React Router hooks.

    Average

    Uses useSearchParams correctly but doesn't explain the API or mention URLSearchParams.

    Strong

    Demonstrates useSearchParams with proper syntax, explains the setter function, and mentions type handling considerations.

    How to structure your answer

    1. Import and use the useSearchParams hook.
    2. Show how to get specific parameters.
    3. Demonstrate updating query parameters.
    4. Mention type conversion considerations.

    Key points to hit

    • Use useSearchParams hook, not manual URL parsing or window.location.
    • The hook returns both current params and a setter function for updates.
    • Query parameters are always strings and need type conversion for numbers or booleans.
    • Updates to search params trigger re-renders and navigation.

    Common mistakes

    • Using window.location.search instead of React Router hooks breaks navigation context.
    • Forgetting that all query parameters are strings and need parsing for other types.

    Sample answer

    I use the useSearchParams hook from React Router. It returns an array with the current search params and a setter function, similar to useState. To get a specific parameter, I call searchParams.get('paramName'). For example, const [searchParams, setSearchParams] = useSearchParams(); const userId = searchParams.get('userId').

    To update parameters, I can call setSearchParams with a new URLSearchParams object or plain object. One important thing is that all query parameters come back as strings, so I need to convert them if I expect numbers or booleans.

    How to level up

    • Create custom hooks to handle common query parameter patterns with type conversion.
    • Use searchParams.getAll() for parameters that can have multiple values.
    • Consider using a library like query-string for complex parameter serialization.

    Follow-up questions to expect

    • How would you handle type-safe query parameters in TypeScript?
    • What's the difference between useSearchParams and useParams?
    • How do you handle query parameters that should persist across route changes?
    Practice this question with AI feedback →
    How do you pass data during navigation without exposing it in the URL?
    medium

    What they're really asking

    This tests knowledge of React Router's state passing mechanisms and understanding of when to avoid URL exposure for sensitive or transient data. The interviewer wants to see if you know the location state API and can choose appropriate data passing strategies.

    How you'll be scored

    Weak

    Suggests localStorage or global state without mentioning React Router's built-in state mechanism.

    Average

    Mentions location state but doesn't show proper syntax or explain when to use it.

    Strong

    Demonstrates navigate with state option, shows how to access it with useLocation, and explains appropriate use cases.

    How to structure your answer

    1. Use the state option in navigate or Link components.
    2. Access the state using useLocation hook.
    3. Explain when this approach is appropriate.
    4. Mention fallback handling for direct URL access.

    Key points to hit

    • Use the state option when calling navigate() or in Link components to pass data.
    • Access passed state through useLocation().state in the destination component.
    • Location state is perfect for temporary data like form submissions or modal contexts.
    • Always handle cases where state might be null if users navigate directly to the URL.

    Common mistakes

    • Relying on location state for data that needs to persist through page refreshes.
    • Not handling null state cases when users access the route directly.

    Sample answer

    I use React Router's location state feature by passing a state object when navigating. When calling navigate, I include a second parameter with the state, like navigate('/profile', { state: { user: userData } }).

    In the destination component, I use the useLocation hook to access this data with const location = useLocation(); const userData = location.state?.user. This is great for passing form data after submission or context for modals. I always check if the state exists because users might navigate directly to the URL where state would be null.

    How to level up

    • Combine location state with a fallback data fetching strategy for robust user experience.
    • Use TypeScript interfaces to define the shape of your location state.
    • Consider the replace option in navigate to avoid cluttering browser history.

    Follow-up questions to expect

    • What happens to location state when the user refreshes the page?
    • When would you choose location state over query parameters?
    • How do you handle location state in nested routes?
    Practice this question with AI feedback →
    What is the difference between client-side routing and server-side routing?
    medium

    What they're really asking

    This tests understanding of fundamental web architecture concepts and how React Router fits into the broader web ecosystem. The interviewer wants to see if you understand the trade-offs between routing approaches and can articulate the benefits of SPAs.

    How you'll be scored

    Weak

    Confuses the concepts or gives vague explanations about 'faster' vs 'slower' without specifics.

    Average

    Correctly identifies that client-side routing doesn't make server requests but doesn't explain the implementation details.

    Strong

    Explains the technical differences, mentions history API, discusses trade-offs like SEO and initial load time, and shows understanding of hybrid approaches.

    How to structure your answer

    1. Define server-side routing and its request-response cycle.
    2. Explain client-side routing and JavaScript manipulation.
    3. Compare performance and user experience differences.
    4. Discuss trade-offs and use cases for each.

    Key points to hit

    • Server-side routing requires full page requests and server responses for each navigation.
    • Client-side routing uses JavaScript and the History API to update the URL without server requests.
    • Client-side routing provides faster navigation but requires JavaScript and has SEO considerations.
    • Modern approaches often combine both with server-side rendering and client-side hydration.

    Common mistakes

    • Thinking client-side routing is always better without considering SEO and initial load implications.
    • Not understanding that client-side routing still needs server configuration for direct URL access.

    Sample answer

    Server-side routing means each navigation triggers a full HTTP request to the server, which returns a complete HTML page. The browser loads this new page from scratch. Client-side routing uses JavaScript to manipulate the browser's URL and render different components without server requests.

    React Router uses the History API to update the URL bar while JavaScript handles the page content. Client-side routing feels much faster after the initial load because there's no network delay, but it requires JavaScript to work and can be trickier for SEO.

    Server-side routing works without JavaScript and is better for SEO out of the box, but every click means a full page reload.

    How to level up

    • Learn about hybrid approaches like Next.js that combine server-side rendering with client-side routing.
    • Understand how to configure your server to handle client-side routes for direct URL access.
    • Consider the performance implications of bundle size with client-side routing.

    Follow-up questions to expect

    • How do you handle SEO with client-side routing?
    • What server configuration is needed to support client-side routing?
    • How do you decide between client-side and server-side routing for a project?
    Practice this question with AI feedback →
    How do loaders and actions work in React Router (data routers)?
    hard

    What they're really asking

    This tests knowledge of React Router v6.4+ data router features and understanding of modern data fetching patterns. The interviewer wants to see if you're familiar with the latest React Router APIs and can explain the loader/action pattern that competes with traditional useEffect data fetching.

    How you'll be scored

    Weak

    Hasn't heard of loaders and actions or confuses them with other React concepts.

    Average

    Knows loaders fetch data and actions handle mutations but can't explain the integration with routing.

    Strong

    Explains the loader/action lifecycle, shows proper syntax with createBrowserRouter, and discusses benefits over useEffect patterns.

    How to structure your answer

    1. Define loaders as route-level data fetching functions.
    2. Explain actions as route-level mutation handlers.
    3. Show how they integrate with createBrowserRouter.
    4. Discuss advantages over component-level data fetching.

    Key points to hit

    • Loaders run before route components render and provide data through useLoaderData.
    • Actions handle form submissions and mutations, triggered by Form components or fetchers.
    • Both are defined in the route configuration when using createBrowserRouter.
    • This pattern moves data fetching out of components and closer to the routing layer.

    Common mistakes

    • Trying to use loaders and actions with older router setups like BrowserRouter instead of data routers.
    • Not understanding that loaders and actions run on navigation, not on component mount.

    Sample answer

    Loaders and actions are part of React Router's data router pattern introduced in v6.4. Loaders are functions that fetch data before a route renders, defined in the route configuration when creating the router with createBrowserRouter. The component accesses this data using useLoaderData hook.

    Actions handle form submissions and mutations, triggered by React Router's Form component or programmatically with fetchers. For example, I'd define a loader function that fetches user data, associate it with a route, and the UserProfile component gets the data immediately without useEffect or loading states. Actions work similarly but for POST requests and mutations.

    How to level up

    • Use defer() in loaders to handle slow data fetching with Suspense boundaries.
    • Leverage the revalidation system to keep data fresh after actions.
    • Combine loaders with error boundaries for robust error handling at the route level.

    Follow-up questions to expect

    • How do you handle loading states with loaders compared to useEffect?
    • What's the difference between Form and regular form elements in React Router?
    • How do loaders work with nested routes?
    Practice this question with AI feedback →
    How do you persist scroll position or scroll-to-top on route change?
    medium

    What they're really asking

    This tests understanding of user experience considerations in single-page applications and knowledge of scroll behavior APIs. The interviewer wants to see if you think about UX details and can implement scroll management that feels natural to users.

    How you'll be scored

    Weak

    Suggests manual scroll management without understanding React Router's built-in options or browser behavior.

    Average

    Mentions scrollTo(0,0) or React Router's scroll behavior but doesn't explain when to use each approach.

    Strong

    Explains both scroll restoration and scroll-to-top strategies, shows implementation with useEffect and useLocation, and discusses UX trade-offs.

    How to structure your answer

    1. Explain the default browser behavior and SPA challenges.
    2. Show scroll-to-top implementation with useEffect and useLocation.
    3. Discuss scroll restoration for back/forward navigation.
    4. Mention React Router's built-in scroll restoration options.

    Key points to hit

    • SPAs don't automatically scroll to top on route changes like traditional websites.
    • Use useEffect with useLocation to scroll to top on route changes.
    • Consider preserving scroll position for back/forward navigation using sessionStorage.
    • React Router v6 has experimental scroll restoration features in development.

    Common mistakes

    • Scrolling to top on every navigation without considering user expectations for back button behavior.
    • Not accounting for async content that might change page height after scroll positioning.

    Sample answer

    By default, React Router doesn't scroll to the top on route changes, which can confuse users who expect traditional website behavior. I handle this with a custom hook that uses useLocation and useEffect. When the pathname changes, I call window.scrollTo(0, 0) to scroll to the top.

    However, for back and forward navigation, users typically expect to return to their previous scroll position, so I store scroll positions in sessionStorage keyed by location and restore them appropriately. I wrap this logic in a useScrollManagement hook that I can apply globally or per-route as needed.

    How to level up

    • Implement smooth scrolling with scroll behavior options for better UX.
    • Use Intersection Observer to restore scroll position only after content has loaded.
    • Consider different scroll behaviors for different types of navigation (link clicks vs back button)

    Follow-up questions to expect

    • How do you handle scroll position with lazy-loaded content?
    • What about scroll management in modal routes?
    • How would you implement scroll-to-anchor behavior with React Router?
    Practice this question with AI feedback →

    Ready to put this into practice?

    Practice this with MockIF →

    Still applying for jobs? Let Auto Apply do it

    Advanced / Architecture Questions (19)

    What are Higher-Order Components (HOC)? What can you do with them?
    medium

    What they're really asking

    This tests understanding of React component composition patterns and code reuse strategies. The interviewer wants to see if you can architect reusable logic and understand the trade-offs between HOCs and modern hooks.

    How you'll be scored

    Weak

    Cannot explain what HOCs are or confuses them with regular components.

    Average

    Explains HOCs as functions that take components and return enhanced components with a basic example.

    Strong

    Explains HOCs clearly, provides practical example, discusses when to use them versus hooks, and mentions common pitfalls like prop collision.

    How to structure your answer

    1. Define HOCs as functions that take a component and return an enhanced component.
    2. Show a concrete example like withAuth or withLoading.
    3. Explain when you'd use HOCs versus custom hooks.
    4. Mention key considerations like prop passing and naming.

    Key points to hit

    • HOCs are functions that take a component and return a new component with additional props or behavior.
    • They're useful for cross-cutting concerns like authentication, logging, or data fetching.
    • Modern React favors custom hooks over HOCs for most use cases.
    • Watch out for prop collision and ensure you pass through unrelated props.

    Common mistakes

    • Not passing through props with spread operator, causing props to be lost.
    • Creating HOCs inside render methods, which breaks React's reconciliation.

    Sample answer

    Higher-Order Components are functions that take a component as input and return a new component with enhanced functionality. For example, I've used a withAuth HOC that checks if a user is logged in and either renders the wrapped component or redirects to login. The pattern looks like `const EnhancedComponent = withAuth(MyComponent)`.

    While HOCs are still valid, I prefer custom hooks nowadays because they're more explicit about what data they provide and don't create additional component layers. The main gotcha with HOCs is making sure you spread through all the original props so nothing gets lost.

    How to level up

    • Use React.forwardRef inside HOCs to properly pass refs through to wrapped components.
    • Consider displayName manipulation for better debugging experience in React DevTools.
    • Evaluate whether a custom hook would be cleaner than an HOC for the specific use case.

    Follow-up questions to expect

    • How would you convert this HOC pattern to use a custom hook instead?
    • What happens if two HOCs try to pass props with the same name?
    • How do you handle ref forwarding in HOCs?
    Practice this question with AI feedback →
    What are render props in React?
    medium

    What they're really asking

    This tests understanding of component composition and data sharing patterns. The interviewer wants to see if you can implement flexible, reusable components that can share logic without prop drilling.

    How you'll be scored

    Weak

    Cannot explain render props or confuses them with regular props.

    Average

    Explains render props as passing functions as props to share logic between components.

    Strong

    Explains render props clearly with example, discusses when to use them, and understands the relationship to modern patterns like custom hooks.

    How to structure your answer

    1. Define render props as passing a function as a prop that returns JSX.
    2. Show a practical example like a data fetching component.
    3. Explain the flexibility this provides for different UI implementations.
    4. Compare to modern alternatives like custom hooks.

    Key points to hit

    • Render props pass functions as props that return JSX, allowing logic sharing without dictating UI.
    • The pattern provides maximum flexibility since the parent controls what gets rendered.
    • Common use cases include data fetching, mouse tracking, or form state management.
    • Custom hooks often provide cleaner solutions for the same problems in modern React.

    Common mistakes

    • Creating arrow functions directly in JSX props, causing unnecessary re-renders.
    • Not considering that render prop components can become deeply nested and hard to read.

    Sample answer

    Render props is a pattern where you pass a function as a prop that returns JSX. The receiving component calls this function and passes data to it.

    For instance, I built a DataFetcher component that handled loading states and error handling, then called `props.render({data, loading, error})` to let the parent decide how to display the results. This gives you maximum flexibility since different screens could use the same data fetching logic but render completely different UIs.

    Today, I'd probably solve the same problem with a custom hook like useApiData, which is cleaner and doesn't create nested component structures.

    How to level up

    • Use render props when you need to share stateful logic but the UI varies significantly between use cases.
    • Consider performance implications since render prop functions often recreate on each render.
    • Modern React Context API with render props can create powerful compound component patterns.

    Follow-up questions to expect

    • How would you optimize a render prop component to prevent unnecessary re-renders?
    • When would you choose render props over a custom hook?
    • Can you show how to implement a mouse tracking component using render props?
    Practice this question with AI feedback →
    Explain the composition pattern in React.
    medium

    What they're really asking

    This tests understanding of React's philosophy of building UIs through component composition rather than inheritance. The interviewer wants to see if you can design flexible, maintainable component hierarchies.

    How you'll be scored

    Weak

    Cannot explain composition or thinks it's just about nesting components.

    Average

    Explains composition as combining components but lacks concrete examples of advanced patterns.

    Strong

    Demonstrates composition with practical examples like compound components, explains benefits over inheritance, and shows understanding of children prop usage.

    How to structure your answer

    1. Define composition as building complex UIs by combining simpler components.
    2. Show examples like compound components or children prop usage.
    3. Contrast with inheritance and explain why React favors composition.
    4. Demonstrate practical patterns like slots or compound components.

    Key points to hit

    • Composition builds complex components by combining simpler ones rather than using inheritance.
    • The children prop is the most basic composition tool, allowing components to wrap arbitrary content.
    • Compound components work together as a cohesive unit while maintaining individual responsibilities.
    • Composition enables better code reuse and testing compared to inheritance hierarchies.

    Common mistakes

    • Over-engineering composition patterns when simple prop passing would suffice.
    • Not using React.Children utilities when you need to manipulate or validate children.

    Sample answer

    Composition in React means building complex UIs by combining simpler components rather than using inheritance. The most basic example is using the children prop to create wrapper components like a Card that can contain any content.

    More advanced patterns include compound components, where components like Tabs, TabList, and TabPanel work together but can be arranged flexibly. I've used this pattern for building a Modal system where ModalHeader, ModalBody, and ModalFooter can be composed differently across the app.

    This approach makes components more testable and reusable than trying to handle every variation through props.

    How to level up

    • Use React.cloneElement to pass props down to children when building compound components.
    • Consider using React Context for compound components that need to share state.
    • Implement slot-based composition using named children props for more controlled layouts.

    Follow-up questions to expect

    • How would you implement a compound component that shares state between its parts?
    • What are the trade-offs between composition and passing many props?
    • Can you show how to validate that compound components are used correctly together?
    Practice this question with AI feedback →
    Explain the presentational vs container component pattern.
    medium

    What they're really asking

    This tests understanding of separation of concerns and component architecture. The interviewer wants to see if you can design maintainable component hierarchies that separate business logic from presentation.

    How you'll be scored

    Weak

    Cannot distinguish between the two types or thinks it's just about having smart and dumb components.

    Average

    Explains the basic difference but lacks concrete examples or understanding of when to apply the pattern.

    Strong

    Clearly explains the separation, provides practical examples, understands when the pattern helps versus when it adds unnecessary complexity.

    How to structure your answer

    1. Define presentational components as focused on how things look.
    2. Define container components as focused on how things work.
    3. Show concrete examples of each type.
    4. Discuss when this separation helps versus when it adds complexity.

    Key points to hit

    • Presentational components focus on UI rendering and receive data through props.
    • Container components handle business logic, state management, and data fetching.
    • This separation makes components more testable and reusable.
    • Modern hooks have reduced the need for this strict separation since logic can be extracted to custom hooks.

    Common mistakes

    • Creating unnecessary container components when the logic could live in the presentational component.
    • Making presentational components too generic, reducing their usability and clarity.

    Sample answer

    Presentational components focus purely on rendering UI and receive all their data through props, like a UserCard that displays a user's info. Container components handle the business logic and data fetching, like a UserProfileContainer that fetches user data and passes it to UserCard.

    I used this pattern heavily when building a product catalog where ProductList was presentational and ProductListContainer handled API calls and filtering logic. However, with modern hooks, I often skip the strict separation since I can extract logic into custom hooks while keeping everything in one component file, which is often simpler to maintain.

    How to level up

    • Use this pattern when you need the same UI with different data sources or business logic.
    • Consider whether a custom hook might be cleaner than a separate container component.
    • Container components are great places to implement error boundaries and loading states.

    Follow-up questions to expect

    • How has the introduction of hooks changed how you think about this pattern?
    • When would you still prefer separate container components over custom hooks?
    • How do you test presentational versus container components differently?
    Practice this question with AI feedback →
    What are error boundaries in React? In which scenarios do they not catch errors?
    medium

    What they're really asking

    This tests understanding of React's error handling mechanisms and when they apply. The interviewer wants to see if you can implement proper error boundaries and understand their limitations.

    How you'll be scored

    Weak

    Cannot explain what error boundaries are or how they work.

    Average

    Explains error boundaries as components that catch errors but lacks understanding of their limitations.

    Strong

    Explains error boundaries clearly, knows exactly which errors they don't catch, and understands proper implementation patterns.

    How to structure your answer

    1. Define error boundaries as components that catch JavaScript errors in component trees.
    2. Explain the lifecycle methods involved.
    3. List specific scenarios where they don't work.
    4. Show practical implementation example.

    Key points to hit

    • Error boundaries catch errors during rendering, lifecycle methods, and constructors of child components.
    • They don't catch errors in event handlers, async code, or errors thrown in the error boundary itself.
    • Implement using componentDidCatch or the newer getDerivedStateFromError lifecycle methods.
    • Place error boundaries strategically to isolate failures without breaking the entire app.

    Common mistakes

    • Assuming error boundaries catch all possible errors including event handlers and async operations.
    • Not implementing both error logging and fallback UI properly.

    Sample answer

    Error boundaries are React components that catch JavaScript errors anywhere in their child component tree and display fallback UI instead of crashing the whole app. You implement them using componentDidCatch or getDerivedStateFromError lifecycle methods.

    However, they have important limitations - they don't catch errors in event handlers, setTimeout callbacks, async operations, or errors that happen during server-side rendering. I typically wrap major sections of the app with error boundaries to isolate failures. For event handler errors, you need regular try-catch blocks since error boundaries won't help there.

    How to level up

    • Use error boundaries at multiple levels - both globally and around risky components like third-party widgets.
    • Implement proper error reporting in componentDidCatch to track production issues.
    • Consider using libraries like react-error-boundary for more convenient error boundary patterns.

    Follow-up questions to expect

    • How would you handle errors in async operations since error boundaries don't catch them?
    • Where would you place error boundaries in a typical React application?
    • How do you test that your error boundaries work correctly?
    Practice this question with AI feedback →
    What is forwardRef() in React and what is it used for?
    medium

    What they're really asking

    This tests understanding of ref forwarding through component layers and why it's necessary for component libraries. The interviewer wants to see if you know that refs don't pass through components like props by default.

    How you'll be scored

    Weak

    Cannot explain why refs don't work on custom components or what forwardRef does.

    Average

    Knows forwardRef lets parent components access a child's DOM node by forwarding the ref.

    Strong

    Explains why refs can't be accessed as props by default, shows the forwardRef pattern, discusses use cases in component libraries, and mentions React 19 changes that simplify ref handling.

    How to structure your answer

    1. Explain the problem: refs don't pass through custom components as regular props.
    2. Show how forwardRef wraps a component to accept and forward a ref.
    3. Give practical use cases in component libraries and HOCs.
    4. Mention combining with useImperativeHandle for controlled APIs.
    5. Note upcoming React 19 changes.

    Key points to hit

    • By default, the ref prop on a custom component does not get forwarded to a child DOM element. It's handled specially by React, not passed as a prop.
    • forwardRef wraps a component so it receives the ref as a second argument alongside props, which you then attach to the appropriate DOM element.
    • Essential for component libraries where consumers need to access the underlying DOM node for focusing, measuring, or scrolling.
    • Commonly combined with useImperativeHandle to expose a controlled set of methods instead of the raw DOM node.

    Common mistakes

    • Trying to access ref as a regular prop without forwardRef, which silently fails because React strips ref from the props object.
    • Not understanding that forwardRef is required for higher-order components and render prop patterns to preserve ref access through wrapper layers.

    Sample answer

    forwardRef solves a specific problem. When you put a ref on a custom component like <MyInput ref={inputRef} />, the ref doesn't automatically reach the underlying input element. React handles ref specially and doesn't include it in the props object. forwardRef wraps your component so it receives ref as a second argument after props.

    Inside the component, you attach that ref to the DOM element you want the parent to access. This is essential for component libraries. If I build a custom TextInput component, users expect to be able to call ref.current.focus(). Without forwardRef, they can't. It's also important for higher-order components that wrap other components.

    Without forwarding, the ref points to the wrapper, not the inner component. React 19 simplifies this by making ref a regular prop, so forwardRef will eventually become unnecessary.

    How to level up

    • Mention that React 19 treats ref as a regular prop, making forwardRef unnecessary for new code targeting React 19+.
    • Discuss how forwardRef affects the component's displayName in DevTools and how to set it for better debugging with forwardRef((props, ref) => ...) and displayName assignment.
    • Point out that forwardRef works with both callback refs and object refs created by useRef or createRef.

    Follow-up questions to expect

    • How does React 19 change the way refs work with components?
    • How would you forward a ref through a higher-order component?
    • Can you use forwardRef with useImperativeHandle? When would you combine them?
    Practice this question with AI feedback →
    What are React Portals and what are they used for?
    medium

    What they're really asking

    This tests understanding of rendering outside the React root DOM hierarchy while maintaining React's component tree behavior. The interviewer wants to see if you know why portals exist and the specific problems they solve.

    How you'll be scored

    Weak

    Cannot explain what portals do or confuses them with regular rendering.

    Average

    Knows portals render children into a different DOM node outside the React root.

    Strong

    Explains the DOM placement versus React tree distinction, shows that events still bubble through the React tree, and gives specific use cases like modals and tooltips with CSS context problems.

    How to structure your answer

    1. Define portals and the createPortal API.
    2. Explain the problem they solve: CSS overflow and z-index context issues.
    3. Show that portals maintain React's event bubbling through the component tree.
    4. List common use cases.
    5. Mention accessibility considerations.

    Key points to hit

    • createPortal renders a child into a DOM node that exists outside the parent component's DOM hierarchy.
    • Portals solve CSS stacking context problems where overflow: hidden or z-index on ancestors would clip or hide overlays.
    • Even though the DOM node is elsewhere, events still bubble up through the React component tree, not the DOM tree.
    • Common use cases include modals, tooltips, dropdown menus, and notification toasts that need to render above everything else.

    Common mistakes

    • Not knowing that React event bubbling works through the React tree even for portaled elements, which can cause unexpected event handling.
    • Using portals when CSS z-index alone would solve the problem, adding unnecessary complexity.

    Sample answer

    React Portals let you render children into a DOM node that lives outside the React root element. You use createPortal(children, domNode) and the JSX renders into that target node instead of the parent component's DOM position. The main problem they solve is CSS.

    If a modal component renders inside a container with overflow: hidden or a specific z-index stacking context, the modal gets clipped or hidden behind other elements. Portals let you render the modal into document.body or a dedicated modal root, breaking out of any ancestor CSS constraints.

    The interesting thing is that even though the portal renders in a different DOM location, React's event bubbling still follows the component tree. A click inside a portal still bubbles to its React parent, not its DOM parent. This means context providers, error boundaries, and event handlers on ancestor React components still work as expected.

    How to level up

    • Mention that portals are also useful for rendering into iframes or shadow DOM boundaries while keeping the React tree connected.
    • Discuss how focus management and keyboard navigation need special attention with portals to maintain accessibility, especially for modal dialogs.
    • Point out that portals are the recommended approach for tooltips in component libraries because they avoid overflow clipping from any ancestor in the DOM tree.

    Follow-up questions to expect

    • How does event bubbling work differently in the DOM tree versus React tree for portals?
    • How would you manage focus trapping for a modal rendered through a portal?
    • Can you use a portal to render into a DOM node that React doesn't control?
    Practice this question with AI feedback →
    What is React Suspense and what does it enable?
    hard

    What they're really asking

    This tests understanding of React's approach to async operations in the component tree. The interviewer wants to see if you grasp how Suspense changes the loading state paradigm and its connection to concurrent features.

    How you'll be scored

    Weak

    Only knows Suspense works with React.lazy or cannot explain the fallback mechanism.

    Average

    Explains the Suspense boundary pattern with fallback UI for lazy-loaded components.

    Strong

    Covers code splitting with React.lazy, data fetching integration, streaming SSR, nested Suspense boundaries, and how Suspense works with useTransition to avoid showing fallbacks for fast operations.

    How to structure your answer

    1. Define Suspense as a declarative way to handle async loading states.
    2. Explain the boundary and fallback pattern.
    3. Cover the code splitting use case with React.lazy.
    4. Discuss data fetching integration in React 18+.
    5. Connect to concurrent features like useTransition.

    Key points to hit

    • Suspense lets you declaratively show a fallback UI while waiting for async content to load, replacing imperative loading state management.
    • A Suspense boundary catches promises thrown by children and shows the fallback prop until they resolve.
    • The original use case was code splitting with React.lazy, which loads component code on demand.
    • React 18 extended Suspense to work with data fetching through compatible libraries and streaming SSR.

    Common mistakes

    • Thinking Suspense replaces all loading state management, when it currently requires specific integration from data fetching libraries to work with data.
    • Not understanding that Suspense boundaries can be nested, with each level handling different loading states for different parts of the UI.

    Sample answer

    Suspense is React's declarative approach to handling loading states. You wrap a component tree in a Suspense boundary with a fallback prop, and when any child is not ready to render, React shows the fallback instead. The first use case was code splitting.

    React.lazy wraps a dynamic import, and Suspense shows a spinner while the component code downloads. React 18 expanded Suspense significantly. It now works with data fetching through compatible libraries like Relay and TanStack Query. When a component suspends during data loading, the Suspense boundary shows the fallback.

    You can nest Suspense boundaries for granular loading states. The header loads independently of the sidebar. The powerful part is how Suspense works with useTransition. A transition can keep the old UI visible instead of showing the fallback, so fast navigations feel instant while slow ones get a loading indicator.

    How to level up

    • Mention that Suspense enables streaming SSR in React 18, where the server can send HTML for ready parts while suspended parts stream in later.
    • Discuss how SuspenseList (experimental) coordinates the reveal order of multiple Suspense boundaries to prevent layout shifts.
    • Point out that the use hook in React 19 is the built-in way to trigger Suspense from a promise, replacing the throw-promise pattern that libraries previously had to implement manually.

    Follow-up questions to expect

    • How does Suspense work with streaming server-side rendering?
    • Can you nest Suspense boundaries? What happens with multiple loading states?
    • How does useTransition interact with Suspense to avoid showing fallbacks?
    Practice this question with AI feedback →
    Explain server-side rendering (SSR) in React and its benefits.
    hard

    What they're really asking

    This tests understanding of rendering strategies and their performance and SEO implications. The interviewer wants to see if you can explain the SSR lifecycle, its benefits over client-side rendering, and the trade-offs involved.

    How you'll be scored

    Weak

    Vaguely says SSR is rendering on the server without explaining the full lifecycle or why it matters.

    Average

    Explains that SSR sends pre-rendered HTML for faster initial load and better SEO.

    Strong

    Describes the full SSR lifecycle including server render, HTML streaming, hydration, explains benefits for FCP/LCP and SEO, discusses trade-offs like server load and TTFB, and mentions streaming SSR in React 18.

    How to structure your answer

    1. Define SSR and contrast with client-side rendering.
    2. Walk through the SSR lifecycle: render on server, send HTML, hydrate on client.
    3. Explain performance benefits: faster FCP, better LCP.
    4. Explain SEO benefits for search engine crawlers.
    5. Discuss trade-offs and React 18 streaming SSR improvements.

    Key points to hit

    • SSR renders React components to HTML on the server and sends that HTML to the browser, so users see content before JavaScript loads and executes.
    • After the HTML arrives, React hydrates it on the client by attaching event listeners and making it interactive.
    • SSR improves First Contentful Paint and Largest Contentful Paint because the browser can display content without waiting for JavaScript bundle download and execution.
    • Search engine crawlers receive complete HTML content, improving SEO for applications that would otherwise show empty div elements with client-side rendering.

    Common mistakes

    • Thinking SSR makes the page interactive faster, when it actually makes content visible faster but interactivity still depends on JavaScript hydration.
    • Not understanding that SSR increases server load and complexity, and that not every application needs it. SPAs with authenticated content may not benefit from SSR.

    Sample answer

    Server-side rendering means rendering React components to HTML on the server before sending them to the browser. With pure client-side rendering, the browser gets an empty HTML shell, downloads the JavaScript bundle, and then renders the UI. The user sees nothing until all that completes.

    With SSR, the server runs renderToString or the streaming renderToPipeableStream, generates the full HTML, and sends it. The user sees the content immediately. Then React hydrates the page on the client, attaching event listeners to make it interactive.

    The benefits are faster First Contentful Paint since HTML renders without JavaScript, better SEO since crawlers see full content, and improved social media link previews. The trade-offs are increased server load since every request runs React, longer Time to First Byte since the server needs to render before responding, and hydration complexity.

    React 18's streaming SSR with Suspense is a big improvement because it sends HTML in chunks as components become ready instead of waiting for the entire page.

    How to level up

    • Mention that React 18 streaming SSR with renderToPipeableStream sends HTML progressively and can stream in Suspense fallback replacements as data loads.
    • Discuss selective hydration where React 18 can start hydrating parts of the page that the user interacts with first, improving Time to Interactive.
    • Point out that frameworks like Next.js abstract SSR complexity with getServerSideProps and React Server Components, which is the recommended approach over manual SSR setup.

    Follow-up questions to expect

    • What is the difference between SSR and SSG? When would you choose each?
    • What are hydration errors and how do you debug them?
    • How does streaming SSR in React 18 improve the user experience?
    Practice this question with AI feedback →
    What is static site generation and how does it differ from SSR?
    hard

    What they're really asking

    This tests understanding of rendering strategies and the ability to choose the right one based on content characteristics. The interviewer wants to see if you understand when pre-building pages is better than rendering on every request.

    How you'll be scored

    Weak

    Confuses SSG with SSR or cannot explain when to use each.

    Average

    Correctly explains SSG generates HTML at build time while SSR generates on each request.

    Strong

    Compares the full lifecycle and performance characteristics of each, discusses ISR as a hybrid approach, and gives clear decision criteria based on content update frequency and personalization needs.

    How to structure your answer

    1. Define SSG and when the HTML is generated.
    2. Contrast with SSR where HTML is generated per request.
    3. Compare performance, scalability, and freshness trade-offs.
    4. Introduce ISR as a middle ground.
    5. Provide decision criteria for choosing between them.

    Key points to hit

    • SSG generates HTML at build time and serves the same pre-built pages to every user. No server computation happens on each request.
    • SSR generates HTML on every request, allowing personalized or frequently changing content at the cost of server processing time.
    • SSG is faster and more scalable because pages are served from a CDN with no server processing, but content is only as fresh as the last build.
    • Incremental Static Regeneration (ISR) in Next.js combines both: serve static pages but regenerate them in the background after a specified revalidation period.

    Common mistakes

    • Recommending SSG for highly dynamic or personalized content like dashboards or user profiles that change frequently.
    • Not considering ISR as a middle ground for content that updates periodically but doesn't need real-time freshness.

    Sample answer

    Static Site Generation builds all the HTML pages at build time, before any user visits the site. Every user gets the same pre-built HTML served directly from a CDN. No server-side computation happens per request. SSR generates HTML on every request.

    The server renders the page fresh for each user, which means the content can be personalized or reflect the latest data. SSG wins on performance and scalability. CDN-served static files are as fast as it gets, and you can handle any traffic volume without server scaling.

    But the content is only as fresh as your last build. SSR is slower per request because of server rendering, but content is always current. The decision comes down to content characteristics. Blog posts, documentation, marketing pages are perfect for SSG. User dashboards, search results, and personalized feeds need SSR.

    ISR in Next.js gives you a middle path. Pages are statically generated but revalidated in the background every N seconds, combining static performance with reasonable freshness.

    How to level up

    • Mention that Next.js App Router with React Server Components is moving toward a model where you can mix static and dynamic rendering per component, not just per page.
    • Discuss on-demand ISR where you can trigger regeneration programmatically through a webhook when content changes, instead of relying on time-based revalidation.
    • Point out that SSG with client-side data fetching (Static Shell approach) gives you static page shells with dynamic content loaded after hydration, combining both strategies.

    Follow-up questions to expect

    • What is ISR and how does it combine SSG and SSR benefits?
    • How do you decide which pages should be SSG versus SSR in a Next.js application?
    • What are the caching implications of SSR versus SSG for CDN deployment?
    Practice this question with AI feedback →
    What is React hydration?
    hard

    What they're really asking

    This tests understanding of client-side rendering hydration and server-side rendering integration. The interviewer wants to see if you grasp the complexity of SSR/SSG and can debug hydration mismatches.

    How you'll be scored

    Weak

    Confuses hydration with initial rendering or gives vague explanation about 'making static HTML interactive'.

    Average

    Correctly explains hydration as React attaching to server-rendered HTML but lacks detail about the process or common issues.

    Strong

    Explains the hydration process, mentions reconciliation with server HTML, and identifies hydration mismatches as a key debugging challenge.

    How to structure your answer

    1. Define hydration in the context of SSR.
    2. Explain the technical process of React taking over server-rendered HTML.
    3. Describe what happens during hydration reconciliation.
    4. Mention common hydration mismatch issues and debugging.

    Key points to hit

    • Hydration occurs when React attaches event listeners and state to server-rendered HTML rather than rendering from scratch.
    • React compares its virtual DOM with the existing server HTML during reconciliation.
    • Hydration mismatches happen when client and server render differently, causing React to re-render the entire tree.
    • Use ReactDOM.hydrateRoot() (React 18) or ReactDOM.hydrate() (legacy) instead of render() for SSR applications.

    Common mistakes

    • Confusing hydration with regular client-side rendering.
    • Not understanding that hydration mismatches force full re-renders, negating SSR performance benefits.

    Sample answer

    Hydration is the process where React takes over server-rendered HTML and makes it interactive by attaching event listeners and initializing component state. When you use SSR with Next.js or similar frameworks, the server sends fully rendered HTML to the browser, then React 'hydrates' this HTML by comparing it with its own virtual DOM.

    If there's a mismatch between what the server rendered and what React expects to render, you'll get hydration errors and React will re-render the entire component tree. I've debugged these before when using different data between server and client renders, like timestamps or random values.

    How to level up

    • Use suppressHydrationWarning sparingly and only for unavoidable client-server differences like timestamps.
    • Consider using React 18's Selective Hydration to hydrate components incrementally based on user interaction.
    • Debug hydration issues by ensuring server and client render with identical props and state.

    Follow-up questions to expect

    • How would you debug a hydration mismatch error?
    • What's the difference between SSR, SSG, and CSR in terms of hydration?
    • How does React 18's concurrent hydration improve the user experience?
    Practice this question with AI feedback →
    What is Strict Mode in React? Why does it render twice?
    medium

    What they're really asking

    This tests knowledge of React's development tools and understanding of why React intentionally double-renders in development. The interviewer wants to see if you understand React's philosophy of pure components.

    How you'll be scored

    Weak

    Doesn't know Strict Mode exists or thinks the double rendering is a bug that needs fixing.

    Average

    Knows Strict Mode helps catch bugs and mentions double rendering but doesn't explain the reasoning behind it.

    Strong

    Explains that Strict Mode intentionally double-renders to surface side effects and helps identify impure components that rely on single execution.

    How to structure your answer

    1. Define React Strict Mode and its purpose as a development tool.
    2. Explain the intentional double rendering behavior.
    3. Connect double rendering to detecting side effects in components.
    4. Mention other Strict Mode features like deprecated API warnings.

    Key points to hit

    • Strict Mode only affects development builds and helps identify unsafe patterns without impacting production.
    • Double rendering helps catch side effects in component bodies, useEffect, and state updaters that assume single execution.
    • Components should be pure functions that produce the same output given the same props and state.
    • Strict Mode also warns about deprecated lifecycle methods and unsafe string ref usage.

    Common mistakes

    • Thinking double rendering is a bug and trying to 'fix' it by removing Strict Mode.
    • Not understanding that side effects should be in useEffect, not in the component body.

    Sample answer

    React Strict Mode is a development tool that helps catch potential problems by intentionally double-rendering components. The double rendering isn't a bug, it's designed to surface side effects that make your components impure.

    For example, if you're modifying a global variable or making an API call directly in your component body, you'll see it happen twice in development, which signals you need to move that logic into useEffect. Strict Mode also warns about deprecated APIs and unsafe patterns.

    I always keep it enabled because it catches bugs early that would be harder to debug in production.

    How to level up

    • Use Strict Mode to identify components that aren't truly pure by checking if double execution breaks functionality.
    • Pay attention to Strict Mode warnings about deprecated features as they often indicate future breaking changes.
    • Consider that Strict Mode in React 18 also helps identify components that aren't compatible with concurrent rendering.

    Follow-up questions to expect

    • Can you give an example of a side effect that Strict Mode would help you catch?
    • How does Strict Mode relate to React's concurrent features?
    • What would you do if removing Strict Mode 'fixes' a bug in your component?
    Practice this question with AI feedback →
    What are some common React anti-patterns?
    hard

    What they're really asking

    This tests practical React experience and code review skills. The interviewer wants to see if you can identify patterns that cause bugs, performance issues, or maintainability problems in real codebases.

    How you'll be scored

    Weak

    Lists generic programming anti-patterns or mentions patterns that aren't actually problematic in modern React.

    Average

    Identifies 2-3 real React anti-patterns but doesn't explain why they're problematic or how to fix them.

    Strong

    Explains specific anti-patterns with concrete examples, explains the problems they cause, and suggests better alternatives.

    How to structure your answer

    1. Identify key categories of React anti-patterns.
    2. Provide specific examples with code or scenarios.
    3. Explain why each pattern causes problems.
    4. Suggest better alternatives for each anti-pattern.

    Key points to hit

    • Using array indices as keys causes bugs when list items are reordered, added, or removed.
    • Mutating state directly breaks React's change detection and can cause components not to re-render.
    • Overusing useEffect for state synchronization creates unnecessary re-renders when derived state would be better.
    • Prop drilling through many components makes code brittle when component structure changes.

    Common mistakes

    • Confusing anti-patterns with legitimate patterns that have trade-offs.
    • Focusing on style preferences rather than patterns that cause actual bugs or performance problems.

    Sample answer

    One major anti-pattern is using array indices as keys, which breaks React's reconciliation when you reorder or filter lists. I've seen bugs where form inputs keep old values after sorting because React thinks it's the same component. Another is directly mutating state objects or arrays, which prevents React from detecting changes.

    Also, overusing useEffect to synchronize state that could be derived during render creates unnecessary cycles. Instead of useEffect to calculate a filtered list from props, just calculate it directly in the component body. Finally, excessive prop drilling makes components tightly coupled when Context or state management would be cleaner.

    How to level up

    • Use ESLint rules like react-hooks/exhaustive-deps and react/jsx-key to catch common anti-patterns automatically.
    • Consider performance implications: some patterns like creating objects in render can cause unnecessary re-renders of child components.
    • Document component APIs clearly to prevent consumers from falling into anti-patterns when using your components.

    Follow-up questions to expect

    • How would you refactor a component that's prop drilling through 5 levels?
    • Can you show me an example of when mutating state directly would cause a bug?
    • What tools or practices help prevent these anti-patterns in a team environment?
    Practice this question with AI feedback →
    What are the different ways to style a React component?
    easy

    What they're really asking

    This tests basic React knowledge and familiarity with the styling ecosystem. The interviewer wants to see if you understand the trade-offs between different styling approaches and can choose appropriately.

    How you'll be scored

    Weak

    Only knows inline styles or basic CSS without understanding trade-offs or mentioning popular React styling solutions.

    Average

    Lists 3-4 styling methods including CSS modules or styled-components but doesn't explain when to use each.

    Strong

    Covers multiple approaches, explains trade-offs like specificity and performance, and demonstrates knowledge of modern styling tools.

    How to structure your answer

    1. List the main styling approaches available in React.
    2. Explain trade-offs for each approach.
    3. Mention when you'd choose each method.
    4. Note any performance or maintenance considerations.

    Key points to hit

    • Inline styles work well for dynamic values but lack pseudo-selectors and media queries.
    • CSS modules provide scoped styles and prevent naming conflicts in larger applications.
    • CSS-in-JS libraries like styled-components offer component co-location but add runtime overhead.
    • Utility frameworks like Tailwind provide consistency and faster development but require learning the class system.

    Common mistakes

    • Recommending inline styles for everything without considering limitations.
    • Not understanding that CSS-in-JS solutions have performance trade-offs compared to static CSS.

    Sample answer

    You can style React components several ways, each with trade-offs. Inline styles are great for dynamic values like animation properties, but they can't handle pseudo-selectors or media queries. CSS modules solve the global namespace problem by automatically scoping class names, which works well for traditional CSS workflows.

    CSS-in-JS libraries like styled-components let you co-locate styles with components and use props for styling logic, but they add runtime overhead. Utility frameworks like Tailwind provide design consistency and fast development once you learn the classes. I typically choose based on team familiarity and whether I need dynamic styling logic.

    How to level up

    • Consider build-time CSS-in-JS solutions like linaria for the benefits of CSS-in-JS without runtime performance costs.
    • Use CSS custom properties (CSS variables) with React for dynamic theming without inline styles.
    • Measure bundle size impact when choosing CSS-in-JS libraries, as some add significant overhead.

    Follow-up questions to expect

    • How would you implement a theme system in React?
    • What are the performance implications of different styling approaches?
    • How do you handle responsive design with CSS-in-JS?
    Practice this question with AI feedback →
    What is the role of PropTypes in React? What are alternatives for type checking?
    easy

    What they're really asking

    This tests knowledge of React's evolution from PropTypes to modern type checking. The interviewer wants to see if you understand type safety in JavaScript and can recommend current best practices.

    How you'll be scored

    Weak

    Doesn't know what PropTypes are or thinks they're still the primary way to add type checking to React.

    Average

    Knows PropTypes provided runtime type checking but doesn't mention TypeScript or other modern alternatives.

    Strong

    Explains PropTypes' historical role, mentions they're development-only, and recommends TypeScript as the modern standard for type safety.

    How to structure your answer

    1. Explain PropTypes' original purpose in React applications.
    2. Describe how PropTypes work and their limitations.
    3. Compare with modern alternatives like TypeScript.
    4. Recommend current best practices for type checking.

    Key points to hit

    • PropTypes provided runtime type checking for component props and helped catch bugs during development.
    • PropTypes are stripped out in production builds, so they don't provide runtime safety in deployed applications.
    • TypeScript offers compile-time type checking with better IDE support and catches more errors earlier.
    • Flow was Facebook's alternative but has largely been superseded by TypeScript in the React ecosystem.

    Common mistakes

    • Thinking PropTypes work in production builds or provide runtime type safety.
    • Not understanding that TypeScript provides much more comprehensive type checking than PropTypes.

    Sample answer

    PropTypes were React's original solution for type checking component props during development. They provided runtime warnings when components received props of the wrong type, which helped catch bugs early. However, PropTypes are development-only and get stripped from production builds, so they don't provide runtime safety.

    Today, TypeScript is the standard for type checking React applications because it catches errors at compile time, provides excellent IDE support with autocomplete and refactoring, and works across your entire application, not just component props. Most new React projects I work on use TypeScript from the start for much better type safety.

    How to level up

    • Use TypeScript's React types like React.FC, React.ComponentProps, and React.RefObject for better component type definitions.
    • Consider using libraries like zod or io-ts for runtime type validation when you need to validate external data.
    • Enable strict TypeScript settings to catch more potential bugs and enforce better coding practices.

    Follow-up questions to expect

    • How do you handle type checking for external API data in TypeScript?
    • What are the advantages of TypeScript over PropTypes beyond just prop validation?
    • How would you migrate a PropTypes codebase to TypeScript?
    Practice this question with AI feedback →
    What are the benefits of using TypeScript with React?
    medium

    What they're really asking

    This tests understanding of type safety in React development and practical experience combining React with TypeScript. The interviewer wants to see if you can articulate the development experience benefits and understand the trade-offs.

    How you'll be scored

    Weak

    Only mentions basic type safety without understanding React-specific benefits or development workflow improvements.

    Average

    Correctly explains type safety for props and state with basic examples but misses advanced TypeScript React patterns.

    Strong

    Demonstrates deep understanding of TypeScript's impact on React development including IDE support, refactoring safety, and team collaboration benefits.

    How to structure your answer

    1. Start with immediate development benefits (IDE support, autocomplete)
    2. Explain React-specific type safety (props, state, event handlers)
    3. Discuss team collaboration and refactoring advantages.
    4. Mention the learning curve trade-off.
    5. Give a concrete example of TypeScript preventing a React bug.

    Key points to hit

    • TypeScript provides compile-time error checking for props, preventing runtime crashes when component APIs change.
    • IDE autocomplete and IntelliSense dramatically improve developer experience when working with component props and callbacks.
    • Interface definitions serve as documentation, making it easier for teams to understand component contracts.
    • Refactoring becomes safer because TypeScript catches breaking changes across component boundaries.

    Common mistakes

    • Claiming TypeScript eliminates all bugs rather than focusing on the specific classes of errors it prevents.
    • Not acknowledging the initial setup overhead and learning curve for teams new to TypeScript.

    Sample answer

    The biggest benefit I've seen with TypeScript and React is the immediate feedback during development. When I'm using a component, TypeScript shows me exactly what props are required and their types, so I catch mistakes before running the code.

    For example, if I change a prop from accepting a string to an enum, TypeScript will highlight every place that needs updating. The IDE autocomplete also makes me much more productive when working with complex prop interfaces.

    There's definitely a learning curve for teams new to TypeScript, but the investment pays off quickly in fewer runtime errors and easier refactoring.

    How to level up

    • Learn React-specific TypeScript patterns like generic components and discriminated unions for prop variants.
    • Use strict TypeScript settings to catch more potential issues, especially strictNullChecks for handling optional props.
    • Leverage utility types like Partial and Pick to create flexible component APIs without duplicating interface definitions.

    Follow-up questions to expect

    • How would you type a component that accepts either a string or a React element as a prop?
    • What's your approach to typing event handlers in React with TypeScript?
    • How do you handle TypeScript with third-party React libraries that don't have types?
    Practice this question with AI feedback →
    Describe the component lifecycle methods in class components.
    medium

    What they're really asking

    This tests knowledge of class component lifecycle methods and understanding of when each method is called. The interviewer wants to see if you understand the mounting, updating, and unmounting flow.

    How you'll be scored

    Weak

    Can only name a few lifecycle methods without understanding when they're called or their purpose.

    Average

    Knows the main lifecycle methods and their basic purposes but lacks understanding of the complete flow or practical usage.

    Strong

    Demonstrates comprehensive understanding of all lifecycle phases with practical examples of when to use each method.

    How to structure your answer

    1. Organize by the three main phases: mounting, updating, unmounting.
    2. Explain the purpose and timing of each key method.
    3. Give practical examples of what you'd do in each method.
    4. Mention deprecated methods and why they're problematic.
    5. Connect to modern hooks equivalents.

    Key points to hit

    • componentDidMount is where you make API calls and set up subscriptions because the component is fully rendered.
    • componentDidUpdate receives previous props and state, making it perfect for responding to specific changes.
    • componentWillUnmount is critical for cleanup to prevent memory leaks from timers, subscriptions, or event listeners.
    • shouldComponentUpdate was used for performance optimization but React.memo and PureComponent are better alternatives.

    Common mistakes

    • Making API calls in componentWillMount or constructor instead of componentDidMount, which can cause issues with server-side rendering.
    • Forgetting to clean up subscriptions in componentWillUnmount, leading to memory leaks and stale updates.

    Sample answer

    Class components have three main lifecycle phases. During mounting, the constructor runs first for initial state, then render, then componentDidMount where I'd make API calls or set up subscriptions. During updates, render runs again, then componentDidUpdate where I can compare previous props to current props and make additional API calls if needed.

    Finally, componentWillUnmount runs before the component is destroyed, and that's where I clean up any timers or subscriptions. There are other methods like shouldComponentUpdate for performance optimization, but most of these patterns are now handled better with hooks like useEffect.

    How to level up

    • Use componentDidUpdate with proper condition checking to avoid infinite loops when making API calls based on prop changes.
    • Understand that componentWillMount, componentWillUpdate, and componentWillReceiveProps are deprecated because they interfere with Concurrent Mode.
    • Learn how error boundaries use componentDidCatch and getDerivedStateFromError for error handling that hooks can't replicate.

    Follow-up questions to expect

    • How would you convert componentDidMount and componentWillUnmount to hooks?
    • What's the difference between componentWillReceiveProps and componentDidUpdate?
    • When would you still choose class components over functional components with hooks?
    Practice this question with AI feedback →
    What are the different phases of the React component lifecycle?
    medium

    What they're really asking

    This tests understanding of React's component lifecycle as a conceptual model, not just memorizing method names. The interviewer wants to see if you understand the timing and purpose of each phase.

    How you'll be scored

    Weak

    Vague understanding of lifecycle phases without connecting them to practical React behavior or re-rendering.

    Average

    Can identify the three main phases and their general purpose but lacks depth in understanding their implications.

    Strong

    Demonstrates clear understanding of how lifecycle phases relate to React's rendering model and practical development decisions.

    How to structure your answer

    1. Define the three core phases: mounting, updating, unmounting.
    2. Explain what triggers each phase in terms of React's operation.
    3. Connect each phase to practical development needs.
    4. Relate to modern functional component patterns.
    5. Discuss how this model helps with debugging and optimization.

    Key points to hit

    • Mounting occurs once when a component is first created and added to the DOM, perfect for initialization and data fetching.
    • Updating happens whenever props change, state changes, or parent re-renders, allowing components to respond to new data.
    • Unmounting provides cleanup opportunities before component removal to prevent memory leaks and cancel ongoing operations.
    • Understanding these phases helps predict when re-renders occur and optimize accordingly.

    Common mistakes

    • Confusing re-rendering with remounting - components update far more often than they mount or unmount.
    • Not recognizing that the same lifecycle model applies to functional components through useEffect dependencies.

    Sample answer

    React components go through three main phases. The mounting phase happens once when the component first appears - this is where I initialize state and fetch initial data. The updating phase happens whenever props or state change, and the component needs to reflect new information. This is the most frequent phase.

    Finally, unmounting happens when the component is being removed, giving me a chance to clean up subscriptions or timers. Even with hooks, this same mental model applies - useEffect with an empty dependency array mimics mounting, useEffect with dependencies handles updates, and the cleanup function handles unmounting.

    How to level up

    • Recognize that React may mount and unmount components multiple times in Concurrent Mode, so always write idempotent mounting logic.
    • Use React DevTools Profiler to visualize when components are mounting vs updating to identify unnecessary re-renders.
    • Understand that error boundaries introduce additional lifecycle phases for error recovery that don't exist in normal component flow.

    Follow-up questions to expect

    • How does React decide when to unmount a component versus just updating it?
    • What happens to the lifecycle when React Suspense is involved?
    • How do keys affect the mounting and unmounting behavior?
    Practice this question with AI feedback →
    What are styled-components? How does CSS-in-JS work?
    medium

    What they're really asking

    This tests understanding of CSS-in-JS concepts and practical experience with styled-components. The interviewer wants to see if you understand the benefits and trade-offs of this styling approach.

    How you'll be scored

    Weak

    Basic awareness of styled-components without understanding the underlying CSS-in-JS concepts or practical implications.

    Average

    Can explain how styled-components work and their basic benefits but lacks understanding of performance implications or alternatives.

    Strong

    Demonstrates comprehensive understanding of CSS-in-JS philosophy, styled-components implementation, and thoughtful analysis of when to use this approach.

    How to structure your answer

    1. Explain what styled-components are and how they create styled elements.
    2. Describe how CSS-in-JS generates and injects styles dynamically.
    3. List the main benefits: component encapsulation, dynamic styling, no naming conflicts.
    4. Discuss trade-offs: runtime performance, bundle size, learning curve.
    5. Compare with alternatives like CSS modules or utility frameworks.

    Key points to hit

    • Styled-components use template literals to create React components with styles attached, eliminating the need for separate CSS files.
    • CSS-in-JS generates unique class names automatically, preventing style conflicts and ensuring true component encapsulation.
    • Dynamic styling based on props becomes straightforward since JavaScript expressions can directly influence CSS.
    • Runtime style injection means styles are only loaded when components are used, but adds overhead during rendering.

    Common mistakes

    • Not considering the performance impact of runtime style generation, especially for frequently re-rendering components.
    • Overusing dynamic styles when static CSS would be more efficient and maintainable.

    Sample answer

    Styled-components let you write CSS directly in your JavaScript using template literals to create styled React components. For example, you can create a Button component with styles and then use props to dynamically change colors or sizes. Under the hood, styled-components generates unique class names and injects the CSS into the document head at runtime.

    This gives you true component encapsulation and makes dynamic styling really natural. The main trade-off is runtime performance since styles are generated during rendering, but you gain developer experience benefits like automatic vendor prefixing and the ability to use JavaScript logic in your styles.

    How to level up

    • Use styled-components' shouldForwardProp to prevent styled props from being passed to DOM elements and causing React warnings.
    • Consider using styled-components' css helper and theme provider for consistent design systems across large applications.
    • Evaluate build-time CSS-in-JS solutions like compiled or zero-runtime alternatives for performance-critical applications.

    Follow-up questions to expect

    • How would you handle global styles in a styled-components application?
    • What are the performance implications of styled-components compared to CSS modules?
    • How do you test components that use styled-components?
    Practice this question with AI feedback →

    React 18+ / Modern React Questions (12)

    What is Concurrent Mode / Concurrent Rendering in React? How does it improve performance?
    hard

    What they're really asking

    This tests understanding of React's advanced rendering architecture and performance optimization strategies. The interviewer wants to see if you understand cutting-edge React concepts and their practical implications.

    How you'll be scored

    Weak

    Vague awareness of Concurrent Mode without understanding the technical concepts or performance benefits.

    Average

    Can explain basic concepts like time slicing and interruptible rendering but lacks understanding of practical applications.

    Strong

    Demonstrates deep understanding of Concurrent Rendering's technical implementation and can articulate specific performance benefits and use cases.

    How to structure your answer

    1. Define Concurrent Rendering and its core goal of keeping UI responsive.
    2. Explain time slicing and how React can interrupt and resume work.
    3. Describe priority-based scheduling and how different updates get different priorities.
    4. Connect to practical features like Suspense and automatic batching.
    5. Discuss the transition from Concurrent Mode to Concurrent Features in React 18.

    Key points to hit

    • Concurrent Rendering allows React to interrupt expensive rendering work to handle high-priority updates like user input, preventing UI blocking.
    • Time slicing breaks rendering work into small chunks, yielding control back to the browser to maintain 60fps and responsive interactions.
    • useTransition and useDeferredValue provide APIs to mark updates as non-urgent, letting React prioritize user interactions.
    • Automatic batching across async operations reduces re-renders by grouping state updates from promises, timeouts, and event handlers.

    Common mistakes

    • Assuming Concurrent Features automatically make all apps faster without understanding that benefits depend on having expensive rendering work.
    • Not recognizing that Concurrent Rendering can cause components to render multiple times, requiring idempotent effect logic.

    Sample answer

    Concurrent Rendering in React 18 allows React to interrupt rendering work to handle more urgent updates, keeping the UI responsive. Instead of blocking the browser while rendering a large component tree, React uses time slicing to break work into chunks and yield control back to the browser between chunks.

    This means if a user clicks a button while React is rendering a long list, React can pause the list rendering, handle the button click immediately, then resume the list work. Features like useTransition let me mark certain updates as non-urgent, so React can prioritize user interactions.

    The key benefit is maintaining smooth 60fps performance even with complex UIs.

    How to level up

    • Understand that Concurrent Rendering requires rethinking effect cleanup since components may render multiple times before committing.
    • Use React DevTools Profiler with Concurrent Features enabled to visualize how React prioritizes different types of updates.
    • Learn to identify CPU-bound rendering work in your app that would benefit from time slicing versus I/O-bound work that needs Suspense.

    Follow-up questions to expect

    • How does useTransition work and when would you use it in a real application?
    • What's the relationship between Concurrent Rendering and Suspense?
    • How do you test components that use Concurrent Features?
    Practice this question with AI feedback →
    How does React handle concurrent rendering with multiple updates and prioritize them?
    hard

    What they're really asking

    This tests understanding of React's concurrent features and scheduling system. The interviewer wants to see if you grasp how React prioritizes work to maintain responsiveness in complex applications.

    How you'll be scored

    Weak

    Confuses concurrent rendering with basic async operations or can't explain prioritization.

    Average

    Correctly explains time-slicing and basic priority levels but lacks depth on scheduling.

    Strong

    Demonstrates understanding of lanes, interrupt mechanisms, and how concurrent features solve real performance problems.

    How to structure your answer

    1. Define concurrent rendering and time-slicing.
    2. Explain React's lane-based priority system.
    3. Describe how interrupts and resumption work.
    4. Give examples of high vs low priority updates.
    5. Mention real-world benefits for user experience.

    Key points to hit

    • React breaks work into chunks and yields control back to the browser to prevent blocking.
    • Lane-based priority system assigns different urgency levels to updates (user input vs background data)
    • High-priority updates can interrupt low-priority work, which gets resumed later.
    • Features like useTransition and useDeferredValue leverage this prioritization system.

    Common mistakes

    • Thinking concurrent mode automatically makes everything faster without understanding the priority trade-offs.
    • Confusing concurrent rendering with React 18's automatic batching feature.

    Sample answer

    React's concurrent rendering uses time-slicing to break work into small chunks, yielding control back to the browser between chunks so the main thread stays responsive. React assigns different priority levels called lanes to updates. For example, typing in an input gets a high-priority lane and will interrupt a low-priority background data fetch.

    The interrupted work isn't thrown away, it gets resumed after the urgent update finishes. This means users see immediate feedback for interactions while heavy computation happens in the background without blocking the UI.

    How to level up

    • Understand that not all React 18 features require concurrent mode, only certain APIs like useTransition activate it.
    • Know that concurrent features are opt-in through specific hooks rather than automatic optimizations.
    • Be aware of potential bugs when components assume synchronous rendering behavior.

    Follow-up questions to expect

    • How would you debug performance issues in an app using concurrent features?
    • What are the potential downsides of using useTransition everywhere?
    • How does Suspense interact with concurrent rendering?
    Practice this question with AI feedback →
    What is automatic batching in React 18? How is it different from React 17?
    hard

    What they're really asking

    This tests knowledge of React 18's batching improvements and performance implications. The interviewer wants to see if you understand how React optimizes renders across different event contexts.

    How you'll be scored

    Weak

    Can't explain what batching is or incorrectly describes the React 17 vs 18 differences.

    Average

    Correctly explains automatic batching but doesn't demonstrate understanding of the performance impact.

    Strong

    Shows deep understanding of when batching occurs, the createRoot requirement, and real performance benefits.

    How to structure your answer

    1. Define what batching means in React context.
    2. Explain React 17's limited batching scope.
    3. Describe React 18's automatic batching expansion.
    4. Show code example demonstrating the difference.
    5. Explain the performance and user experience benefits.

    Key points to hit

    • Batching groups multiple state updates into a single re-render to improve performance.
    • React 17 only batched updates inside event handlers, not in promises, timeouts, or native event handlers.
    • React 18 with createRoot automatically batches updates everywhere, including async contexts.
    • You can opt out of batching using flushSync when you need synchronous updates.

    Common mistakes

    • Assuming automatic batching works with legacy ReactDOM.render instead of createRoot.
    • Not understanding that batching affects when effects run, not just render count.

    Sample answer

    Automatic batching in React 18 groups multiple state updates into a single re-render for better performance. In React 17, this only happened inside event handlers like onClick, but updates in promises or timeouts would cause separate renders.

    React 18 with createRoot extends batching to all contexts, so even setState calls inside fetch callbacks or setTimeout get batched together. This means fewer renders and better performance. If you need synchronous updates for specific cases like focus management, you can use flushSync to opt out.

    How to level up

    • Remember that automatic batching requires using createRoot, not the legacy ReactDOM.render.
    • Understand that batched updates can change the timing of useEffect callbacks.
    • Know when to use flushSync for cases requiring immediate DOM updates like scrolling or focus.

    Follow-up questions to expect

    • When would you use flushSync to bypass automatic batching?
    • How does automatic batching affect useEffect timing?
    • What happens if you mix createRoot and legacy render in the same app?
    Practice this question with AI feedback →
    What are React Server Components?
    hard

    What they're really asking

    This tests understanding of React's newest paradigm shift toward server-side rendering optimization. The interviewer wants to see if you grasp the architectural implications and performance benefits.

    How you'll be scored

    Weak

    Confuses Server Components with traditional SSR or can't explain the zero-bundle benefit.

    Average

    Correctly explains that Server Components run on the server but lacks depth on serialization and boundaries.

    Strong

    Demonstrates understanding of the zero-bundle size benefit, serialization format, and integration with client components.

    How to structure your answer

    1. Define Server Components and their execution environment.
    2. Explain the zero JavaScript bundle benefit.
    3. Describe the serialization and streaming process.
    4. Contrast with traditional SSR and client components.
    5. Mention current ecosystem support and limitations.

    Key points to hit

    • Server Components run entirely on the server and send serialized output to the client, not JavaScript code.
    • They have zero impact on client bundle size since their code never ships to the browser.
    • Server Components can directly access databases and server resources without API layers.
    • They work alongside client components but have restrictions like no state or browser APIs.

    Common mistakes

    • Thinking Server Components are the same as traditional server-side rendering with hydration.
    • Assuming you can use hooks or browser APIs in Server Components.

    Sample answer

    React Server Components are a new type of component that runs entirely on the server and sends serialized output to the client instead of JavaScript code. Unlike traditional SSR where components hydrate on the client, Server Components have zero bundle size impact because their code never ships to the browser.

    They can directly access databases, file systems, and other server resources without building API endpoints. The server sends a special serialized format that describes the component tree, which gets merged with client components.

    This gives you the performance benefits of server rendering without the complexity of hydration for parts of your app that don't need interactivity.

    How to level up

    • Understand that Server Components are currently best supported through frameworks like Next.js 13+ App Router.
    • Know that Server Components can import and render Client Components, but not vice versa.
    • Recognize that the serialization format enables streaming and progressive enhancement.

    Follow-up questions to expect

    • How do you pass data from Server Components to Client Components?
    • What are the limitations of Server Components compared to regular components?
    • How do Server Components integrate with Suspense and streaming?
    Practice this question with AI feedback →
    When should you use client components vs server components?
    hard

    What they're really asking

    This tests architectural decision-making skills for modern React applications. The interviewer wants to see if you can choose the right component type based on requirements and understand the trade-offs.

    How you'll be scored

    Weak

    Can't articulate clear criteria for choosing between component types or gives incorrect guidance.

    Average

    Provides basic criteria like interactivity vs static content but lacks nuance about boundaries.

    Strong

    Demonstrates understanding of performance implications, data access patterns, and boundary management strategies.

    How to structure your answer

    1. Identify key decision criteria.
    2. Explain when Server Components are optimal.
    3. Describe scenarios requiring Client Components.
    4. Discuss boundary management strategies.
    5. Address performance and complexity trade-offs.

    Key points to hit

    • Use Server Components for static content, data fetching, and components that don't need browser APIs.
    • Use Client Components for interactive features, state management, and browser API access.
    • Consider bundle size impact and place interactive boundaries as deep in the tree as possible.
    • Server Components can render Client Components but not the other way around.

    Common mistakes

    • Making entire pages Client Components when only small parts need interactivity.
    • Trying to use state or effects in Server Components without understanding the execution model.

    Sample answer

    I choose Server Components for static content, data fetching, and anything that doesn't need browser APIs because they have zero bundle impact and can access server resources directly. I use Client Components for interactive features like forms, state management, and anything requiring useEffect or browser APIs.

    The key is pushing the client boundary as deep as possible in the component tree. For example, I'd make a blog post layout a Server Component that fetches content, but the comment form at the bottom would be a Client Component. This minimizes bundle size while maintaining interactivity where needed.

    How to level up

    • Design component boundaries by thinking about data flow and where interactivity is actually needed.
    • Use the 'use client' directive strategically at boundary points rather than sprinkling it everywhere.
    • Consider that Server Components enable new patterns like co-locating data fetching with presentation logic.

    Follow-up questions to expect

    • How would you handle shared state between Server and Client Components?
    • What strategies would you use to minimize Client Component bundle size?
    • How do you debug issues that span Server and Client Component boundaries?
    Practice this question with AI feedback →
    What is useTransition and how does it help with expensive state updates?
    hard

    What they're really asking

    This tests understanding of React's concurrent features for handling expensive operations. The interviewer wants to see if you can prevent UI blocking while maintaining responsive user interactions.

    How you'll be scored

    Weak

    Confuses useTransition with regular async operations or can't explain the isPending state.

    Average

    Correctly explains that useTransition makes updates non-blocking but lacks depth on priority implications.

    Strong

    Demonstrates understanding of how transitions work with concurrent rendering and when to apply them strategically.

    How to structure your answer

    1. Define useTransition and its core purpose.
    2. Explain how it marks updates as non-urgent.
    3. Describe the isPending state for user feedback.
    4. Show practical example with expensive operations.
    5. Discuss when to use it vs other optimization techniques.

    Key points to hit

    • useTransition marks state updates as non-urgent so they don't block user interactions.
    • Returns isPending to show loading states while transitions are happening.
    • Works with React's concurrent rendering to yield control during expensive updates.
    • Best for updates that cause heavy re-renders like filtering large lists or complex calculations.

    Common mistakes

    • Using useTransition for every state update instead of only expensive ones that block the UI.
    • Forgetting to show loading states with isPending, leaving users without feedback.

    Sample answer

    useTransition allows me to mark expensive state updates as non-urgent so they don't block user interactions. It returns a startTransition function and isPending boolean. When I wrap a state update in startTransition, React treats it as low priority and will interrupt it for urgent updates like typing.

    For example, when filtering a large product list, I'd wrap the filter state update in startTransition so typing in the search box stays responsive while the expensive filtering happens in the background. I use isPending to show a loading spinner during the transition so users know something is happening.

    How to level up

    • Combine useTransition with useDeferredValue for even more granular control over update timing.
    • Profile your app to identify which updates actually benefit from transitions rather than applying blindly.
    • Consider that transitions work best when the expensive work is in rendering, not in event handlers themselves.

    Follow-up questions to expect

    • How does useTransition differ from useDeferredValue?
    • What would happen if you wrapped every state update in startTransition?
    • How would you debug performance issues in components using useTransition?
    Practice this question with AI feedback →
    What is useDeferredValue and how does it differ from useTransition?
    hard

    What they're really asking

    This tests nuanced understanding of React 18 concurrent features and the specific differences between two hooks that seem similar. The interviewer wants to see if you can articulate when to use each and why they exist as separate APIs.

    How you'll be scored

    Weak

    Thinks they are the same or cannot explain either hook clearly.

    Average

    Knows both defer rendering but struggles to explain the practical difference.

    Strong

    Clearly explains that useTransition wraps a state update you control while useDeferredValue defers a value you receive, with concrete examples showing when each is the right choice.

    How to structure your answer

    1. Define each hook briefly.
    2. Explain the key architectural difference: controlling the update vs deferring a value.
    3. Show when you use useTransition (you own the setState)
    4. Show when you use useDeferredValue (you receive the value as a prop)
    5. Compare their API surfaces and behavior.

    Key points to hit

    • useTransition wraps a setState call you control, marking it as low-priority. It returns isPending for loading states and startTransition to wrap the update.
    • useDeferredValue accepts a value (often a prop) and returns a deferred version. You use it when you don't control the state update.
    • useTransition gives you an isPending boolean. useDeferredValue requires you to compare the original and deferred values to detect pending state.
    • Both use the same underlying concurrent rendering mechanism but provide different ergonomics for different ownership patterns.

    Common mistakes

    • Using both on the same value, which is redundant since they solve the same problem from different access points.
    • Not understanding that useDeferredValue requires React.memo on the consuming component to actually skip expensive rendering with the old value.

    Sample answer

    Both hooks defer expensive rendering, but they target different situations based on who controls the state update. useTransition is for when you own the state setter. You wrap your setState call in startTransition, and React processes it at a lower priority.

    You get an isPending boolean to show loading indicators. useDeferredValue is for when you receive a value you don't control, like a prop from a parent component. You pass it to useDeferredValue and get a deferred copy that lags behind the original during heavy renders.

    The key architectural decision is simple: can I access the setState call? If yes, useTransition. If no, useDeferredValue. For example, a SearchPage component that owns the query state uses useTransition. But a SearchResults component that receives query as a prop uses useDeferredValue.

    One important detail: useDeferredValue only helps if the child consuming the deferred value is wrapped in React.memo, so it can skip rendering with the unchanged deferred value.

    How to level up

    • Mention that useTransition can delay Suspense fallbacks by keeping old content visible during navigation transitions.
    • Discuss that both hooks use React's lane-based priority system under the hood, but useTransition provides more control through isPending.
    • Point out that in a component tree, you might use useTransition at the top and useDeferredValue at leaf nodes that receive the transitioning values as props.

    Follow-up questions to expect

    • Can you show a component tree where both hooks are used at different levels?
    • How do you show loading indicators with useDeferredValue since it doesn't have isPending?
    • How do these hooks interact with Suspense boundaries?
    Practice this question with AI feedback →
    What is the useId hook introduced in React 18?
    medium

    What they're really asking

    This tests awareness of React 18 additions and the specific SSR problem that useId solves. The interviewer wants to see if you understand hydration-safe ID generation and practical accessibility patterns.

    How you'll be scored

    Weak

    Has not heard of useId or suggests using random IDs in components.

    Average

    Knows useId generates unique IDs for accessibility attributes.

    Strong

    Explains the SSR hydration mismatch problem, shows usage patterns with form labels and ARIA attributes, and understands that useId generates deterministic IDs based on component tree position.

    How to structure your answer

    1. Explain what useId does and why it was introduced in React 18.
    2. Describe the hydration mismatch problem it solves.
    3. Show practical usage with form labels and ARIA attributes.
    4. Clarify what useId should not be used for.
    5. Mention the identifierPrefix option for multiple React roots.

    Key points to hit

    • useId generates a unique, deterministic ID string that matches between server and client renders.
    • It solves the problem where random or counter-based IDs produce different values on server and client, causing hydration mismatches.
    • Primary use is connecting form labels to inputs with htmlFor/id and linking ARIA attributes like aria-describedby to error messages.
    • Do not use useId for list keys. Keys should come from data, not be generated by React.

    Common mistakes

    • Using useId for list item keys, which is a different problem requiring stable data-based identifiers.
    • Generating IDs with Math.random() or global counters in SSR applications, which causes hydration mismatches.

    Sample answer

    useId was introduced in React 18 to generate unique IDs that are stable across server and client renders. The problem it solves is hydration safety. If you use Math.random() or an incrementing counter to generate IDs, the server produces one value and the client produces a different one.

    React detects the mismatch and throws a hydration error. useId generates deterministic IDs based on the component's position in the tree, so the server and client always produce the same ID. I use it for accessibility.

    When I have a text input, I call const id = useId(), set the input's id to that value, and the label's htmlFor to the same value. Same pattern for connecting aria-describedby to an error message div.

    You can derive multiple related IDs from one call by appending suffixes, like id + '-email' and id + '-password'. Just don't use it for list keys.

    How to level up

    • Mention the identifierPrefix option in createRoot that prefixes all useId values, preventing collisions when multiple React roots exist on the same page.
    • Discuss that useId values contain colons which makes them invalid for CSS selectors, so avoid using them for styling purposes.
    • Point out that useId is one of the few hooks that produces the same value on every render without a dependency array, making it simpler than useMemo for stable values.

    Follow-up questions to expect

    • How would you handle unique IDs in a micro-frontend architecture with multiple React roots?
    • Why do useId values contain colons and what limitation does that create?
    • How does useId determine the component's position in the tree?
    Practice this question with AI feedback →
    Is it possible to prevent automatic batching in React 18?
    hard

    What they're really asking

    This tests deep knowledge of React 18 rendering behavior and the escape hatch for cases where you need synchronous DOM updates. The interviewer wants to see if you understand when automatic batching is undesirable and how to opt out safely.

    How you'll be scored

    Weak

    Doesn't know what automatic batching is or how to prevent it.

    Average

    Knows about flushSync but can't explain when it would actually be needed.

    Strong

    Explains flushSync from react-dom, gives concrete scenarios where synchronous updates are necessary, and warns about performance implications of overusing it.

    How to structure your answer

    1. Briefly explain automatic batching in React 18.
    2. Introduce flushSync as the opt-out mechanism.
    3. Show how flushSync forces a synchronous re-render.
    4. Give concrete use cases where this is necessary.
    5. Warn about performance implications.

    Key points to hit

    • React 18 automatically batches all state updates regardless of context (event handlers, promises, timeouts, native events)
    • flushSync from react-dom forces React to flush DOM updates synchronously inside its callback, opting out of batching.
    • Use cases include reading DOM measurements immediately after a state update, integrating with non-React libraries that need the DOM to be current, and animation coordination.
    • flushSync should be used sparingly because it defeats the performance benefits of batching and can cause unnecessary re-renders.

    Common mistakes

    • Using flushSync as a default pattern because batching seems unpredictable, when the solution is usually understanding the batching behavior better.
    • Not understanding that flushSync only affects the updates inside its callback. Updates outside it are still batched normally.

    Sample answer

    Yes, you can opt out of automatic batching using flushSync from react-dom. In React 18 with createRoot, all state updates are batched into a single re-render by default, even in promises, setTimeout, and native event handlers. flushSync wraps a state update and forces React to apply it synchronously before the next line of code runs.

    For example, if you need to update state and then immediately read the resulting DOM dimensions, flushSync ensures the DOM reflects the update before you call getBoundingClientRect. Another use case is integrating with third-party libraries that expect the DOM to be in a specific state after you update it. But you should use flushSync rarely.

    It forces a synchronous re-render, which blocks the main thread and loses the performance benefit of batching. If you find yourself using it often, the code probably needs restructuring rather than more flushSync calls.

    How to level up

    • Mention that flushSync triggers lifecycle methods and effects synchronously, which can cause unexpected behavior if effects have async dependencies.
    • Discuss that you can wrap only the specific update that needs to be synchronous in flushSync while letting other updates in the same handler stay batched.
    • Point out that the legacy ReactDOM.render API does not batch updates outside event handlers anyway, so flushSync is mainly relevant for apps using createRoot.

    Follow-up questions to expect

    • Can you show a concrete example where flushSync is necessary?
    • What happens if you nest flushSync calls?
    • How does flushSync affect pending useEffect cleanup functions?
    Practice this question with AI feedback →
    How does Suspense work with data fetching in React 18+?
    hard

    What they're really asking

    This tests understanding of React's evolving approach to async data in the component tree. The interviewer wants to see if you know the mechanism behind Suspense for data fetching and which libraries support it.

    How you'll be scored

    Weak

    Only associates Suspense with React.lazy code splitting or cannot explain the data fetching mechanism.

    Average

    Knows that compatible libraries can trigger Suspense boundaries during data loading.

    Strong

    Explains the throw-promise mechanism, which libraries support it (Relay, TanStack Query), how it changes the component mental model, and the relationship with streaming SSR and the use hook.

    How to structure your answer

    1. Explain how Suspense for data fetching works mechanically.
    2. Describe the throw-promise protocol that libraries implement.
    3. List which libraries currently support Suspense data fetching.
    4. Show how it simplifies component code compared to useEffect patterns.
    5. Connect to streaming SSR and the use hook in React 19.

    Key points to hit

    • When a component needs data that isn't ready, it throws a promise. The nearest Suspense boundary catches it and shows the fallback until the promise resolves.
    • Libraries like Relay, TanStack Query (experimental), and Next.js implement the Suspense protocol by managing the cache and throwing promises at the right time.
    • This eliminates the loading/error/data state management pattern in components. The component code assumes data is available and Suspense handles the waiting.
    • React 19 introduces the use hook as the built-in way to read promises and context, making Suspense integration simpler without requiring library-specific wrappers.

    Common mistakes

    • Trying to throw promises manually in components without a proper cache, which causes infinite fetching loops because each render creates a new promise.
    • Thinking you can just wrap a fetch call in Suspense without a compatible library that manages the promise caching and status tracking.

    Sample answer

    Suspense for data fetching works through a throw-promise protocol. When a component tries to read data that isn't loaded yet, it throws a promise. The nearest Suspense boundary catches the thrown promise, renders the fallback, and re-renders the component when the promise resolves.

    The key is that you need a library that implements this protocol correctly. You can't just throw fetch() inside a component because every render would create a new promise, causing infinite loops. Libraries like Relay, TanStack Query with its experimental Suspense mode, and Next.js handle the caching layer that makes this work.

    The benefit for developers is huge. Component code becomes synchronous-looking. You just read the data and render. No more tracking loading, error, and data states manually. React 19 makes this even cleaner with the use hook, which lets you read a promise or context value directly and integrates with Suspense automatically.

    How to level up

    • Mention that Suspense for data fetching enables streaming SSR where the server sends HTML for ready components and streams in suspended components as their data resolves.
    • Discuss how Error Boundaries work alongside Suspense boundaries: Suspense handles loading states while Error Boundaries handle failure states.
    • Point out that the render-as-you-fetch pattern (start fetching before rendering) is the recommended approach with Suspense, as opposed to fetch-on-render (useEffect pattern) or fetch-then-render.

    Follow-up questions to expect

    • What is the render-as-you-fetch pattern and how does it work with Suspense?
    • How does the use hook in React 19 simplify Suspense for data fetching?
    • What happens if a suspended component throws an error instead of resolving?
    Practice this question with AI feedback →
    What is the new JSX transform and what are its benefits?
    medium

    What they're really asking

    This tests awareness of React build tooling evolution and understanding of what happens at compile time. The interviewer wants to see if you know why the React import was historically required and what changed.

    How you'll be scored

    Weak

    Doesn't know what the JSX transform is or why React had to be imported in JSX files.

    Average

    Knows that React 17 eliminated the need to import React in every file that uses JSX.

    Strong

    Explains the old transform (React.createElement), the new transform (jsx function from react/jsx-runtime), the benefits for bundle size and developer experience, and how to configure it.

    How to structure your answer

    1. Explain the old JSX transform: JSX compiled to React.createElement.
    2. Explain why import React was required in every JSX file.
    3. Introduce the new transform from React 17.
    4. Show the compilation output difference.
    5. List the practical benefits.

    Key points to hit

    • The old transform compiled JSX to React.createElement calls, which required React to be in scope in every file that used JSX.
    • The new transform (React 17+) compiles JSX to jsx() and jsxs() calls from a react/jsx-runtime module that the compiler imports automatically.
    • You no longer need to import React just for JSX. Only import it when you actually use React APIs like hooks or createContext.
    • The new transform enables minor bundle size improvements because the jsx function is slightly more optimized than createElement.

    Common mistakes

    • Thinking the new transform is a React version feature when it's actually a compiler/bundler configuration change that can work with older React versions too.
    • Removing all React imports including ones needed for hooks and APIs, not just the JSX import.

    Sample answer

    Before React 17, JSX compiled to React.createElement() calls. That meant every file using JSX needed import React from 'react' at the top, even if you never referenced React directly. The new JSX transform, introduced in React 17, changes the compilation output.

    Instead of React.createElement, JSX now compiles to jsx() and jsxs() functions from react/jsx-runtime, and the compiler inserts this import automatically. You no longer need the React import in every file. This is a developer experience improvement since forgetting the import was a common error.

    It also gives a small bundle size benefit because the jsx runtime function is slightly more optimized than createElement. The transform is configured in Babel with the automatic runtime option or in TypeScript with jsx: react-jsx in tsconfig. It's worth noting this is a build tool change, not a runtime change.

    React 16.14+ supports it too if you update your compiler config.

    How to level up

    • Mention that you can run the official codemod react-codemod/update-react-imports to automatically remove unnecessary React imports across your codebase.
    • Discuss that the new transform also passes a source location to jsx() in development mode, improving error messages with file and line information.
    • Point out that the jsxs function is used specifically for elements with static children arrays, enabling optimizations the old createElement couldn't do.

    Follow-up questions to expect

    • How do you configure the new JSX transform in Babel versus TypeScript?
    • What is the difference between jsx() and jsxs() in the new transform?
    • Can you use the new transform with older versions of React?
    Practice this question with AI feedback →
    What are capture phase events in React?
    hard

    What they're really asking

    This tests understanding of React's event system implementation and advanced event handling patterns. The interviewer wants to see if you know how React's synthetic events work beyond basic onClick handlers.

    How you'll be scored

    Weak

    Confuses event bubbling with capturing or gives incorrect information about React's event delegation.

    Average

    Correctly explains capture phase but can't provide practical use cases or implementation details.

    Strong

    Demonstrates deep understanding of React's event system, provides concrete examples, and explains when capture phase is actually useful.

    How to structure your answer

    1. Explain React's synthetic event system and event delegation.
    2. Define capture phase vs bubbling phase.
    3. Show how to use capture phase in React with onClickCapture.
    4. Provide practical use case where capture phase solves a problem.
    5. Mention performance implications and when to avoid it.

    Key points to hit

    • React uses event delegation with a single listener on the document root, not individual DOM elements.
    • Capture phase events fire before bubbling phase, traveling from root to target element.
    • Use onClickCapture, onMouseDownCapture syntax to register capture phase listeners in React.
    • Capture phase is useful for intercepting events before they reach child components, like implementing custom drag and drop or modal backdrop clicks.

    Common mistakes

    • Thinking that React events work exactly like native DOM events without understanding the synthetic event wrapper and delegation.
    • Using capture phase unnecessarily when regular event handling would work, adding complexity without benefit.

    Sample answer

    React uses synthetic events with event delegation, meaning there's one event listener on the document root that handles all events. The capture phase happens first, where events travel from the root down to the target element, then bubbling goes back up. In React, you can use onClickCapture instead of onClick to handle the capture phase.

    I've used this when building a modal component where I needed to detect clicks on the backdrop before any child components could handle them. You'd put onClickCapture on the backdrop div to close the modal, which fires before any onClick handlers in the modal content.

    How to level up

    • Understand that React 17 changed event delegation from document to the React root container, which matters for micro-frontends.
    • Know that stopPropagation() in capture phase prevents the event from reaching the target element entirely.
    • Use capture phase for implementing focus management patterns like focus traps in accessibility scenarios.

    Follow-up questions to expect

    • How would you implement a custom hook that detects clicks outside a component using capture phase?
    • What's the difference between event delegation in React 16 vs React 17?
    • When would you choose capture phase over using a ref and addEventListener?
    Practice this question with AI feedback →

    Ready to put this into practice?

    Practice this with MockIF →

    Still applying for jobs? Let Auto Apply do it

    Testing Questions (10)

    How do you test React applications?
    medium

    What they're really asking

    This tests knowledge of React testing strategies and tools ecosystem. The interviewer wants to see if you can design a comprehensive testing approach for React applications.

    How you'll be scored

    Weak

    Only mentions basic unit tests or shows confusion between different testing types and tools.

    Average

    Lists common testing tools but can't explain when to use each type of test or testing strategy.

    Strong

    Demonstrates understanding of testing pyramid, explains different testing approaches for React components, and shows practical experience with testing user interactions.

    How to structure your answer

    1. Outline the testing pyramid: unit, integration, end-to-end tests.
    2. Explain React-specific testing approaches: component testing vs hook testing.
    3. Cover key tools: Jest, React Testing Library, Cypress or Playwright.
    4. Discuss what to test: user interactions, state changes, API integration.
    5. Address testing best practices: avoiding implementation details, testing behavior.

    Key points to hit

    • Focus on testing user behavior and component outputs rather than internal implementation details like state variables.
    • Use React Testing Library for component testing because it encourages testing from the user's perspective.
    • Test components in isolation with mocked dependencies, and test integration points separately.
    • Write tests that would break when the user experience breaks, not when you refactor internal code.

    Common mistakes

    • Testing implementation details like checking if setState was called instead of testing the resulting UI changes.
    • Writing tests that are too brittle and break when you refactor code without changing behavior.

    Sample answer

    I approach React testing with three layers. Unit tests for individual components using Jest and React Testing Library, focusing on user interactions like clicking buttons and seeing expected text appear. Integration tests for connected components that interact with context or make API calls, usually mocking external services.

    End-to-end tests with Cypress for critical user flows like authentication or checkout. I avoid testing implementation details and instead test what users actually see and do. For example, I test that clicking a submit button shows a success message, not that a specific state variable changed.

    How to level up

    • Use MSW (Mock Service Worker) to mock API calls at the network level instead of mocking fetch directly, making tests more realistic.
    • Implement custom render functions that wrap components with necessary providers and default props.
    • Consider using Storybook for visual regression testing and component documentation alongside your unit tests.

    Follow-up questions to expect

    • How do you test components that use React Context?
    • What's your strategy for testing components that make API calls?
    • How do you decide what deserves an end-to-end test vs a unit test?
    Practice this question with AI feedback →
    What is Jest and how is it used for testing React?
    medium

    What they're really asking

    This tests familiarity with Jest as React's default testing framework. The interviewer wants to see if you understand Jest's features and how to configure it for React projects.

    How you'll be scored

    Weak

    Basic knowledge of Jest as a test runner but can't explain React-specific setup or useful features.

    Average

    Knows Jest basics like describe/it blocks and common matchers but limited understanding of mocking or setup.

    Strong

    Demonstrates practical Jest knowledge including mocking, setup/teardown, and React-specific configuration and testing patterns.

    How to structure your answer

    1. Define Jest as a JavaScript testing framework with built-in test runner, assertion library, and mocking.
    2. Explain Jest's role in Create React App and typical React setup.
    3. Cover key Jest features: test organization, matchers, mocking capabilities.
    4. Show practical examples of testing React components with Jest.
    5. Discuss Jest configuration and React-specific setup.

    Key points to hit

    • Jest comes pre-configured in Create React App with Babel transformation and jsdom environment for testing React components.
    • Use Jest's mocking capabilities to mock modules, functions, and timers when testing React components with external dependencies.
    • Jest provides useful matchers for React testing like toBeInTheDocument when combined with jest-dom.
    • Configure Jest with setupFilesAfterEnv to include React Testing Library's custom matchers and global test setup.

    Common mistakes

    • Not understanding that Jest runs in Node.js with jsdom, not a real browser, which affects some DOM APIs and timing.
    • Forgetting to clean up mocks between tests, causing test pollution where one test affects another.

    Sample answer

    Jest is a JavaScript testing framework that comes built into Create React App. It includes a test runner, assertion library, and powerful mocking system. For React, Jest runs tests in a Node environment with jsdom to simulate the DOM.

    I use Jest's describe and it blocks to organize tests, expect assertions to check component behavior, and jest.mock to mock external dependencies like API calls. Jest also provides useful features like snapshot testing for component output and timer mocking for testing useEffect with delays.

    The setupTests.js file lets me configure jest-dom matchers that make React testing more convenient.

    How to level up

    • Use Jest's --watch mode during development to automatically re-run tests when files change, with pattern matching to focus on specific tests.
    • Configure Jest coverage thresholds in package.json to enforce minimum test coverage and catch untested code paths.
    • Leverage Jest's mock functions (jest.fn()) to test that callback props are called correctly and with expected arguments.

    Follow-up questions to expect

    • How do you mock a React component in Jest?
    • What's the difference between jest.mock and jest.spyOn?
    • How do you test components that use timers or setTimeout?
    Practice this question with AI feedback →
    What is React Testing Library and how do you use it?
    medium

    What they're really asking

    This tests understanding of React Testing Library's philosophy and practical usage. The interviewer wants to see if you know why RTL is preferred over Enzyme and how to write user-centric tests.

    How you'll be scored

    Weak

    Treats React Testing Library like Enzyme, focusing on implementation details instead of user behavior.

    Average

    Knows basic RTL queries like getByText but doesn't understand the testing philosophy or best practices.

    Strong

    Demonstrates understanding of RTL's user-focused approach, uses appropriate queries, and writes tests that resemble how users interact with components.

    How to structure your answer

    1. Explain React Testing Library's philosophy: test components like users interact with them.
    2. Cover the query hierarchy: getByRole, getByLabelText, getByText as preferred options.
    3. Show practical example of testing user interactions with fireEvent or userEvent.
    4. Explain how RTL encourages accessible component design.
    5. Contrast with implementation-focused testing approaches.

    Key points to hit

    • React Testing Library encourages testing components from the user's perspective, using queries that find elements by text content, labels, or roles rather than CSS classes or test IDs.
    • Use getByRole as the preferred query method because it mirrors how screen readers and users navigate interfaces.
    • The userEvent library provides more realistic user interactions than fireEvent, simulating actual browser behavior.
    • React Testing Library's queries encourage writing accessible components because tests break when proper ARIA labels or semantic HTML is missing.

    Common mistakes

    • Overusing getByTestId instead of semantic queries, which defeats the purpose of user-focused testing.
    • Testing component internal state or props instead of the resulting DOM output and user experience.

    Sample answer

    React Testing Library helps you test components the way users actually interact with them. Instead of testing internal state, you find elements by their text, labels, or ARIA roles. For example, I'd use getByRole('button', { name: 'Submit' }) rather than searching by CSS class.

    When testing interactions, I use userEvent.click() to simulate real user behavior more accurately than fireEvent. This approach naturally encourages accessible component design because your tests break when components lack proper labels or semantic markup. I've found that RTL tests are more resilient to refactoring since they focus on user outcomes rather than implementation details.

    How to level up

    • Use screen.debug() to see the current DOM structure when queries aren't working as expected.
    • Prefer waitFor() over act() for handling asynchronous updates, as it's more declarative and handles React's internal scheduling.
    • Create custom queries for domain-specific patterns in your application while still following RTL's user-focused philosophy.

    Follow-up questions to expect

    • When would you use getByTestId instead of semantic queries?
    • How do you test components that conditionally render based on props?
    • What's the difference between getBy, queryBy, and findBy queries?
    Practice this question with AI feedback →
    How do you test asynchronous code in React components?
    medium

    What they're really asking

    This tests knowledge of testing async operations in React components like API calls, useEffect, and state updates. The interviewer wants to see if you can handle timing issues and async testing patterns.

    How you'll be scored

    Weak

    Struggles with async testing concepts or suggests incorrect approaches like using setTimeout in tests.

    Average

    Knows about waitFor but limited understanding of different async scenarios or proper cleanup.

    Strong

    Demonstrates comprehensive understanding of async testing patterns, proper mocking strategies, and can handle complex async scenarios like race conditions.

    How to structure your answer

    1. Identify common async scenarios: API calls, useEffect, delayed state updates.
    2. Explain React Testing Library's async utilities: waitFor, findBy queries, act.
    3. Show mocking strategies for async operations using Jest.
    4. Cover proper cleanup and error handling in async tests.
    5. Discuss testing loading states and error scenarios.

    Key points to hit

    • Use waitFor() when waiting for DOM changes that happen after async operations complete, with a condition that describes what you're waiting for.
    • Mock async functions like fetch or axios at the module level using Jest, returning resolved or rejected promises to test different scenarios.
    • The findBy queries are shortcuts for getBy + waitFor, useful when you know an element will appear after an async operation.
    • Test both success and error states of async operations, including loading indicators and error messages that users would see.

    Common mistakes

    • Forgetting to wait for async operations to complete, leading to tests that pass incorrectly or have timing-dependent failures.
    • Not cleaning up pending async operations in tests, which can cause memory leaks and test interference.

    Sample answer

    When testing async code in React, I use React Testing Library's waitFor to wait for DOM changes after async operations. For components that fetch data, I mock the API call using jest.mock, then use waitFor to wait for the loading state to disappear and content to appear.

    I test both success and error scenarios by having my mocked function return resolved or rejected promises. For useEffect hooks, I often use findByText which combines getBy with waitFor automatically.

    The key is making sure tests wait for React to finish updating before making assertions, and cleaning up any pending operations in afterEach to prevent test interference.

    How to level up

    • Use MSW (Mock Service Worker) for more realistic API mocking that intercepts requests at the network level instead of mocking fetch directly.
    • Configure Jest to handle unhandled promise rejections properly and fail tests when async operations throw unexpected errors.
    • Use React's act() utility when testing custom hooks with async operations that don't immediately update the DOM.

    Follow-up questions to expect

    • How do you test a component that makes multiple API calls in sequence?
    • What's your approach to testing race conditions in React components?
    • How do you test custom hooks that contain async operations?
    Practice this question with AI feedback →
    How do you mock API calls in React component tests?
    medium

    What they're really asking

    This tests your understanding of test isolation and your ability to write predictable unit tests. The interviewer wants to see if you can decouple component behavior from external dependencies.

    How you'll be scored

    Weak

    Shows confusion about mocking or suggests testing against real APIs.

    Average

    Mentions jest.mock or MSW but lacks concrete implementation details.

    Strong

    Demonstrates multiple mocking approaches with clear examples and explains when to use each.

    How to structure your answer

    1. Choose your mocking strategy (jest.mock vs MSW vs manual mocks)
    2. Set up the mock before your test.
    3. Write assertions that verify component behavior, not API implementation.
    4. Clean up mocks between tests.
    5. Explain why mocking improves test reliability.

    Key points to hit

    • Use jest.mock for simple cases, MSW for complex request/response patterns.
    • Mock at the right level - mock the API client, not individual fetch calls.
    • Test loading states, success states, and error states separately.
    • Always restore mocks after tests to avoid test pollution.

    Common mistakes

    • Testing implementation details of the API call instead of component behavior.
    • Forgetting to mock error cases, which leaves critical paths untested.

    Sample answer

    I typically use jest.mock to mock my API client at the module level. For example, if I have a getUserData function, I'd mock it to return resolved promises with test data. Then I can test that my component shows loading state initially, renders the data correctly on success, and displays error messages on failure.

    I always test all three states because users will encounter each scenario. For more complex scenarios with multiple endpoints, I use MSW to intercept requests and return controlled responses.

    How to level up

    • Use MSW for integration-style tests where you need realistic request/response cycles.
    • Create reusable mock factories that generate consistent test data.
    • Test race conditions by controlling promise resolution timing with Jest's fake timers.

    Follow-up questions to expect

    • How would you test a component that makes multiple API calls?
    • What's your approach to testing optimistic updates?
    • How do you handle testing authentication flows with API calls?
    Practice this question with AI feedback →
    How do you test custom hooks in React?
    medium

    What they're really asking

    This tests whether you understand hooks as isolated units of logic and can test them without unnecessary component complexity. The interviewer wants to see if you can write focused tests for reusable logic.

    How you'll be scored

    Weak

    Suggests testing hooks only through components or shows confusion about React Testing Library's renderHook.

    Average

    Mentions renderHook but provides a basic example without handling side effects properly.

    Strong

    Demonstrates testing hooks in isolation with proper handling of async effects and state updates.

    How to structure your answer

    1. Use renderHook from React Testing Library to render the hook in isolation.
    2. Access hook values through result.current.
    3. Use act() when triggering state updates or side effects.
    4. Test initial state, state transitions, and cleanup behavior.
    5. Verify dependencies and effect triggers.

    Key points to hit

    • Use renderHook to test hooks without creating wrapper components.
    • Wrap state updates in act() to ensure React processes all updates.
    • Test useEffect cleanup functions by unmounting the hook.
    • For async hooks, use waitFor to handle promise resolution.

    Common mistakes

    • Not wrapping state updates in act(), causing warnings and unreliable tests.
    • Testing hooks through components when the logic could be tested in isolation.

    Sample answer

    I use renderHook from React Testing Library to test custom hooks in isolation. For a useCounter hook, I'd call renderHook(() => useCounter(0)), then access the current value through result.current. When testing increment functions, I wrap them in act() to ensure React processes the state update.

    For hooks with useEffect, I test both the effect trigger and cleanup by using rerender with different props and unmount. This approach lets me test the hook logic without the complexity of a full component.

    How to level up

    • Create custom render functions for hooks that need providers or context.
    • Use Jest's fake timers when testing hooks with delays or intervals.
    • Test error boundaries around hooks that might throw during rendering.

    Follow-up questions to expect

    • How would you test a hook that depends on React Context?
    • What's your approach to testing hooks with complex async logic?
    • How do you test hooks that use other hooks internally?
    Practice this question with AI feedback →
    How do you test components that use context or Redux?
    medium

    What they're really asking

    This tests your ability to set up test environments that mirror production context dependencies. The interviewer wants to see if you understand how to provide necessary context without testing context implementation details.

    How you'll be scored

    Weak

    Suggests avoiding context/Redux in tests or doesn't understand how to provide test context.

    Average

    Knows to wrap components in providers but provides minimal example.

    Strong

    Shows multiple approaches for different scenarios and explains trade-offs between mocking and real providers.

    How to structure your answer

    1. Create test providers with controlled state for your test scenario.
    2. Wrap your component with necessary providers during rendering.
    3. Use real reducers with test data rather than mocking Redux store completely.
    4. Test context updates by triggering actions and verifying component responses.
    5. Consider whether to test context logic separately from component behavior.

    Key points to hit

    • Wrap components in test providers with known initial state.
    • Use real context/Redux logic in tests to catch integration issues.
    • Create helper functions to render components with common provider setups.
    • Test both context consumption and context updates through user interactions.

    Common mistakes

    • Over-mocking context providers, which misses integration bugs between context and components.
    • Not providing required context, causing tests to fail with unclear error messages.

    Sample answer

    I create test versions of my providers with controlled initial state. For Redux, I'll create a test store with known data using the real reducer, then wrap my component with Provider. For Context, I render a custom provider with test values around my component.

    I typically create a renderWithProviders helper that takes initial state as a parameter. This approach lets me test how components respond to different context states while using the real context logic, so I catch integration bugs that pure mocking would miss.

    How to level up

    • Build custom render helpers that accept initial store/context state as parameters.
    • Test context updates by dispatching actions and verifying component re-renders.
    • Use different provider configurations to test edge cases like empty or loading states.

    Follow-up questions to expect

    • How do you test components that update context state?
    • What's your strategy for testing deeply nested context consumers?
    • How would you test context performance optimizations?
    Practice this question with AI feedback →
    What is Snapshot Testing?
    medium

    What they're really asking

    This tests your understanding of regression testing strategies and whether you know when snapshot testing is useful versus harmful. The interviewer wants to see if you can balance convenience with maintainability.

    How you'll be scored

    Weak

    Describes snapshot testing incorrectly or suggests using it for all components.

    Average

    Correctly explains snapshot testing but doesn't discuss appropriate use cases.

    Strong

    Explains snapshot testing with clear guidance on when to use it and when to avoid it.

    How to structure your answer

    1. Explain that snapshot testing captures component output and compares it to saved snapshots.
    2. Describe how Jest generates and updates snapshots automatically.
    3. Identify good use cases like testing pure components or preventing unintended markup changes.
    4. Warn about snapshot brittleness and meaningless updates.
    5. Suggest combining with targeted assertions for better test coverage.

    Key points to hit

    • Snapshot tests capture rendered output and flag unexpected changes.
    • Most useful for components with stable, predictable output.
    • Can become maintenance overhead if components change frequently.
    • Should complement, not replace, behavior-focused tests.

    Common mistakes

    • Using snapshots as the primary testing strategy instead of testing actual behavior.
    • Blindly updating snapshots without reviewing what changed and why.

    Sample answer

    Snapshot testing captures the rendered output of a component and saves it as a reference file. When the test runs again, Jest compares the current output to the saved snapshot and fails if they don't match. I find snapshots most useful for pure components that render predictable output, like formatted text or icons.

    They catch unintended changes quickly. However, I avoid them for dynamic components because they create maintenance overhead. I always review snapshot changes carefully before updating them, and I combine snapshots with specific assertions that test actual behavior.

    How to level up

    • Use property matchers for dynamic values like timestamps in snapshots.
    • Consider inline snapshots for small, critical pieces of output.
    • Create custom snapshot serializers for complex objects to make diffs more readable.

    Follow-up questions to expect

    • When would you choose not to use snapshot testing?
    • How do you handle snapshots that include timestamps or random values?
    • What's your process for reviewing snapshot changes in code reviews?
    Practice this question with AI feedback →
    What is the difference between shallow rendering and full DOM rendering?
    medium

    What they're really asking

    This tests your understanding of different testing strategies and their trade-offs. The interviewer wants to see if you can choose the right rendering approach based on what you're trying to test.

    How you'll be scored

    Weak

    Confuses the concepts or shows preference for shallow rendering in modern React.

    Average

    Correctly distinguishes between approaches but lacks nuanced understanding of when to use each.

    Strong

    Explains both approaches with clear guidance on modern best practices and specific use cases.

    How to structure your answer

    1. Define shallow rendering as testing one component level without rendering children.
    2. Define full DOM rendering as rendering the complete component tree.
    3. Explain that React Testing Library promotes full rendering by default.
    4. Discuss trade-offs: isolation vs integration, speed vs realism.
    5. Recommend full DOM rendering for most cases with strategic shallow rendering exceptions.

    Key points to hit

    • Shallow rendering tests components in isolation by stubbing child components.
    • Full DOM rendering creates a complete DOM tree and tests component integration.
    • React Testing Library encourages full DOM rendering to test user-facing behavior.
    • Full DOM rendering catches integration bugs that shallow rendering misses.

    Common mistakes

    • Defaulting to shallow rendering without considering integration testing benefits.
    • Using shallow rendering for components that rely heavily on child component behavior.

    Sample answer

    Shallow rendering only renders the immediate component without its children, while full DOM rendering creates the complete component tree in a virtual DOM. Enzyme popularized shallow rendering for isolated unit tests, but React Testing Library defaults to full DOM rendering because it better reflects how users interact with your app.

    I prefer full DOM rendering for most tests since it catches integration issues and tests actual user workflows. I only consider shallow rendering for complex components where I need to isolate specific logic from expensive child components.

    How to level up

    • Use React Testing Library's screen queries to find elements the way users would.
    • Consider rendering performance when testing large component trees, but measure before optimizing.
    • Mock expensive child components selectively rather than shallow rendering the entire tree.

    Follow-up questions to expect

    • How do you decide between integration tests and unit tests for React components?
    • What's your approach to testing component hierarchies with multiple levels?
    • How do you handle testing components with expensive child components?
    Practice this question with AI feedback →
    How do you handle long-running tasks without blocking the UI?
    hard

    What they're really asking

    This tests your understanding of React's single-threaded nature and ability to maintain responsive UIs. The interviewer wants to see if you can architect solutions that prevent blocking operations from freezing the interface.

    How you'll be scored

    Weak

    Suggests basic setTimeout without understanding the underlying issues or React-specific considerations.

    Average

    Mentions web workers or async patterns but lacks implementation details or trade-off awareness.

    Strong

    Demonstrates multiple approaches with code examples, explains when to use each, and addresses React state updates from background tasks.

    How to structure your answer

    1. Explain why long-running tasks block the UI in JavaScript.
    2. Present web workers as the primary solution for CPU-intensive tasks.
    3. Show how to handle async operations with proper loading states.
    4. Discuss React-specific patterns like useTransition for concurrent features.
    5. Address data synchronization between workers and React state.

    Key points to hit

    • Use web workers for CPU-intensive tasks to move computation off the main thread.
    • Implement proper loading states and progress indicators for better UX during async operations.
    • Break large synchronous operations into smaller chunks using requestIdleCallback or setTimeout.
    • Leverage React 18's useTransition and useDeferredValue for non-urgent updates.

    Common mistakes

    • Using setTimeout for everything without understanding it still blocks the main thread during execution.
    • Forgetting to handle cleanup when components unmount during long-running operations.

    Sample answer

    Long-running tasks block React's UI because JavaScript is single-threaded. For CPU-intensive work like data processing, I use web workers to move computation off the main thread, then postMessage results back to update React state. For network requests, I implement proper loading states with useState and show progress indicators.

    In React 18, I also use useTransition to mark expensive state updates as non-urgent, letting React prioritize user interactions. The key is never letting synchronous operations run longer than 16ms without yielding control back to the browser.

    How to level up

    • Use requestIdleCallback to perform work during browser idle time, with setTimeout fallback for older browsers.
    • Consider libraries like Comlink to make web worker communication feel more natural with async/await.
    • Implement proper error boundaries and retry logic for long-running operations that might fail partway through.

    Follow-up questions to expect

    • How would you handle a web worker that needs to access React context or state?
    • What's the difference between useTransition and useDeferredValue?
    • How do you test components that use web workers?
    Practice this question with AI feedback →

    Next.js / Framework Questions (8)

    What is Next.js and what are its major features?
    medium

    What they're really asking

    This tests your knowledge of the React ecosystem beyond the core library. The interviewer wants to see if you understand Next.js as a production framework and can articulate its value proposition.

    How you'll be scored

    Weak

    Vague description like 'it makes React easier' without mentioning specific features.

    Average

    Lists main features like SSR and file-based routing but lacks depth on implementation details.

    Strong

    Explains core features with examples, discusses performance benefits, and shows understanding of build-time vs runtime optimizations.

    How to structure your answer

    1. Define Next.js as a production React framework.
    2. Explain server-side rendering and static site generation capabilities.
    3. Cover file-based routing and API routes.
    4. Discuss built-in optimizations like image optimization and code splitting.
    5. Mention deployment and performance features.

    Key points to hit

    • Next.js provides server-side rendering and static site generation out of the box for better SEO and initial load times.
    • File-based routing eliminates the need for separate routing configuration.
    • Built-in API routes let you create backend endpoints alongside your React components.
    • Automatic code splitting and optimizations like next/image improve performance without configuration.

    Common mistakes

    • Confusing SSR with SSG or not understanding when to use each rendering method.
    • Thinking Next.js is only for static sites when it supports full-stack applications.

    Sample answer

    Next.js is a production-ready React framework that adds server-side rendering, static site generation, and file-based routing. Instead of configuring webpack and routing yourself, you just create files in the pages directory and Next.js handles the rest.

    It pre-renders pages on the server for better SEO and faster initial loads, then hydrates them with React on the client. The framework also includes API routes for building full-stack apps, automatic code splitting per page, and optimizations like the Image component that handles responsive images and lazy loading automatically.

    How to level up

    • Understand the difference between getStaticProps, getServerSideProps, and getInitialProps for different data fetching scenarios.
    • Use Next.js middleware for authentication, redirects, and request modification before pages render.
    • Leverage incremental static regeneration to combine static generation benefits with dynamic content updates.

    Follow-up questions to expect

    • When would you choose getStaticProps vs getServerSideProps?
    • How does Next.js handle code splitting compared to a standard React app?
    • What are the trade-offs between SSR and client-side rendering?
    Practice this question with AI feedback →
    What are the differences between the Pages Router and App Router in Next.js?
    hard

    What they're really asking

    This tests your understanding of Next.js's architectural evolution and ability to choose between routing paradigms. The interviewer wants to see if you can navigate the framework's current transition period.

    How you'll be scored

    Weak

    Confuses the two routers or provides incorrect information about their capabilities.

    Average

    Correctly identifies basic differences like file location but misses key architectural distinctions.

    Strong

    Explains architectural differences, migration considerations, and can recommend which to use based on project requirements.

    How to structure your answer

    1. Explain that Pages Router is the legacy system, App Router is the new default.
    2. Compare file structure and routing conventions.
    3. Discuss rendering differences and React Server Components.
    4. Cover data fetching pattern changes.
    5. Address migration strategy and when to use each.

    Key points to hit

    • Pages Router uses the pages directory with file-based routing, while App Router uses the app directory with nested layouts.
    • App Router introduces React Server Components by default, enabling server-side logic without API routes.
    • Data fetching moved from getStaticProps/getServerSideProps to async server components and the fetch API.
    • App Router provides better nested layouts and loading states with less boilerplate.

    Common mistakes

    • Assuming you must migrate existing Pages Router apps immediately when App Router is stable for new projects.
    • Not understanding that App Router components are server components by default, requiring 'use client' for interactivity.

    Sample answer

    The Pages Router is Next.js's original system using the pages directory, where each file becomes a route. The newer App Router uses the app directory with nested folder structures that map to URL segments.

    The biggest difference is that App Router uses React Server Components by default, letting you run server-side code directly in components instead of using getServerSideProps. App Router also has better support for nested layouts and streaming, but requires adding 'use client' to components that need browser APIs.

    For new projects, I'd choose App Router, but Pages Router is still fully supported and better for teams not ready for the server component paradigm.

    How to level up

    • Use App Router's loading.js and error.js files to create better UX with granular loading and error states.
    • Understand that App Router enables partial pre-rendering and streaming by default for better performance.
    • Consider the learning curve: App Router requires understanding server vs client components, which can confuse teams new to the concept.

    Follow-up questions to expect

    • How do you handle client-side state management with React Server Components?
    • What's the migration path from Pages Router to App Router?
    • When would you still choose Pages Router for a new project?
    Practice this question with AI feedback →
    How do you implement routing in Next.js vs React Router?
    medium

    What they're really asking

    This tests your understanding of different routing philosophies and ability to choose appropriate tools. The interviewer wants to see if you understand the trade-offs between client-side and file-based routing.

    How you'll be scored

    Weak

    Confuses client-side and server-side routing or provides incorrect implementation details.

    Average

    Shows basic understanding but lacks depth on configuration differences and use case scenarios.

    Strong

    Demonstrates clear understanding of both approaches, explains configuration differences, and can recommend based on project needs.

    How to structure your answer

    1. Explain that Next.js uses file-based routing while React Router is programmatic.
    2. Show configuration examples for both approaches.
    3. Compare dynamic routing syntax and parameter handling.
    4. Discuss nested routing and layout patterns.
    5. Address when to choose each approach.

    Key points to hit

    • Next.js routing is file-based: create a file in pages or app directory and it becomes a route automatically.
    • React Router requires explicit route configuration with components like BrowserRouter and Route.
    • Dynamic routes use [param] syntax in Next.js vs :param in React Router.
    • Next.js provides built-in optimizations like prefetching and code splitting per route.

    Common mistakes

    • Thinking you can use React Router with Next.js for client-side routing when Next.js handles routing internally.
    • Not understanding that Next.js routing works with SSR while React Router is purely client-side.

    Sample answer

    Next.js uses file-based routing where creating pages/about.js automatically creates an /about route, while React Router requires explicit configuration with Route components and path props. For dynamic routes, Next.js uses bracket syntax like [id].js, while React Router uses colon syntax like path=':id'.

    Next.js automatically code-splits by route and can prefetch linked pages, while React Router requires manual configuration for these optimizations. I'd use Next.js routing for full-stack apps that need SSR, and React Router for client-only SPAs where I need more programmatic control over route logic.

    How to level up

    • Next.js supports catch-all routes with [...slug].js syntax for flexible URL structures.
    • Use Next.js's useRouter hook for programmatic navigation, which works with both SSR and client-side routing.
    • React Router v6 introduced data loading patterns that compete with Next.js, but still lack SSR capabilities.

    Follow-up questions to expect

    • How do you handle protected routes in Next.js vs React Router?
    • What's the difference between shallow routing and normal routing in Next.js?
    • How do you implement nested layouts in both systems?
    Practice this question with AI feedback →
    How do you localize React applications?
    medium

    What they're really asking

    This tests your experience with internationalization and ability to handle complex user experience requirements. The interviewer wants to see if you can implement localization beyond just translating text.

    How you'll be scored

    Weak

    Suggests basic string replacement or hardcoded language switching without proper i18n structure.

    Average

    Mentions i18n libraries but lacks implementation details or doesn't address routing and formatting.

    Strong

    Shows comprehensive understanding including text translation, date/number formatting, RTL support, and SEO considerations.

    How to structure your answer

    1. Choose an internationalization library like react-i18next or next-i18next.
    2. Set up translation files and namespace organization.
    3. Implement language switching with proper routing.
    4. Handle locale-specific formatting for dates, numbers, and currency.
    5. Address RTL languages and SEO considerations.

    Key points to hit

    • Use established libraries like react-i18next rather than building custom translation systems.
    • Organize translations in namespaced JSON files by feature or page for maintainability.
    • Implement proper locale routing that works with SSR and is SEO-friendly.
    • Handle locale-specific formatting with Intl API for dates, numbers, and currencies beyond just text translation.

    Common mistakes

    • Only translating visible text while ignoring alt text, meta tags, and accessibility labels.
    • Hardcoding layout assumptions that break with RTL languages or longer translated text.

    Sample answer

    I typically use react-i18next for localization, organizing translations into JSON files by feature like common.json for shared terms and dashboard.json for page-specific content. I set up language detection from URL, localStorage, or browser settings, and use the useTranslation hook for text.

    Beyond translation, I use the Intl API for formatting dates and currencies properly for each locale, and test with longer German text and RTL Arabic to ensure layouts don't break. For SEO, I implement proper hreflang tags and locale-specific URLs, either with subdomains or path prefixes like /en/about and /de/about.

    How to level up

    • Implement translation loading strategies: bundle common translations and lazy-load page-specific ones to reduce initial bundle size.
    • Use interpolation carefully with proper pluralization rules, as some languages have complex plural forms beyond singular/plural.
    • Set up automated translation validation to catch missing keys and ensure all UI text is translatable before deployment.

    Follow-up questions to expect

    • How do you handle translations for dynamic content from APIs?
    • What's your strategy for managing translator workflows and updating translation files?
    • How do you test your app with different locales during development?
    Practice this question with AI feedback →
    How do you handle data persistence in a React application?
    medium

    What they're really asking

    This tests your understanding of data persistence strategies in React applications and whether you can choose appropriate persistence mechanisms based on data sensitivity, lifespan, and synchronization needs.

    How you'll be scored

    Weak

    Only mentions localStorage without considering security, data types, or synchronization with server state.

    Average

    Lists multiple persistence options like localStorage and sessionStorage with basic understanding of when to use each.

    Strong

    Demonstrates understanding of different persistence layers, security considerations, and how to synchronize client-side persistence with server state.

    How to structure your answer

    1. Categorize persistence needs: temporary vs permanent, sensitive vs non-sensitive.
    2. List browser storage options with use cases.
    3. Explain server-side persistence integration.
    4. Address security and synchronization considerations.

    Key points to hit

    • Use localStorage for non-sensitive data that should persist across sessions, sessionStorage for temporary data within a session.
    • Never store sensitive data like tokens in localStorage; use httpOnly cookies or secure session storage.
    • Implement proper synchronization between client-side cache and server state using libraries like React Query or SWR.
    • Consider IndexedDB for complex data structures or large datasets that need client-side querying.

    Common mistakes

    • Storing authentication tokens or sensitive user data in localStorage where XSS attacks can access them.
    • Not handling storage quota exceeded errors or assuming localStorage is always available.

    Sample answer

    I approach data persistence by first categorizing what needs to be stored. For user preferences like theme or language settings, I use localStorage since it persists across browser sessions. For temporary data like form drafts, sessionStorage works well since it clears when the tab closes.

    For authentication, I never put tokens in localStorage due to XSS risks - I prefer httpOnly cookies or work with the backend team to implement secure session management. For complex application data, I use React Query to handle server state synchronization, which gives me caching, background updates, and offline support.

    If I need to store large amounts of structured data client-side, like for a progressive web app, I'll use IndexedDB with a library like Dexie.

    How to level up

    • Implement storage event listeners to sync data across multiple tabs of the same application.
    • Use React Query or SWR for server state management rather than trying to manually sync localStorage with API calls.
    • Consider implementing a storage abstraction layer that can gracefully fallback when storage APIs are unavailable.

    Follow-up questions to expect

    • How would you handle storage quota exceeded errors?
    • What's your strategy for migrating data when your storage schema changes?
    • How do you sync data across multiple browser tabs?
    Practice this question with AI feedback →
    What are common folder structures for React projects?
    medium

    What they're really asking

    This tests whether you understand how to organize React codebases for maintainability and can make architectural decisions that scale with team size and project complexity.

    How you'll be scored

    Weak

    Mentions basic folders like components and pages without explaining organization principles or reasoning.

    Average

    Describes a coherent folder structure with separation of concerns but lacks depth on scaling considerations.

    Strong

    Explains multiple organizational approaches, when to use each, and how folder structure impacts developer experience and maintainability.

    How to structure your answer

    1. Present feature-based vs type-based organization approaches.
    2. Explain folder hierarchy with specific examples.
    3. Discuss how structure changes with project scale.
    4. Address team collaboration and developer experience.

    Key points to hit

    • Feature-based organization groups related components, hooks, and utilities together, making features easier to maintain and potentially extract.
    • Type-based organization separates by file type but can become unwieldy as projects grow beyond simple applications.
    • Keep shared utilities, components, and hooks in clearly defined common areas with index files for clean imports.
    • Use consistent naming conventions and co-locate tests with their corresponding components for better developer experience.

    Common mistakes

    • Creating overly deep folder nesting that makes imports cumbersome and navigation difficult.
    • Mixing feature-specific and shared components in the same directories without clear separation.

    Sample answer

    I prefer feature-based organization for most projects because it keeps related code together. I'll have a src/features directory where each feature like 'user-profile' or 'product-catalog' contains its components, hooks, and utilities. I keep a src/shared directory for truly reusable components, custom hooks, and utilities used across features.

    My typical structure includes src/components for shared UI components, src/hooks for custom hooks, src/utils for pure functions, and src/services for API calls. I co-locate test files with their components using .test.js extensions and use index.js files to create clean import paths.

    For smaller projects, I might start with type-based organization but refactor to feature-based as complexity grows.

    How to level up

    • Use path mapping in your bundler to create clean import aliases like '@/components' instead of relative paths.
    • Consider creating a components library structure with proper documentation if you're building design system components.
    • Implement barrel exports strategically to avoid circular dependencies while maintaining clean import paths.

    Follow-up questions to expect

    • How do you handle shared components that are used by multiple features?
    • What's your approach to organizing utility functions and custom hooks?
    • How would you structure a monorepo with multiple React applications?
    Practice this question with AI feedback →
    How do you ensure a user remains authenticated on page refresh using Context API?
    medium

    What they're really asking

    This tests your understanding of authentication state management and whether you can implement secure, persistent authentication flows that handle edge cases like token expiration and storage security.

    How you'll be scored

    Weak

    Suggests storing tokens in Context without considering persistence, security, or refresh scenarios.

    Average

    Implements basic Context-based auth with localStorage but doesn't address security concerns or token refresh.

    Strong

    Demonstrates secure authentication patterns with proper token storage, automatic refresh handling, and graceful error states.

    How to structure your answer

    1. Create AuthContext with authentication state and methods.
    2. Implement secure token storage strategy.
    3. Handle token validation and refresh on app initialization.
    4. Provide loading states and error handling for auth operations.

    Key points to hit

    • Store authentication tokens securely using httpOnly cookies or encrypted storage, never in plain localStorage.
    • Implement token validation in your AuthContext's initialization to check if stored tokens are still valid.
    • Use a loading state while checking authentication status to prevent flash of unauthenticated content.
    • Handle token refresh automatically in the background and provide logout functionality when refresh fails.

    Common mistakes

    • Storing JWT tokens in localStorage where they're vulnerable to XSS attacks.
    • Not handling the loading state during authentication check, causing UI flicker between authenticated and unauthenticated states.

    Sample answer

    I create an AuthContext that manages authentication state and provides login, logout, and token refresh methods. On app initialization, I check for existing authentication by validating stored tokens - I prefer httpOnly cookies but if I must use client storage, I encrypt the tokens first.

    The AuthProvider includes a loading state that prevents rendering the app until authentication status is determined, avoiding the flash of login screen for authenticated users. I implement automatic token refresh using axios interceptors or React Query, and if refresh fails, I automatically log the user out and redirect to login.

    The context also provides user information and methods that components can use to check authentication status and permissions.

    How to level up

    • Implement token refresh in HTTP interceptors to handle expired tokens automatically across all API calls.
    • Use React Query's or SWR's error handling to globally manage authentication failures and automatic logout.
    • Consider implementing role-based access control in your AuthContext to handle different user permission levels.

    Follow-up questions to expect

    • How do you handle concurrent requests when a token expires?
    • What's your strategy for handling different user roles and permissions?
    • How would you implement automatic logout when a user is inactive for too long?
    Practice this question with AI feedback →
    What is the difference between React Native and React?
    easy

    What they're really asking

    This tests your understanding of React's ecosystem and whether you can clearly explain the relationship between React's core library and its platform-specific implementations.

    How you'll be scored

    Weak

    States that React Native is for mobile without explaining the underlying architectural differences or shared concepts.

    Average

    Correctly identifies that React Native targets mobile while React targets web browsers with different rendering approaches.

    Strong

    Explains the shared component model and reconciliation while clearly distinguishing rendering targets, performance characteristics, and development workflows.

    How to structure your answer

    1. Explain React as a general UI library with reconciliation engine.
    2. Distinguish rendering targets: DOM vs native components.
    3. Compare development workflows and tooling differences.
    4. Highlight shared concepts and transferable knowledge.

    Key points to hit

    • React is the core library that handles component logic, state management, and the reconciliation algorithm, while React DOM and React Native are different renderers.
    • React renders to browser DOM elements like div and span, while React Native renders to platform-specific native components like View and Text.
    • Both share the same component lifecycle, hooks, and state management patterns, making knowledge highly transferable between platforms.
    • React Native requires platform-specific tooling like Metro bundler and device simulators, while React uses standard web development tools.

    Common mistakes

    • Thinking React Native just wraps web components in a mobile container rather than understanding it renders to truly native components.
    • Assuming all React libraries and components work directly in React Native without considering platform-specific implementations.

    Sample answer

    React is the core library that provides the component model, hooks, and reconciliation algorithm, while React and React Native are different renderers for that core. React renders to DOM elements in web browsers using divs, spans, and standard HTML elements.

    React Native renders to native mobile components like UIView on iOS and ViewGroup on Android, giving you truly native performance and feel. The component logic, state management with useState and useEffect, and overall development patterns are identical between both platforms.

    However, React Native has its own set of components like View instead of div, Text instead of span, and requires platform-specific tooling like Metro bundler and Xcode or Android Studio for device deployment.

    How to level up

    • Learn React Native's Flexbox implementation which differs slightly from web CSS Flexbox in default values and behavior.
    • Understand platform-specific code splitting in React Native using .ios.js and .android.js file extensions.
    • Explore React Native's bridge architecture and how it's evolving with the new architecture using JSI and Fabric.

    Follow-up questions to expect

    • What are the main styling differences between React and React Native?
    • How would you share business logic between a React web app and React Native mobile app?
    • What are the performance considerations unique to React Native compared to web React?
    Practice this question with AI feedback →

    Frequently Asked Questions

    What React topics should I study for interviews?
    Focus on hooks (useState, useEffect, useRef, useMemo, useCallback), component lifecycle, state management patterns, the virtual DOM, and performance optimization. Senior-level interviews also cover React Server Components, concurrent features, custom hook design, and frontend system design using React.
    Do React interviews include coding challenges?
    Yes. Most React interviews include a live coding round where you build a small component or feature. Common tasks include a search with debounce, a todo list with filtering, or a data fetching component with loading and error states. Practice building components from scratch without relying on boilerplate or IDE autocompletion.
    How important is understanding React internals for interviews?
    For junior and mid-level roles, understanding the virtual DOM, reconciliation, and the rules of hooks is usually enough. Senior roles expect knowledge of React Fiber, the diffing algorithm, concurrent rendering, and how React batches state updates. You do not need to read the source code, but you should be able to explain why React works the way it does.
    Should I learn class components for interviews?
    Understand them enough to read and migrate existing code, but focus your preparation on hooks for new code. Most companies have moved to functional components, and interviewers primarily test hooks-based patterns. That said, error boundaries still require class components, so know how those work.
    How important is knowing Redux for React interviews?
    Less critical than it used to be. Many companies now use lighter alternatives like Zustand, Jotai, or React Query. What matters more is understanding the pattern: unidirectional data flow, actions, reducers, and selectors. If you understand the concept, you can pick up any specific library quickly. Check the job description for signals about which tools the team uses.
    Do I need to know Next.js?
    It depends on the role. Full-stack React positions increasingly expect Next.js experience. For frontend-only roles, you should at minimum understand SSR concepts, static generation, and hydration. If the job listing mentions Next.js, spend time building something with it. If it does not, conceptual knowledge is usually sufficient.
    How do I practice React interview questions?
    Build small projects that exercise specific concepts: a debounced search, a data table with sorting and pagination, a multi-step form with validation. Then practice explaining your decisions out loud. Reading code is not enough. You need to articulate your reasoning clearly under time pressure. AI mock interviews help you practice both building and explaining.
    What React version should I study?
    Focus on React 18+ features: concurrent rendering, automatic batching, transitions with useTransition, and Suspense for data fetching. Interviewers care about current patterns, not legacy APIs. If a company is still on React 16 or 17, understanding the upgrade path shows initiative and awareness of the ecosystem.

    Stop Preparing in Your Head. Start Practicing Out Loud.

    Drop your resume, add a job description, and get a mock interview like the real thing.

    Start Free Mock Interview →
    No credit card required. 5 free credits to start.

    Still applying for jobs? Let Auto Apply do it for you.

    Try Auto Apply →