Blog

React.js Interview Questions: From Junior to Principal Engineer (2026)

By Ahsan Hafeez · 2026-11-10

Whether you are preparing for your first React role or a principal engineer interview, this post covers the questions that actually come up. Organized by seniority level so you can focus on what matters for your target role.

Core Foundations

Q: What is the Virtual DOM and how does React's diffing algorithm work?

The Virtual DOM is a lightweight JavaScript object tree that mirrors the real DOM. When state changes, React builds a new virtual tree and compares it with the previous one using a diffing algorithm. It compares nodes level by level (breadth-first), and if a node type changes, React tears down the entire subtree and rebuilds it. Same-type elements get their attributes patched in place.

Q: What is reconciliation in React?

Reconciliation is the process React uses to determine what changed between two renders. React compares the old and new virtual DOM trees, computes the minimal set of DOM operations needed, and applies them in a batch. This is what makes React fast: instead of re-rendering the entire page, it only touches the nodes that actually changed.

Q: What is Fiber architecture and why was it introduced?

Fiber is React's internal reconciliation engine introduced in React 16. It replaced the old synchronous stack-based reconciler with an incremental one that can pause, resume, and prioritize work. This lets React split rendering into chunks so the main thread stays responsive during heavy updates. Each fiber node is a unit of work that tracks its own state, parent, child, and sibling references.

Q: How does React batch state updates?

React groups multiple setState calls within the same event handler into a single re-render for performance. Since React 18, automatic batching extends this to promises, setTimeout, and native event handlers as well. If you need to force a synchronous update, you can wrap it in flushSync. Batching reduces unnecessary renders and keeps the UI consistent.

Q: What are synthetic events in React?

Synthetic events are React's cross-browser wrapper around native DOM events. They follow the W3C spec and normalize behavior across browsers so you do not have to worry about inconsistencies. Synthetic events are pooled for performance in React 16 and earlier, but pooling was removed in React 17. They bubble through the React tree, not the DOM tree.

Q: Describe the React component lifecycle: mount, update, unmount.

On mount, React creates the component instance, runs the render, commits to the DOM, then fires useEffect (or componentDidMount). On update, a state or prop change triggers a re-render, DOM diff, commit, and useEffect cleanup followed by the new effect. On unmount, React runs useEffect cleanup functions (or componentWillUnmount) and removes the component from the DOM.

Q: What is the difference between Shadow DOM and Virtual DOM?

They solve completely different problems. Shadow DOM is a browser API for encapsulating DOM and CSS inside a component (used by Web Components) so styles do not leak in or out. Virtual DOM is a programming concept where a virtual representation of the UI is kept in memory and synced with the real DOM through reconciliation. React uses Virtual DOM; it does not use Shadow DOM.

Q: Why are keys important in lists, and why is using index as a key problematic?

Keys help React identify which items changed, were added, or removed during reconciliation. Using array index as a key breaks when items are reordered, inserted, or deleted because React maps the wrong state to the wrong element. For example, if you delete the first item, every subsequent item gets the previous item's state. Always use a stable, unique identifier like a database ID.

Q: What is unidirectional data flow in React?

Data in React flows in one direction: from parent to child via props. A child cannot directly modify its parent's state. Instead, the parent passes down a callback function, and the child calls it to request a state change. This makes data flow predictable and debugging easier because you can trace any state change back to its source.

Junior Level

Q: When would you use useState vs useReducer?

Use useState for simple, independent pieces of state like a toggle or input value. Switch to useReducer when state logic is complex, involves multiple sub-values, or when the next state depends on the previous one. useReducer also helps when you want to pass dispatch down to deeply nested components instead of multiple callbacks.

Q: Why is useEffect cleanup important and when does it run?

The cleanup function returned from useEffect runs before the component unmounts and before the effect re-runs on subsequent renders. It prevents memory leaks by letting you unsubscribe from events, cancel timers, or abort network requests. Without cleanup, you get stale closures, dangling subscriptions, and state updates on unmounted components.

Q: What are common conditional rendering patterns in React?

The three main patterns are: ternary operator for if/else (condition ? <A/> : <B/>), logical AND for show/hide (condition && <A/>), and early return for guard clauses. Watch out for the AND pattern with numbers: count && <Component/> renders "0" instead of nothing when count is 0. Use count > 0 && <Component/> instead.

Q: What is the difference between controlled and uncontrolled components?

A controlled component has its value managed by React state. Every keystroke triggers a state update, and the input always reflects the state. An uncontrolled component manages its own value internally through the DOM, and you read it with a ref when needed. Controlled components give you more control for validation and formatting but require more code.

Q: What is the difference between props and state?

Props are read-only data passed from parent to child. State is mutable data owned and managed by the component itself. When props or state change, the component re-renders. A good rule: if a component needs to track something that changes over time and no parent is passing it down, it belongs in state.

Q: What does "lifting state up" mean?

When two sibling components need to share the same data, you move that state to their closest common parent. The parent holds the state and passes it down as props to both children. This is React's answer to shared state without external libraries. It keeps data flow unidirectional and avoids out-of-sync UI.

Q: Why use React.Fragment instead of a wrapper div?

React.Fragment lets you group multiple elements without adding an extra DOM node. Extra divs can break CSS layouts (especially flexbox and grid), add unnecessary nesting, and hurt accessibility. The shorthand syntax <>...</> works the same way but does not support the key prop. Use the full <Fragment key={id}> form inside maps.

Q: How does event handling in React differ from vanilla JavaScript?

React uses camelCase for event names (onClick, not onclick) and passes functions, not strings. Events are delegated to the root element rather than attached to individual DOM nodes. React's synthetic event system normalizes cross-browser differences. You call e.preventDefault() explicitly since returning false does not prevent default behavior.

Q: What happens when JSX gets compiled?

JSX is syntactic sugar that gets transformed into React.createElement() calls (or the new JSX transform's jsx() function). <div className="box">Hello</div> becomes jsx("div", { className: "box", children: "Hello" }). This is why you needed to import React in every file before React 17. The new transform handles the import automatically.

Mid Level

Q: When should you use useCallback, useMemo, and React.memo?

React.memo is a higher-order component that skips re-rendering when props have not changed (shallow comparison). useMemo caches the result of an expensive computation between renders. useCallback caches a function reference so it does not break React.memo on child components. Do not use them everywhere: they add memory overhead and complexity. Profile first, optimize second.

Q: What makes a good custom hook?

A custom hook extracts reusable stateful logic into a function prefixed with "use". Good custom hooks do one thing well, return a clean API, and handle their own cleanup. They should not contain UI logic or JSX. Examples: useDebounce, useFetch, useLocalStorage, useMediaQuery.

Q: What are the performance pitfalls of React Context?

Every component that consumes a context re-renders when the context value changes, even if it only uses a small part of the value. Putting unrelated state in the same context causes unnecessary renders across the tree. Split contexts by update frequency, memoize the provider value, or use a state management library for high-frequency updates.

Q: How do error boundaries work in React?

Error boundaries are class components that catch JavaScript errors in their child component tree during rendering, lifecycle methods, and constructors. They use componentDidCatch for logging and getDerivedStateFromError to show a fallback UI. They do not catch errors in event handlers, async code, or server-side rendering. You typically wrap route-level or feature-level sections with them.

Q: How does code splitting with React.lazy and Suspense work?

React.lazy takes a function that returns a dynamic import and creates a component that loads the module on demand. Suspense wraps lazy components and shows a fallback (like a spinner) while the chunk loads. This reduces your initial bundle size by splitting code at route or feature boundaries. Combine it with route-based splitting for the biggest impact.

Q: What is React.forwardRef and when do you need it?

forwardRef lets a parent component pass a ref through to a child's DOM element. By default, refs do not pass through function components because they do not have instances. This is essential for reusable component libraries where consumers need direct DOM access for focus management, measurements, or animations.

Q: What does useImperativeHandle do?

useImperativeHandle customizes the value exposed to parent components when using forwardRef. Instead of exposing the entire DOM node, you expose a limited API with specific methods like focus() or scrollTo(). This provides encapsulation: the parent gets only what it needs, and you can change the internal implementation without breaking consumers.

Q: When would you use React Portals?

Portals render children into a DOM node that exists outside the parent component's DOM hierarchy. Common use cases are modals, tooltips, and dropdown menus that need to break out of overflow:hidden or z-index stacking contexts. Events still bubble through the React tree, not the DOM tree, so the parent can still handle events from the portal.

Q: Compare render props, HOCs, and custom hooks. Which should you use?

Custom hooks are the modern standard for sharing stateful logic. They compose cleanly, avoid wrapper hell, and work with TypeScript without type gymnastics. HOCs still show up in older codebases (withRouter, connect) but create naming collisions and prop-drilling confusion. Render props remain useful for specific UI delegation patterns but are largely replaced by hooks for logic reuse.

Senior Level

Q: Explain concurrent rendering and startTransition.

Concurrent rendering lets React prepare multiple UI versions simultaneously without blocking the main thread. startTransition marks a state update as non-urgent so React can interrupt it to handle user input. This keeps typing, clicking, and scrolling responsive even during heavy renders. The useTransition hook also gives you an isPending flag to show loading indicators.

Q: What is the difference between server components and client components?

Server components run only on the server: they can access databases and file systems directly, and they send zero JavaScript to the client. Client components run in the browser and handle interactivity, state, and effects. Server components cannot use useState, useEffect, or event handlers. You mark a file with "use client" to make it a client component.

Q: How does streaming SSR work?

Streaming SSR sends HTML to the browser in chunks as components render on the server, instead of waiting for the entire page. React's renderToPipeableStream supports Suspense boundaries: content inside a Suspense boundary streams in when it is ready, and the browser shows the fallback until then. This improves Time to First Byte and perceived load time.

Q: How do you choose the right state management solution?

Local useState handles component-specific state. Context works for low-frequency shared state like theme or auth. For complex client state with frequent updates, use Zustand or Redux Toolkit. Server state (API data) belongs in React Query or SWR, which handle caching, revalidation, and deduplication. Do not put server state in Redux: you end up reimplementing a cache poorly.

Q: What does a solid React testing strategy look like?

Unit test pure logic (utils, reducers, hooks) with fast tests. Integration test components with React Testing Library, focusing on user behavior, not implementation details. E2E test critical flows (login, checkout, onboarding) with Playwright or Cypress. Avoid testing implementation details like state values or internal method calls. Aim for high integration test coverage since they catch the most real bugs.

Q: How do you architect a design system's component library?

Start with primitive components (Button, Input, Text) that accept variants through props, not custom CSS. Use composition over configuration: a Card component with Card.Header, Card.Body slots beats a Card with 15 props. Enforce constraints through TypeScript types, not documentation. Publish as a versioned package with a changelog so consumers can upgrade safely.

Q: What accessibility patterns should every React app implement?

Manage focus when routes change (announce the new page to screen readers). Use semantic HTML elements before ARIA attributes. Ensure all interactive elements are keyboard accessible. Implement skip navigation links. Test with a screen reader and keyboard-only navigation, not just automated tools. Use aria-live regions for dynamic content updates.

Q: How do you profile and optimize React performance?

Use React DevTools Profiler to identify components that render too often or take too long. Check the flamegraph for hot paths. Common fixes: memoize expensive computations, virtualize long lists with react-window, lazy load below-the-fold content, and debounce rapid state updates. Measure before and after with Web Vitals. Never optimize without profiling first.

Team Lead

Q: How do you establish and enforce frontend architecture standards?

Define standards in a living architecture document covering folder structure, component patterns, state management boundaries, and naming conventions. Enforce them through ESLint rules, custom lint plugins, and PR templates. Automate what you can so code reviews focus on logic, not formatting. Run architecture decision records (ADRs) for significant changes so the team understands the why.

Q: What should a React PR code review checklist cover?

Check for: proper error handling and loading states, accessibility basics (keyboard nav, labels), no unnecessary re-renders (correct memo/callback usage), proper TypeScript types (no "any" escapes), test coverage for new behavior, no hardcoded strings that should be constants, clean component boundaries, and no premature abstractions. Review the user experience, not just the code.

Q: How do you migrate a large codebase from class components to hooks?

Do not rewrite everything at once. Migrate incrementally: new code uses hooks, and you convert class components when you touch them for a feature or bug fix. Start with the simplest components (no lifecycle complexity) to build team confidence. Write tests before migrating so you catch regressions. Set up a lint rule that warns on new class components.

Q: How do you manage bundle size across multiple teams?

Set a bundle budget in CI that fails the build if the total or per-route size exceeds the limit. Use tools like bundleanalyzer or source-map-explorer to visualize what each team ships. Share common dependencies through a shared chunk. Audit imports regularly: a single import _ from 'lodash' can add 70KB. Prefer tree-shakeable ESM packages.

Q: How do you build a testing culture in a React team?

Make testing part of the definition of done, not a separate task. Start with integration tests that test user behavior because they provide the most confidence per effort. Set up CI to report coverage changes on every PR. Pair with engineers who are less comfortable with testing. Celebrate catching bugs in tests before production. Never let flaky tests stay: fix or remove them immediately.

Q: What is your strategy for upgrading React across a large codebase?

Read the migration guide and changelog thoroughly. Run codemods first (React provides official ones for most major versions). Upgrade in a feature branch and run the full test suite. Use StrictMode to catch deprecation warnings early. For breaking changes, create a wrapper or compatibility layer and migrate consumers incrementally. Communicate the timeline and breaking changes to all teams early.

Principal Engineer

Q: How would you design a micro-frontend architecture with React?

Use Module Federation (webpack) or importmap-based federation to let teams deploy independently. Each micro-frontend owns a route or feature and ships its own bundle. Share React and the design system as singleton dependencies to avoid version conflicts. Define clear contracts for cross-app communication (custom events or a shared event bus). The tradeoff is operational complexity for team autonomy.

Q: How do you optimize the build system for a large React monorepo?

Use Turborepo or Nx for task orchestration with remote caching so unchanged packages skip rebuilding. Migrate from webpack to Vite for faster dev server starts (native ESM, no bundling in dev). Configure SWC or esbuild as the compiler instead of Babel. Set up incremental TypeScript builds with project references. Parallelize CI across packages and cache aggressively.

Q: How do you choose between Next.js and Remix for a full-stack React project?

Next.js suits content-heavy sites with its mature SSG/ISR support, image optimization, and Vercel deployment story. Remix shines for highly interactive apps with nested layouts, optimistic UI, and progressive enhancement through its loader/action model. Both support SSR and RSC. Choose based on your deployment target, team familiarity, and whether your app is more content-driven or interaction-driven.

Q: How do you decide which rendering strategy (CSR, SSR, SSG, ISR) to use per page?

Static pages (marketing, docs, blog) get SSG for best performance and cacheability. Dynamic pages with SEO needs (product pages, profiles) get SSR or ISR. Highly interactive dashboards behind auth get CSR since search engines do not need to index them. ISR works for pages that change periodically but do not need real-time data. Mix strategies within the same app based on each page's requirements.

Q: How do you scale React development across 10+ teams?

Build a frontend platform team that owns the build system, shared component library, CI/CD pipeline, and developer tooling. Define module boundaries so teams work in isolation. Use a design system as the single source of truth for UI consistency. Establish RFCs for cross-cutting changes. Run a frontend guild for cross-team knowledge sharing. Invest in developer experience: fast builds, clear docs, and reliable staging environments.

Q: What are the responsibilities of a frontend platform team?

The platform team owns: the build and deploy pipeline, the component library and design system, shared tooling (linters, generators, test utilities), performance monitoring and budgets, dependency management and security patches, and the developer onboarding experience. They do not own product features. Their success metric is how fast product teams can ship quality UI without hitting infrastructure problems.

Rapid Fire: Practical Q&A

Q: Class Components vs Functional Components: what is the difference?

Class components use ES6 classes, extend React.Component, and manage state with this.state and lifecycle methods like componentDidMount. Functional components are plain functions that use hooks for state and side effects. Functional components are shorter, easier to test, and the standard since React 16.8.

Use Case: Migrating legacy class-based codebases to hooks for simpler logic reuse. Real-Time Example: Converting a class-based UserProfile with componentDidMount data fetching into a functional component with useEffect.

Q: What is JSX?

JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. It compiles to React.createElement() (or the jsx() function in React 17+). JSX is not a template language: it has the full power of JavaScript through curly brace expressions.

Use Case: Building declarative UI trees that are easier to read than nested function calls. Real-Time Example: Writing <button onClick={handleSubmit}>Save</button> instead of React.createElement("button", { onClick: handleSubmit }, "Save").

Q: Explain DOM, Virtual DOM, and Shadow DOM. How do diffing and reconciliation fit in?

The DOM is the browser's tree of HTML elements. The Virtual DOM is React's in-memory copy of that tree. When state changes, React builds a new virtual tree, diffs it against the old one (the diffing algorithm), and applies only the changed nodes to the real DOM (reconciliation). Shadow DOM is a separate browser API that encapsulates styles and markup inside Web Components. React does not use Shadow DOM.

Use Case: Understanding why React re-renders are fast despite JavaScript-driven UI updates. Real-Time Example: Updating one item in a 500-row table: React diffs the virtual trees and patches only that single table cell in the real DOM.

Q: Give an overview of React Hooks.

Hooks let functional components use state, side effects, context, and other React features without classes. The core hooks are useState, useEffect, useContext, useRef, useMemo, useCallback, and useReducer. Custom hooks let you extract and reuse stateful logic across components. Rules: only call hooks at the top level, never inside loops or conditionals.

Use Case: Sharing data-fetching logic across multiple components without HOCs or render props. Real-Time Example: A useAuth() custom hook that wraps useContext and returns the current user, login, and logout functions.

Q: What are React lifecycle methods?

Lifecycle methods map to three phases: mounting (constructor, render, componentDidMount), updating (shouldComponentUpdate, render, componentDidUpdate), and unmounting (componentWillUnmount). In functional components, useEffect covers mount and update, and its cleanup function covers unmount. useLayoutEffect runs synchronously after DOM mutations but before the browser paints.

Use Case: Running setup and teardown logic tied to a component's presence in the DOM. Real-Time Example: Starting a WebSocket connection on mount and closing it on unmount to avoid memory leaks.

Q: useCallback vs useMemo: what is the difference?

useMemo caches the return value of a computation so it does not re-run on every render. useCallback caches the function reference itself. useMemo returns a value, useCallback returns a function. Both accept a dependency array and recompute only when dependencies change.

Use Case: Preventing child components wrapped in React.memo from re-rendering due to new function/object references. Real-Time Example: Wrapping an onSort handler in useCallback so a memoized DataTable does not re-render when the parent's unrelated state changes.

Q: useEffect vs useLayoutEffect: when to use which?

useEffect runs asynchronously after the browser paints, so users see the initial render first. useLayoutEffect runs synchronously after DOM mutations but before the paint, blocking the browser until it finishes. Use useLayoutEffect only when you need to measure or mutate the DOM before the user sees it.

Use Case: Preventing a visual flicker when you need to reposition an element based on its measured size. Real-Time Example: Measuring a tooltip's width with useLayoutEffect to flip its position before the browser renders it in the wrong spot.

Q: State vs Props: what is the difference?

State is data owned and managed locally by the component. Props are data passed down from a parent, and they are read-only inside the receiving component. Changing state triggers a re-render of that component. Changing props means the parent re-rendered with new values.

Use Case: Deciding whether a piece of data should live in the component or be controlled by its parent. Real-Time Example: A SearchBar owns its input text as local state, but receives the onSearch callback as a prop from the parent page.

Q: How does setState work under the hood?

setState schedules a state update and tells React to re-render the component. It does not update state immediately: React batches multiple setState calls within the same event handler into one re-render. Since React 18, batching extends to promises, timeouts, and native events too. If you need the previous state value, pass a function: setState(prev => prev + 1).

Use Case: Avoiding stale state bugs when multiple updates depend on the current value. Real-Time Example: A counter button clicked rapidly: using setCount(c => c + 1) instead of setCount(count + 1) so no increments get lost during batching.

Q: How do props and callback functions work together in React?

A parent passes a function as a prop to a child component. The child calls that function (often with data) to communicate back to the parent. This is how React implements child-to-parent communication without breaking unidirectional data flow. The parent owns the state, the child triggers the update.

Use Case: Building reusable form components that notify the parent when values change. Real-Time Example: A ColorPicker component receives an onChange prop and calls onChange("#FF0000") when the user picks red, letting the parent update its theme state.

Contact