🎯 Free Interview Preparation

ReactJS Interview Questions & Answers

Top ReactJS interview questions and answers with practical examples for beginners and experienced developers.

ReactJS Interview Questions & Answers (2026)

Top ReactJS interview questions and answers with practical examples for beginners and experienced developers.

Question #1: What is ReactJS?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

ReactJS is a JavaScript library developed by Meta for building reusable and interactive user interfaces using components.

Practical Example

Applications such as Facebook, Instagram, Netflix, dashboards and admin portals are commonly built using React.

Follow-Up Questions

  • Why React over Angular?
  • What is Virtual DOM?
  • What is JSX?
Interviewer Note: 💡 Strong candidates explain React using real production projects.

Question #2: What is JSX?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

JSX is a syntax extension that allows developers to write HTML-like code inside JavaScript.

Code Example

const element = (
  <h1>Welcome to React</h1>
);

Follow-Up Questions

  • Can React work without JSX?
  • How does Babel process JSX?
  • What does JSX compile into?
Interviewer Note: 💡 Candidates should know JSX is converted into JavaScript.

Question #3: What is a React Component?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

Components are reusable building blocks of React applications. Each component manages a portion of the UI.

Practical Example

  • Navbar Component
  • Sidebar Component
  • Product Card Component
  • User Profile Component

Code Example

function UserCard() {
  return (
    <div>User Profile</div>
  );
}

Follow-Up Questions

  • Functional vs Class Components?
  • What are Props?
  • What is State?

Question #4: Difference Between Props and State?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

Props are data passed from parent components while State is data managed inside a component.

Comparison

Props
  • Read Only
  • Passed by Parent
  • Cannot be modified directly

Comparison

State
  • Mutable
  • Managed by Component
  • Updated using Hooks

Code Example

function User({ name }) {

  const [count, setCount] = useState(0);

  return (
    <div>
      {name}
      {count}
    </div>
  );
}
Interviewer Note: 💡 Every React interview asks Props vs State.

Question #5: What is useState?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

useState is a React Hook used to manage component state inside functional components.

Code Example

import { useState } from 'react';

function Counter() {

  const [count, setCount] = useState(0);

  return (
    <button
      onClick={() => setCount(count + 1)}
    >
      {count}
    </button>
  );
}

Real World Usage

  • Form Inputs
  • Dropdowns
  • Counters
  • Search Filters
  • Modal Visibility

Follow-Up Questions

  • Can useState store objects?
  • Can useState store arrays?
  • What triggers re-rendering?

Question #6: What is useEffect?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

useEffect is a React Hook used to perform side effects such as API calls, subscriptions, timers and DOM manipulation.

Code Example

import { useEffect, useState } from 'react';

function Users() {

  const [users, setUsers] = useState([]);

  useEffect(() => {

    fetch('/api/users')
      .then(res => res.json())
      .then(data => setUsers(data));

  }, []);

  return (
    <div>
      {users.length} Users Loaded
    </div>
  );
}

Real World Usage

  • API Calls
  • Authentication Validation
  • WebSocket Connections
  • Analytics Tracking

Follow-Up Questions

  • What does [] mean?
  • What causes useEffect to re-run?
  • What is a cleanup function?
Interviewer Note: 💡 Strong candidates explain dependency arrays and cleanup functions.

Question #7: What is Virtual DOM?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

Virtual DOM is a lightweight JavaScript representation of the real DOM. React compares changes and updates only affected elements.

Practical Example

When updating a counter from 1 to 2, React updates only the text node instead of re-rendering the entire page.

Interviewer Note: 💡 Most candidates know Virtual DOM but cannot explain reconciliation.

Question #8: What are Keys in React?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

Keys are unique identifiers used by React to track list items efficiently during re-rendering.

Code Example

function UserList() {

  const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'David' }
  ];

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          {user.name}
        </li>
      ))}
    </ul>
  );
}

Common Mistakes

  • Using array index as key
  • Using duplicate keys
  • Using random values as keys

Follow-Up Questions

  • Why should keys be unique?
  • Can we use index as key?
  • How does React use keys internally?
Interviewer Note: 💡 Strong candidates explain how keys help React's reconciliation process.

Question #9: Controlled vs Uncontrolled Components

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

Controlled components use React state to manage form values. Uncontrolled components rely on the DOM to manage form values.

Controlled Component Example

import { useState } from 'react';

function LoginForm() {

  const [email, setEmail] = useState('');

  return (
    <input
      value={email}
      onChange={(e) => setEmail(e.target.value)}
    />
  );
}

Uncontrolled Component Example

import { useRef } from 'react';

function LoginForm() {

  const emailRef = useRef();

  const submit = () => {
    console.log(emailRef.current.value);
  };

  return (
    <>
      <input ref={emailRef} />
      <button onClick={submit}>
        Submit
      </button>
    </>
  );
}

When To Use?

  • Controlled → Most React Forms
  • Uncontrolled → Simple Forms & Third Party Libraries
Interviewer Note: 💡 Most enterprise applications prefer controlled components.

Question #10: What is React Router?

Level: Junior | Category: Fundamentals | Time: 8 mins

Expected Answer

React Router is a routing library that enables navigation between pages in React applications without full page reloads.

Code Example

import {
  BrowserRouter,
  Routes,
  Route
} from 'react-router-dom';

function App() {

  return (
    <BrowserRouter>

      <Routes>

        <Route
          path='/'
          element={<Home />}
        />

        <Route
          path='/users'
          element={<Users />}
        />

      </Routes>

    </BrowserRouter>
  );
}

Real World Usage

  • Dashboard Navigation
  • E-Commerce Websites
  • Admin Portals
  • CRM Applications

Follow-Up Questions

  • What is BrowserRouter?
  • What is useNavigate?
  • Difference between Link and Anchor Tag?
Interviewer Note: 💡 Candidates should understand client-side routing vs server-side routing.

Question #11: What is React.memo?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

React.memo is a Higher Order Component that prevents unnecessary re-rendering when props have not changed.

Code Example

const UserCard = React.memo(
  ({ user }) => {

    console.log('Rendered');

    return (
      <div>
        {user.name}
      </div>
    );
  }
);

When To Use?

  • Expensive Components
  • Large Lists
  • Dashboard Widgets
Interviewer Note: 💡 Candidates should know React.memo is not a silver bullet.

Question #12: What is useMemo?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

useMemo memoizes computed values and recalculates them only when dependencies change.

Code Example

const total = useMemo(() => {

  return orders.reduce(
    (sum, item) => sum + item.amount,
    0
  );

}, [orders]);

Real World Usage

  • Large Data Sets
  • Reports
  • Dashboard Calculations

Question #13: What is useCallback?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

useCallback memoizes function references to avoid unnecessary re-renders.

Code Example

const saveUser = useCallback(() => {

  api.save(user);

}, [user]);

Follow-Up Questions

  • Difference between useMemo and useCallback?
  • When should useCallback be avoided?

Question #14: What is Context API?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Context API provides a way to share data across components without prop drilling.

Code Example

const UserContext =
  createContext();

function App() {

  return (
    <UserContext.Provider
      value={user}
    >
      <Dashboard />
    </UserContext.Provider>
  );
}
Interviewer Note: 💡 Candidates should understand Context API is not a replacement for Redux.

Question #15: What are Custom Hooks?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Custom Hooks allow reusable stateful logic to be shared across components.

Code Example

function useWindowWidth() {

  const [width, setWidth] =
    useState(window.innerWidth);

  useEffect(() => {

    const resize = () =>
      setWidth(window.innerWidth);

    window.addEventListener(
      'resize',
      resize
    );

    return () =>
      window.removeEventListener(
        'resize',
        resize
      );

  }, []);

  return width;
}
Interviewer Note: 💡 Every React developer should know how to create custom hooks.

Question #16: What are Error Boundaries?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Error Boundaries are React components that catch JavaScript errors in their child component tree and display a fallback UI instead of crashing the entire application.

Code Example

class ErrorBoundary extends React.Component {

  state = {
    hasError: false
  };

  static getDerivedStateFromError() {
    return {
      hasError: true
    };
  }

  render() {

    if (this.state.hasError) {
      return <h2>Something went wrong</h2>;
    }

    return this.props.children;
  }
}

Real World Usage

  • Dashboard Widgets
  • Third Party Components
  • Micro Frontends

Question #17: What is Code Splitting?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Code Splitting allows applications to load only required JavaScript bundles instead of downloading everything upfront.

Code Example

const Dashboard = React.lazy(
  () => import('./Dashboard')
);

Benefits

  • Smaller Bundle Size
  • Faster Initial Load
  • Better Performance
Interviewer Note: 💡 Most enterprise React applications use route-level code splitting.

Question #18: What is Lazy Loading?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Lazy Loading delays loading components until they are actually needed.

Code Example

import React, {
  Suspense
} from 'react';

const Users = React.lazy(
  () => import('./Users')
);

function App() {

  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Users />
    </Suspense>
  );
}

Real World Usage

  • Admin Modules
  • Reports Section
  • Large Dashboards

Question #19: What is Redux Toolkit?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Redux Toolkit is the official recommended way to write Redux logic with less boilerplate code.

Code Example

import {
  createSlice
} from '@reduxjs/toolkit';

const userSlice = createSlice({

  name: 'user',

  initialState: {
    name: ''
  },

  reducers: {

    setUser(state, action) {
      state.name =
        action.payload;
    }

  }

});

When To Use?

  • Large Applications
  • Shared Global State
  • Complex Business Logic

Question #20: What is a Higher Order Component (HOC)?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

A Higher Order Component is a function that accepts a component and returns an enhanced component.

Code Example

function withAuth(
  Component
) {

  return function AuthComponent(
    props
  ) {

    const isLoggedIn = true;

    return isLoggedIn
      ? <Component {...props} />
      : <p>Access Denied</p>;

  };

}

Common Use Cases

  • Authentication
  • Authorization
  • Logging
  • Analytics
Interviewer Note: 💡 Modern React often prefers Hooks over HOCs, but HOCs are still asked in interviews.

Question #21: What is the Render Props Pattern?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Render Props is a pattern where a component shares logic by passing a function as a prop that returns JSX.

Code Example

function MouseTracker({

  render

}) {

  const [position, setPosition] =
    useState({
      x: 0,
      y: 0
    });

  return render(position);

}

<MouseTracker
  render={(pos) => (
    <h2>
      {pos.x}, {pos.y}
    </h2>
  )}
/>
Interviewer Note: 💡 Mostly replaced by Hooks but still important for legacy projects.

Question #22: What is Component Composition?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Component Composition is the practice of combining smaller reusable components to build larger features instead of using inheritance.

Code Example

function Card({

  children

}) {

  return (
    <div className='card'>
      {children}
    </div>
  );

}

<Card>

  <h2>Product</h2>

  <p>
    Product Description
  </p>

</Card>

Benefits

  • Reusable Components
  • Cleaner Architecture
  • Better Maintainability

Question #23: How do you handle Forms and Validation in React?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

Forms can be managed using controlled components, custom validation logic or libraries such as React Hook Form and Formik.

Code Example

const [email, setEmail] =
  useState('');

const submit = () => {

  if (!email) {
    alert('Email Required');
  }

};

<input
  value={email}
  onChange={(e) =>
    setEmail(e.target.value)
  }
/>

Common Libraries

  • React Hook Form
  • Formik
  • Yup
  • Zod

Question #24: How do you test React Components?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

React components are commonly tested using Jest and React Testing Library.

Code Example

import {

  render,
  screen

} from '@testing-library/react';

test(

  'renders title',

  () => {

    render(
      <h1>React</h1>
    );

    expect(
      screen.getByText('React')
    ).toBeInTheDocument();

  }

);

Types of Testing

  • Unit Testing
  • Integration Testing
  • End-to-End Testing

Question #25: How do you optimize React Performance?

Level: Mid-Level | Category: Hooks & State | Time: 12 mins

Expected Answer

React performance can be improved using memoization, lazy loading, virtualization and efficient state management.

Optimization Techniques

  • React.memo
  • useMemo
  • useCallback
  • Lazy Loading
  • Code Splitting
  • Virtualization

Virtualization Example

import {

  FixedSizeList

} from 'react-window';

<FixedSizeList

  height={500}
  itemCount={10000}
  itemSize={35}

>

  {Row}

</FixedSizeList>
Interviewer Note: 💡 For 5+ years candidates, interviewers usually expect real-world performance tuning examples.

Question #26: Explain React Reconciliation

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Reconciliation is React's process of comparing the previous Virtual DOM with the new Virtual DOM and updating only the changed parts of the real DOM.

Practical Example

When a counter changes from 1 to 2, React updates only the text node instead of rebuilding the entire page.

Interview Follow-Up

  • What role do Keys play?
  • How does React decide to re-use a component?
  • What happens when Keys change?
Interviewer Note: 💡 Most candidates know Virtual DOM but cannot explain reconciliation.

Question #27: What is React Fiber Architecture?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Fiber is React's rendering engine introduced to improve rendering, scheduling and responsiveness for large applications.

Key Benefits

  • Incremental Rendering
  • Task Prioritization
  • Concurrent Features
  • Better UI Responsiveness

Practical Example

A large dashboard can continue responding to user interactions while React processes low-priority updates in the background.

Interviewer Note: 💡 Frequently asked for senior React positions.

Question #28: What is Concurrent Rendering?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Concurrent Rendering allows React to prepare multiple UI updates without blocking the browser's main thread.

Code Example

import {

  useTransition

} from 'react';

function Search() {

  const [

    isPending,

    startTransition

  ] = useTransition();

  const handleChange = (value) => {

    startTransition(() => {

      setSearch(value);

    });

  };

}

Benefits

  • Smoother User Experience
  • Reduced UI Blocking
  • Better Responsiveness

Question #29: What is Suspense?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Suspense allows React to display fallback content while waiting for components or data to load.

Code Example

import {

  Suspense

} from 'react';

<Suspense

  fallback={<p>Loading...</p>}

>

  <Dashboard />

</Suspense>

Common Usage

  • Lazy Loading
  • Code Splitting
  • Server Components

Question #30: Explain Hydration in React

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Hydration is the process of attaching React event handlers to HTML generated by server-side rendering.

Practical Example

Next.js renders HTML on the server, sends it to the browser, then React hydrates it to make it interactive.

Why Important?

  • Improves SEO
  • Faster Initial Load
  • Better User Experience
Interviewer Note: 💡 Senior candidates should understand hydration mismatches and debugging techniques.

Question #31: What are React Server Components?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

React Server Components execute on the server and send rendered UI to the client without shipping unnecessary JavaScript.

Benefits

  • Smaller Bundle Size
  • Faster Page Load
  • Improved SEO
  • Reduced Client-Side Processing

Practical Example

Product listing pages can be rendered entirely on the server while interactive shopping cart functionality remains on the client.

Question #32: Explain SSR vs CSR vs SSG

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Type Rendering Location
CSR Browser
SSR Server
SSG Build Time

Practical Example

  • CSR → Internal Dashboard
  • SSR → E-Commerce Website
  • SSG → Blog Platform
Interviewer Note: 💡 Senior developers should understand SEO, caching and performance implications.

Question #33: What is React Query (TanStack Query)?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

React Query is a data-fetching library that simplifies server-state management, caching and synchronization.

Code Example

import {

  useQuery

} from '@tanstack/react-query';

function Users() {

  const {

    data,
    isLoading

  } = useQuery({

    queryKey: ['users'],

    queryFn: () =>
      fetch('/api/users')
        .then(r => r.json())

  });

}

Benefits

  • Caching
  • Background Refetching
  • Retry Logic
  • Optimistic Updates

Question #34: Zustand vs Redux Toolkit

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Zustand Redux Toolkit
Simple Enterprise Ready
Minimal Boilerplate Structured Architecture
Small Bundle Advanced Tooling

Code Example

import {

  create

} from 'zustand';

const useStore = create(

  (set) => ({

    count: 0,

    increment: () =>

      set((state) => ({

        count: state.count + 1

      }))

  })

);
Interviewer Note: 💡 Interviewers often ask which solution you would choose and why.

Question #35: How do you identify and prevent memory leaks in React?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Memory leaks occur when subscriptions, timers or event listeners remain active after a component is unmounted.

Common Causes

  • Uncleared setTimeout
  • Uncleared setInterval
  • WebSocket Connections
  • Event Listeners
  • Subscriptions

Code Example

useEffect(() => {

  const timer = setInterval(

    () => {

      console.log('Running');

    },

    1000

  );

  return () => {

    clearInterval(timer);

  };

}, []);
Interviewer Note: 💡 Production debugging experience is often revealed through this question.

Question #36: How do you optimize React bundle size?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Bundle size can be optimized through code splitting, lazy loading, tree shaking, dynamic imports and dependency optimization.

Optimization Techniques

  • React.lazy()
  • Dynamic Imports
  • Tree Shaking
  • Webpack Bundle Analyzer
  • Removing Unused Libraries

Code Example

const AdminModule = React.lazy(
  () => import('./AdminModule')
);
Interviewer Note: 💡 Candidates should mention bundle analysis tools.

Question #37: What are React Security Best Practices?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

React automatically escapes content, but developers must still protect applications against XSS, CSRF and insecure API usage.

Security Checklist

  • Avoid dangerouslySetInnerHTML
  • Validate User Input
  • Use HTTPS
  • Secure Authentication Tokens
  • Implement CSP Headers

Dangerous Example

<div
  dangerouslySetInnerHTML={{
    __html: userContent
  }}
></div>

Question #38: Explain React Rendering Internals

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

React follows a rendering pipeline consisting of Render Phase and Commit Phase.

Rendering Flow

  • State Change
  • Virtual DOM Generation
  • Reconciliation
  • Fiber Scheduling
  • DOM Commit
Interviewer Note: 💡 This question separates senior developers from mid-level developers.

Question #39: How would you design a scalable React application?

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

A scalable React application should have clear separation of concerns, reusable components, modular architecture and proper state management.

Example Folder Structure

src/

├── components/
├── features/
├── hooks/
├── services/
├── store/
├── routes/
├── utils/
└── pages/

Architecture Considerations

  • Code Splitting
  • State Management
  • Testing Strategy
  • Performance Monitoring
  • Error Handling

Question #40: Describe a production issue you solved in React

Level: Senior | Category: Core & Performance | Time: 15 mins

Expected Answer

Interviewers want to evaluate debugging skills, ownership and production experience.

Strong Answer Structure

  • Problem Description
  • Impact Analysis
  • Investigation Steps
  • Root Cause
  • Fix Applied
  • Lessons Learned

Example Scenario

A dashboard became extremely slow after loading 15,000 records. Investigation revealed unnecessary component re-renders. The issue was resolved using React.memo, virtualization and API pagination.

Interviewer Note: 💡 One of the most important senior-level questions.

Question #41: How would you design Netflix using React?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

A Netflix-like application requires scalable architecture, lazy loading, SSR, caching, video streaming integration, performance optimization and global CDN distribution.

High Level Architecture

Users

  ↓

CDN

  ↓

React / Next.js

  ↓

API Gateway

  ↓

Microservices

  ├── Movies
  ├── Recommendations
  ├── Search
  └── User Profiles

Key Considerations

  • SSR for SEO
  • Video Streaming Optimization
  • Recommendation Engine
  • Global CDN
  • Micro Frontend Architecture
Interviewer Note: 💡 Strong candidates discuss scalability, caching and user experience.

Question #42: How would you design an Enterprise E-Commerce Platform?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

The application should support millions of users, product catalogs, inventory, orders, payments and analytics.

Modules

Frontend

├── Home
├── Products
├── Cart
├── Checkout
├── Orders
├── User Profile

Admin

├── Inventory
├── Pricing
├── Analytics
└── Promotions

Technology Choices

  • Next.js
  • React Query
  • Redux Toolkit
  • CDN
  • Edge Caching

Question #43: What are Micro Frontends and when would you use them?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Micro Frontends divide a large frontend application into independently deployable modules owned by different teams.

Architecture Example

Host Application

├── Products Team
├── Orders Team
├── Payments Team
├── Analytics Team

Each team deploys independently.

Popular Technologies

  • Webpack Module Federation
  • Single SPA
  • Nx

Question #44: How would you structure a React Monorepo?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Monorepos enable code sharing, consistent tooling and easier dependency management across multiple applications.

Folder Structure

apps/

  customer-portal
  admin-portal
  seller-portal

packages/

  ui
  auth
  api-client
  shared-types

Tools

  • Nx
  • Turborepo
  • Rush

Question #45: How would you design a reusable Design System?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

A design system provides reusable UI components, accessibility standards and branding consistency.

Architecture

@company/ui-core

@company/ui-react

@company/theme

@company/icons

Key Features

  • Accessibility
  • Dark Mode
  • Theming
  • Storybook
  • Versioning
Interviewer Note: 💡 Architects should discuss governance and adoption strategy.

Question #46: How would you design an Enterprise State Management Strategy?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Different types of state should be managed using appropriate tools. Not all state belongs in Redux or Context API.

Recommended Strategy

UI State

  ↓

useState

--------------------------------

Global Application State

  ↓

Redux Toolkit

--------------------------------

Server State

  ↓

React Query

--------------------------------

Form State

  ↓

React Hook Form

Interview Discussion Points

  • Redux Toolkit vs Zustand
  • Context API Limitations
  • Server State vs Client State
  • Scalability Considerations
Interviewer Note: 💡 Architects should justify why each state management solution is used.

Question #47: How would you improve Core Web Vitals in a React Application?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Core Web Vitals measure user experience and directly impact SEO and business metrics.

Important Metrics

LCP
(Largest Contentful Paint)

CLS
(Cumulative Layout Shift)

INP
(Interaction to Next Paint)

Optimization Techniques

  • SSR / SSG
  • Image Optimization
  • Code Splitting
  • CDN Usage
  • Lazy Loading
  • Caching

Monitoring Tools

  • Google Lighthouse
  • PageSpeed Insights
  • Chrome DevTools
  • Web Vitals Library
Interviewer Note: 💡 Candidates should explain how improvements affect business KPIs.

Question #48: How would you design a Frontend CI/CD Pipeline?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Every code change should pass quality gates before reaching production.

Pipeline Example

Developer

  ↓

Pull Request

  ↓

Lint

  ↓

Unit Tests

  ↓

Build

  ↓

E2E Tests

  ↓

Security Scan

  ↓

Deploy

  ↓

Monitoring

Popular Tools

  • GitHub Actions
  • Azure DevOps
  • GitLab CI
  • Jenkins

Advanced Topics

  • Blue-Green Deployment
  • Canary Releases
  • Feature Flags
  • Rollback Strategy

Question #49: How would you monitor a React Application in Production?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Production monitoring should provide visibility into errors, performance issues and user behavior.

Observability Architecture

Users

  ↓

Frontend Application

  ↓

Sentry

  ↓

Datadog

  ↓

Alerting

  ↓

Engineering Team

Track These Metrics

  • JavaScript Errors
  • API Failures
  • Performance Metrics
  • User Sessions
  • Core Web Vitals

Popular Tools

  • Sentry
  • Datadog
  • New Relic
  • Azure Monitor
  • Grafana
Interviewer Note: 💡 Architects should discuss observability, not just error logging.

Question #50: How would you lead a team of 20+ React Developers?

Level: Architect | Category: Architecture & Design | Time: 18 mins

Expected Answer

Leadership involves balancing people, process and technology while maintaining delivery quality and engineering standards.

Leadership Responsibilities

  • Architecture Reviews
  • Code Quality Standards
  • Mentoring Developers
  • Technical Roadmaps
  • Performance Reviews
  • Cross-Team Collaboration

Team Structure Example

Frontend Architect

├── Team Lead A
│   ├── 5 Developers
│   └── QA

├── Team Lead B
│   ├── 5 Developers
│   └── QA

└── Team Lead C
    ├── 5 Developers
    └── QA

Key Success Metrics

  • Deployment Frequency
  • Defect Rate
  • Developer Productivity
  • Technical Debt Reduction
  • System Reliability
Interviewer Note: 💡 Strong architects talk about team enablement, not just coding.

Question #51: Why is state updates in React asynchronous (batched)? How does automatic batching work in React 18?

Level: Junior | Category: Fundamentals | Time: 5 mins

Expected Answer

State updates are batched for performance optimization. If React re-rendered the component immediately on every state update, multiple state updates inside the same event handler would cause unnecessary reflows and repaints.

  • Automatic Batching (React 18): In older versions, React only batched updates inside React event handlers. React 18 introduces automatic batching, which batches state updates across promises, timeouts, and native event handlers as well.

Code Example


// React 18 batches both state updates, triggering a single re-render:
setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
}, 1000);
Interviewer Note: 💡 Check if the candidate knows how to opt out of batching using flushSync() when immediate DOM updates are required.

Question #52: What are Synthetic Events in React? How do they differ from native browser events?

Level: Junior | Category: Fundamentals | Time: 5 mins

Expected Answer

Synthetic Events are React's wrapper around browser native events, providing a consistent API across different browsers:

  • Cross-Browser Compatibility: Normalizes event behaviors across browsers (e.g. auto-handling transition events).
  • Event Pooling (Legacy): In React 16 and older, event objects were pooled and reused for performance, which meant they could not be accessed asynchronously unless event.persist() was called. This pooling was removed in React 17.
Interviewer Note: 💡 Ask: 'Where are events attached in React 17+?' (Answer: They are attached to the root container node instead of the document, which helps run multiple React versions on the same page).

Question #53: Explain the difference between useEffect and useLayoutEffect. When should you use useLayoutEffect?

Level: Junior | Category: Hooks & State | Time: 5 mins

Expected Answer

These hooks run side effects at different stages of browser rendering:

  • useEffect: Runs asynchronously **after** the browser has painted layout changes onto the screen. This is non-blocking and preferred for API calls, timers, and subscriptions.
  • useLayoutEffect: Runs synchronously **after** DOM mutations but **before** the browser paints changes. This blocks the main thread, making it ideal for measuring DOM layout or adjusting styles before they appear on screen, preventing visual jumps.
Interviewer Note: 💡 Warn candidates: useLayoutEffect blocks rendering, which can lead to laggy performance if it contains heavy computations.

Question #54: What is the difference between useRef and a normal variable defined inside a component?

Level: Junior | Category: Hooks & State | Time: 5 mins

Expected Answer

These variables handle state preservation differently during rendering:

  • Normal Variable: Re-initialized on every render. If the component re-renders, the variable's value resets.
  • useRef: Preserves its .current value across re-renders. Modifying .current is a side effect and **does not trigger** a component re-render.

Code Example


function Counter() {
  const countRef = useRef(0);
  let normalCount = 0;
  
  const increment = () => {
    countRef.current++; // Value is preserved across renders, but does not trigger re-render
    normalCount++; // Resets back to 0 on the next component render!
  };
}
Interviewer Note: 💡 Check if the candidate knows when to use useRef (e.g. storing timer IDs, accessing DOM elements directly).

Question #55: What is the difference between useReducer and useState? When is useReducer preferred?

Level: Junior | Category: Hooks & State | Time: 5 mins

Expected Answer

Both hooks manage component state, but are suited for different state complexities:

  • useState: Best for simple state values (e.g. flags, strings, simple objects).
  • useReducer: Best for complex state structures with multiple actions (e.g. forms, state machines). It separates state update logic from components, making it easier to test.
Interviewer Note: 💡 Ask about optimization: useReducer makes passing dispatch handlers down to children safer because dispatch is guaranteed to be stable and won't trigger re-renders.

Question #56: Explain React's Compound Component pattern (e.g. <Select><Select.Option /></Select>). How does it share state?

Level: Junior | Category: Design Patterns | Time: 5 mins

Expected Answer

The Compound Component pattern allows building modular UI elements that share state implicitly using **Context API**. This decouples layouts from data flow, allowing consumers to arrange sub-elements customly without passing redundant props.

Code Example


const SelectContext = createContext();

function Select({ children, onChange }) {
  const [value, setValue] = useState('');
  return (
    <SelectContext.Provider value={{ value, setValue, onChange }}>
      <div className="select-box">{children}</div>
    </SelectContext.Provider>
  );
}

Select.Option = function Option({ value, children }) {
  const { setValue, onChange } = useContext(SelectContext);
  return (
    <div onClick={() => { setValue(value); onChange(value); }}>{children}</div>
  );
};
Interviewer Note: 💡 A clean design pattern question. Check if they use Context or React.Children.map (Context is preferred as it supports nested structures).

Question #57: What is a portal in React (createPortal)? When should it be used for UI overlays?

Level: Junior | Category: Fundamentals | Time: 5 mins

Expected Answer

createPortal(child, container) renders React elements into a DOM node located outside the parent component's DOM tree.

  • Use Cases: Modal dialogs, tooltips, and popups. It prevents CSS clipping and parent styling limits (like `overflow: hidden` or `z-index` stacking context rules) from cutting off elements.
Interviewer Note: 💡 Ask: 'Do portal events bubble?' (Answer: Yes, events still bubble up the React component tree hierarchy, regardless of their location in the DOM).

Question #58: How does React's O(N) Diffing Algorithm work? Explain the heuristics (element type changes, keys).

Level: Mid-Level | Category: Core & Performance | Time: 7 mins

Expected Answer

Comparing two XML trees has an O(N³) complexity, which is too slow for real-time rendering. React implements a heuristic $O(N)$ diffing algorithm based on two assumptions:

  • Different Element Types: If two elements have different types (e.g. changing `div` to `span`), React destroys the old tree and builds the new one from scratch.
  • Keys Validation: React uses `key` props to track element identities across renders, allowing it to move or update elements rather than destroying and rebuilding them.
Interviewer Note: 💡 Important for performance: explains why changing keys forces components to unmount and re-mount completely.

Question #59: Why does referencing a Context provider force all consumer components to re-render, even if they only read a portion of the value? How do you prevent this?

Level: Mid-Level | Category: Hooks & State | Time: 7 mins

Expected Answer

React's Context API triggers re-renders on all components consuming a context value whenever that value changes, even if they only read a property that didn't change.

  • Prevention: Split the context into separate, smaller contexts, or wrap consumer component bodies in React.memo and pass read values down as props, or use global state managers (like Zustand) that support selectors to read specific state properties.
Interviewer Note: 💡 Candidates should know that Context is not an optimized state management tool for high-frequency updates.

Question #60: Explain the difference between the useMemo hook and React.memo HOC.

Level: Mid-Level | Category: Core & Performance | Time: 7 mins

Expected Answer

While both optimize performance via caching, they serve different scopes:

  • React.memo: A Higher Order Component that caches the **rendering output** of a component, preventing re-renders if props remain shallowly equal.
  • useMemo: A React hook that caches the **return value** of a function, preventing re-calculations inside components unless dependencies change.
Interviewer Note: 💡 Ask about comparison functions: React.memo accepts a custom comparison function as its second argument.

Question #61: Explain React 19's new use hook. How does it handle Promises and Context conditionally?

Level: Mid-Level | Category: React 19 Features | Time: 8 mins

Expected Answer

React 19 introduces the use API, which can read Promises or Context values dynamically inside rendering flows:

  • Conditional Usage: Unlike standard React hooks, use can be called conditionally inside if blocks and loops.
  • Promise Resolution: If passed a Promise, use suspends the component, showing the nearest Suspense boundary fallback until the Promise resolves.

Code Example


function UserProfile({ userPromise }) {
  // Can resolve promises inside the rendering path!
  const user = use(userPromise);
  return <div>{user.name}</div>;
}
Interviewer Note: 💡 A modern React 19 check. Verify they know that 'use' still cannot be called inside nested JavaScript helper functions (only inside component rendering functions).

Question #62: What is the React Compiler (React Forget)? How does it automate dependency arrays and memoization?

Level: Mid-Level | Category: React Compiler | Time: 7 mins

Expected Answer

The React Compiler (formerly React Forget) is a build-time tool that compiles code to automate memoization. It analyzes code structures and automatically inserts memoization checks for components, hooks, and hook dependency arrays. This removes the need to write useMemo, useCallback, and React.memo manually, reducing boilerplate.

Interviewer Note: 💡 Tests modern build tool awareness. Ask them if they still need to write key properties (Answer: Yes, keys are still required by the reconciler).

Question #63: What are React 19 Actions? Explain the new useActionState and useFormStatus hooks.

Level: Mid-Level | Category: React 19 Features | Time: 8 mins

Expected Answer

React 19 introduces **Actions** to simplify handling asynchronous state transitions (like form submissions):

  • useActionState: Manages state updates for async actions, automatically tracking pending states and error messages.
  • useFormStatus: A hook that reads the parent form's submission status (e.g. pending), removing the need to pass pending states manually as props.

Code Example


// useActionState signature
const [state, formAction, isPending] = useActionState(async (prevState, formData) => {
  const result = await saveUser(formData.get('name'));
  return result;
}, null);
Interviewer Note: 💡 Check if the candidate knows how useFormStatus requires context, meaning it must be used inside a child component rendered within the form wrapper.

Question #64: Explain Next.js dynamic routing, middleware, and route handlers.

Level: Mid-Level | Category: Next.js Concepts | Time: 8 mins

Expected Answer

Next.js provides a robust, file-based routing architecture:

  • Dynamic Routing: Created using folder name brackets (e.g. [id]/page.js matches /users/123).
  • Middleware: A script (middleware.js) that intercepts requests before they complete. Used to inspect session cookies, handle redirects, or check authentication headers.
  • Route Handlers: Custom request handlers built using standard Web Request and Response APIs (e.g. route.js).
Interviewer Note: 💡 Look for experience with Next.js App Router conventions.

Question #65: What is the difference between React Server Components (RSC) and Server-Side Rendering (SSR)?

Level: Mid-Level | Category: Core & Performance | Time: 8 mins

Expected Answer

While both execute on the server, they solve different performance bottlenecks:

  • SSR (Server-Side Rendering): Generates raw HTML on the server. The client downloads the HTML and must download and execute JavaScript to hydrate the page, making it interactive. SSR is a rendering lifecycle step.
  • RSC (React Server Components): Components that run only on the server, generating a serialized JSON stream (not HTML). They don't ship JavaScript for client hydration. This reduces bundle sizes.
Interviewer Note: 💡 Ensure they understand that RSCs and SSR are complementary technologies, not competitors.

Question #66: Explain the useDeferredValue and useTransition hooks. How do they solve main-thread blocking during input updates?

Level: Mid-Level | Category: Core & Performance | Time: 8 mins

Expected Answer

Both hooks defer low-priority updates to keep the main thread responsive:

  • useTransition: Used to wrap state transitions (e.g. filtering lists). React processes the update in the background and can interrupt it if the user continues typing.
  • useDeferredValue: Defers updating a value (like a search string) for child components until high-priority renders are complete.

Code Example


const deferredQuery = useDeferredValue(query);
const list = useMemo(() => , [deferredQuery]);
Interviewer Note: 💡 Look for their understanding of how these hooks differ from standard debounce methods (which use timers instead of scheduling priorities).

Question #67: What is the difference between useId and generating random numbers or global counters for accessibility element IDs?

Level: Mid-Level | Category: Accessibility | Time: 7 mins

Expected Answer

useId generates unique, stable IDs across client and server renders:

  • Random Numbers (e.g. Math.random): Re-evaluate on every render, which causes hydration mismatches because the server and client generate different IDs.
  • Global Counters: Can cause ID collisions when running multiple app instances on the same page.
  • useId: Generates a stable string ID that is unique across mounts and matches exactly during hydration.
Interviewer Note: 💡 A good accessibility check. Ensure they know useId is intended for linking DOM attributes (like aria-describedby) rather than generating list keys.

Question #68: What are Fiber Nodes, and how does the Fiber reconciler structure work (child, sibling, return pointers)?

Level: Senior | Category: Core & Performance | Time: 12 mins

Expected Answer

A Fiber node is a lightweight object containing component metadata, state, and queues. Unlike standard DOM trees, React Fiber links nodes using a singly linked list structure:

  • child: Points to the first child element.
  • sibling: Points to the next sibling element.
  • return: Points back to the parent container node (the return target).

This structure allows the reconciler to pause, resume, or abort rendering passes at any node in the tree. This is the foundation of concurrent features.

Interviewer Note: 💡 A deep internal question. Evaluate their understanding of reconciliation architecture.

Question #69: Explain React 18/19 Concurrent Rendering and Lane-Based Scheduling. How does React interrupt rendering for high-priority tasks?

Level: Senior | Category: Core & Performance | Time: 12 mins

Expected Answer

Concurrent rendering allows React to pause rendering passes to handle high-priority tasks (like user typing):

  • Lanes: React uses a 32-bit bitmask system (Lanes) to assign priorities to different updates (e.g. SyncLane, InputContinuousLane, TransitionLane).
  • Time-Slicing: During compilation, React splits the render phase into chunks. After processing a chunk, React yields control back to the browser's main thread to check for high-priority events, resuming compilation afterward.
Interviewer Note: 💡 Verify they understand how concurrent rendering prevents input delays (jank) in heavy applications.

Question #70: Detail the hydration process in React. What causes hydration mismatches, and how do you resolve them?

Level: Senior | Category: Core & Performance | Time: 11 mins

Expected Answer

Hydration links server-rendered HTML with client-side React:

  • Process: The browser loads the HTML. React runs on the client, builds the Virtual DOM tree, and attaches event listeners to matching HTML nodes instead of recreating them.
  • Mismatches: Occur when the Virtual DOM generated on the client differs from the server HTML (e.g. using new Date(), browser-only window objects, or invalid nested markup like `

    `).

Resolution

  • Wrap browser-only code in useEffect checks.
  • Disable hydration check for specific nodes using the suppressHydrationWarning attribute.
  • Use dynamic imports with ssr: false to disable SSR for specific components.
Interviewer Note: 💡 Ask about debugging: mismatch details appear in the console, listing differences in HTML attributes and content.

Question #71: How do React Server Components handle client interactivity? Explain the boundaries and the serialize-deserialize serialization stream.

Level: Senior | Category: Core & Performance | Time: 12 mins

Expected Answer

React Server Components (RSC) cannot contain client interactivity (like state or event handlers). To add interactivity, you must define client boundaries using the "use client" directive.

  • RSC Stream: The server renders RSCs into a serialized JSON format containing component metadata, elements, and client component imports.
  • Serialization: Props passed from Server Components to Client Components must be serializable (e.g. strings, numbers, arrays). Passing non-serializable values (like functions or class instances) across boundaries throws compilation errors.
Interviewer Note: 💡 Check if they understand how Client Components can accept Server Components as children props to render static structures.

Question #72: What is CSS Injection, and how can dynamic styling configurations create Cross-Site Scripting (XSS) risks in React applications?

Level: Senior | Category: Security | Time: 11 mins

Expected Answer

While React escapes values rendered in JSX, CSS values passed to inline styles or dynamic CSS declarations are not escaped:

  • CSS Injection: If you pass unescaped user inputs directly to styles (e.g. background: url(...)), attackers can inject malicious URLs or script targets.
  • Mitigation: Avoid passing raw user input strings directly to CSS fields. Sanitize URLs and restrict values to predefined options.
Interviewer Note: 💡 A security-focused question. Check if they know about Content Security Policy (CSP) configurations.

Question #73: Explain the Query Cache lifecycle in TanStack Query (staleTime, gcTime, key invalidation). How does it synchronize client/server states?

Level: Senior | Category: State Management | Time: 11 mins

Expected Answer

TanStack Query manages server state caching using specific configurations:

  • staleTime: The duration before data is marked as stale. While data is fresh, subsequent query requests read from the cache directly without hitting the server.
  • gcTime (formerly cacheTime): The duration inactive query data remains in the cache before being garbage-collected.
  • Invalidation: Triggering queryClient.invalidateQueries() marks cached queries as stale, causing them to refetch in the background.
Interviewer Note: 💡 Ensure they understand the difference between staleTime and gcTime (data can be stale but still present in the cache).

Question #74: How do you test components that contain asynchronous API requests and mock loaders using React Testing Library?

Level: Senior | Category: Testing | Time: 11 mins

Expected Answer

Testing asynchronous behaviors requires waiting for elements to resolve using queries like findBy and utility methods like waitFor:

Code Example


test('loads and displays users', async () => {
  render(<UserList />);
  
  // findBy returns a Promise resolving when the element appears
  const items = await screen.findAllByRole('listitem');
  expect(items).toHaveLength(2);
});
Interviewer Note: 💡 Look for their use of userEvent instead of fireEvent, which mimics real browser interactions more accurately.

Question #75: Explain the atomic state management model (Jotai/Recoil) vs the selector/flux model (Zustand/Redux).

Level: Senior | Category: State Management | Time: 11 mins

Expected Answer

These represent different architectural models for managing global state:

  • Atomic Model (Jotai/Recoil): State is split into small units (atoms). Components subscribe to individual atoms. This prevents re-renders across unrelated components and makes the state structure highly modular.
  • Selector/Flux Model (Zustand/Redux): State is stored in a single store. Components use selectors to read specific state fields. If the selected state changes, the component re-renders. This is preferred for managing structured application states.
Interviewer Note: 💡 Ask the candidate how they choose between these libraries for a large project.

Question #76: How do you build an accessible Modal component (focus traps, escape key bindings, and aria landmarks) from scratch?

Level: Senior | Category: Accessibility | Time: 11 mins

Expected Answer

An accessible Modal component must meet WAI-ARIA standards:

  • Attributes: Add role="dialog", aria-modal="true", and link titles using aria-labelledby.
  • Focus Management: Move focus to the modal when opened. Implement a **focus trap** to restrict keyboard tab navigation to the modal elements, returning focus to the trigger button when closed.
  • Keyboard Bindings: Close the modal when the user presses the Escape key.
Interviewer Note: 💡 A great accessibility check. Ask about libraries that simplify this (like Radix UI Dialog).

Question #77: How does Webpack Module Federation enable dynamic micro-frontend shell orchestration in enterprise React apps?

Level: Senior | Category: Architecture & Design | Time: 11 mins

Expected Answer

Webpack Module Federation allows an application to load compiled JavaScript bundles from other builds dynamically at runtime:

  • Dynamic Remote Loading: The container shell loads remote entry files (e.g. remoteEntry.js) dynamically.
  • Shared Dependencies: Allows sharing dependencies (like `react`, `react-dom`) between builds. This avoids loading multiple copies of libraries, reducing bundle sizes and preventing runtime conflicts.
Interviewer Note: 💡 Look for experience with micro-frontends and dependency sharing configurations.

Question #78: Explain Next.js Server Actions and how to handle form revalidation, error states, and security validations.

Level: Senior | Category: Next.js Concepts | Time: 11 mins

Expected Answer

Server Actions are asynchronous functions executed on the server, declared using the "use server" directive. They can be invoked directly from Client or Server Components.

  • Revalidation: Update cached routes dynamically using revalidatePath() or revalidateTag().
  • Security: Always validate input values (using Zod) and verify session authentication tokens inside the action, because client parameters can be tampered with.
Interviewer Note: 💡 Ask about security: Server Actions compile to POST endpoints, which means they are susceptible to CSRF attacks if not secured.

Question #79: Explain the difference between Cypress and Playwright for E2E testing React applications.

Level: Senior | Category: Testing | Time: 11 mins

Expected Answer

Both are popular E2E testing tools, but use different architectures:

  • Cypress: Runs tests inside the browser itself, providing simple debugging and visual test runners. However, it only supports single-origin navigations and is slower for testing multi-tab features.
  • Playwright: Controls browsers using DevTools protocols (like CDP) from Node.js. It supports multiple tabs, multiple browser contexts, is faster, and integrates with CI pipelines out of the box.
Interviewer Note: 💡 Look for experience with setting up testing environments in CI/CD pipelines.

Question #80: What are the performance hazards of using inline function bindings or object literals inside React render paths, and when does it matter?

Level: Senior | Category: Core & Performance | Time: 11 mins

Expected Answer

Declaring inline functions (e.g. onClick={() => doSomething()}) or object literals (e.g. style={{ margin: 0 }}) creates new object instances in memory on every render.

  • When it matters: This is a performance hazard when passed as props to child components optimized with React.memo. Because inline functions and objects have new references on every render, the shallow equality checks in React.memo fail, forcing the child component to re-render.
Interviewer Note: 💡 Check if they know when this behavior is safe (e.g., passing inline events to native HTML elements, where reference checks don't affect performance).

Architect Question #11: Design a scalable, resilient Micro-Frontend container shell in React using Webpack Module Federation and Shared State.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

A Micro-Frontend shell application coordinates loading independent application modules dynamically:

  • Orchestration: Use Webpack Module Federation to mount remote entry files asynchronously.
  • Resilience: Wrap remote imports in Error Boundaries and Suspense blocks to prevent a crash in a micro-frontend from taking down the entire application shell.
  • State Sharing: Implement a shared event emitter or a lightweight custom state store to communicate between micro-frontends without creating tight couplings.
Interviewer Note: 💡 Look for their use of shared dependencies configurations to prevent duplicate React runtime instances from loading.

Architect Question #12: Design a modular Design System component library (like Radix UI or Headless UI) supporting complete accessibility, theming, and token overrides.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

A design system requires decoupling component logic from styling:

  • Unstyled Base: Build unstyled, accessible components (using Radix primitives) that handle keyboard navigation and aria states.
  • Theming: Use CSS custom variables linked to design token JSON files, allowing consumers to override styles dynamically.
  • Composition: Expose slot properties (using asChild patterns) to allow consumers to customize the rendered DOM elements easily.
Interviewer Note: 💡 Ask about package versioning strategies (e.g., using monorepos with Lerna or Changesets to release updates).

Architect Question #13: Architect an offline-first mobile web dashboard in React using Service Workers, IndexedDB, and conflict resolution sync gates.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

An offline-first architecture uses service workers and local storage to handle network changes:

  • Asset Caching: Use Workbox to configure a Stale-While-Revalidate caching strategy for JS and CSS bundles.
  • Data Storage: Store application data in IndexedDB (using Dexie.js) to support offline writes.
  • Synchronization: When the browser comes online, trigger a background synchronization queue to upload local updates, resolving data conflicts using conflict resolution strategies (like Last-Write-Wins).
Interviewer Note: 💡 Ask about browser storage limits and how to handle quota errors on mobile platforms.

Architect Question #14: Design a telemetry and error logging SDK for React apps that captures crash stacks, breadcrumbs, user states, and sends beacon data.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

A monitoring SDK captures application crashes and user actions without degrading page performance:

  • Error Capture: Intercept crashes using global window error listeners and React Error Boundaries.
  • Breadcrumbs: Track user interactions, route changes, and API fetches automatically to build a timeline leading to a crash.
  • Data Delivery: Deliver telemetry packets asynchronously using navigator.sendBeacon() to prevent blocking page transitions.
Interviewer Note: 💡 Verify they understand the difference between beforeunload and visibilitychange events when sending final telemetry logs.

Architect Question #15: Design a dynamic theme engine in React that supports dark mode, brand overrides, and user-configured palettes using CSS Custom Properties and Context.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

A theme engine should toggle brand properties dynamically without triggering full component re-renders:

  • CSS Custom Variables: Define styling parameters as CSS variables (e.g. --color-primary) on the document root.
  • Context API: Use a theme context to store the current theme mode string. When toggled, update the matching attributes on the HTML root element.
  • No Re-renders: Because layout colors are controlled by CSS variables, updating the root attributes changes styles instantly without forcing React to re-render the component tree.
Interviewer Note: 💡 Verify they know to apply theme selections during initial HTML loading to prevent flash-of-unstyled-content (FOUC) flashes.

Architect Question #16: Architect a secure authentication and token refresh strategy in React using silent token refresh, secure cookies, and Axios interceptors.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

Secure authentication requires separating tokens to prevent script access and XSS theft:

  • Tokens: Store access tokens in memory (JavaScript state). Store refresh tokens in HttpOnly, Secure, SameSite=Strict cookies.
  • Axios Interceptors: Add interceptors to handle outgoing requests and responses. If an API request fails with a 401 error, pause request queues, fetch a new access token in the background, update request headers, and retry the failed requests automatically.
Interviewer Note: 💡 Look for their handling of multiple concurrent 401 requests (queuing requests to prevent triggering multiple refresh token requests simultaneously).

Architect Question #17: Design a high-frequency real-time dashboard in React that renders 10,000 data updates per second without freezing the UI thread.

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

Rendering 10,000 updates per second synchronously will block the main thread and freeze the UI. To prevent this:

  • Throttling: Buffer incoming data updates and batch render updates once every 100-200ms using a timer.
  • Bypass React: Update high-frequency values (like chart bars or text ticks) by writing directly to DOM node references (using refs), bypassing React's reconciler entirely.
  • Web Workers: Process incoming websocket data streams in a Web Worker, sending only finalized data payloads back to the main thread.
Interviewer Note: 💡 Check if they suggest Canvas rendering or virtualization libraries to optimize the list rendering performance.

Architect Question #18: How do SOLID principles translate to modern React development using hooks, composition, and custom provider factories?

Level: Architect | Category: Architecture & Design | Time: 15 mins

Expected Answer

SOLID principles help build decoupled, maintainable React components:

  • Single Responsibility: Separate data-fetching logic into custom hooks, keeping UI components focused on rendering.
  • Open/Closed: Extend component behaviors using children composition or slots rather than adding multiple conditional properties.
  • Interface Segregation: Components should only require props they actually use. Avoid passing entire large data objects if the component only reads a single property.
  • Dependency Inversion: Inject configurations or providers using Context providers, rather than importing concrete configurations directly.
Interviewer Note: 💡 Evaluate if the candidate prefers component composition over nested class inheritance structures.

Tricky Question #1: Why does updating state using setCount(count + 1) multiple times inside an event handler result in only a single increment?

Level: Tricky Question | Category: Fundamentals | Time: 10 mins

Expected Answer

State updates are scheduled and batched. Inside the event handler, the count variable retains its initial closure value (e.g. 0) during execution.

The Trap: Calling setCount(count + 1) multiple times translates to setCount(0 + 1), which repeatedly schedules updates to 1. The component re-renders once with a count of 1.

Fix: Pass an updater function that receives the latest state: setCount(prev => prev + 1).

Interviewer Note: 💡 A classic state closure trap. Verify they understand how updater functions resolve state dependencies.

Tricky Question #2: What is the Stale Closure problem inside useEffect? Write an example and explain the resolution.

Level: Tricky Question | Category: Hooks & State | Time: 10 mins

Expected Answer

A stale closure occurs when a function inside useEffect references state variables from its creation scope, but does not list them in the hook's dependency array. Because the dependency array is empty, the hook is not re-evaluated, keeping variables stuck at their initial values.

Resolution: Include referenced state variables in the dependency array, or use updater functions to read the latest state without creating dependencies.

Code Example


// Stale closure: logs 0 on every tick because count is missing in dependencies
useEffect(() => {
  const interval = setInterval(() => {
    console.log(count);
  }, 1000);
  return () => clearInterval(interval);
}, []); // Missing count dependency!
Interviewer Note: 💡 Excellent React hooks question. Ask how they use refs to store values without updating dependency arrays.

Tricky Question #3: Why does passing a new object array as a dependency to useEffect trigger an infinite rendering loop? How do you solve it?

Level: Tricky Question | Category: Hooks & State | Time: 10 mins

Expected Answer

React performs shallow equality checks (using Object.is) to determine if dependencies have changed. Because arrays and objects are reference types, declaring them inline (e.g. [] or {}) inside a component creates a new reference in memory on every render. Since the references are always different, useEffect executes on every render, triggering state updates that force a new render, creating an infinite loop.

Fixes: Memoize the object using useMemo, split properties into primitive dependencies, or compare values manually using a custom comparison ref.

Interviewer Note: 💡 Tests candidate's understanding of reference equality checks in React hooks.

Tricky Question #4: Why does accessing reference values inside useEffect without adding them to the dependency array trigger linter warnings?

Level: Tricky Question | Category: Hooks & State | Time: 10 mins

Expected Answer

The eslint-plugin-react-hooks rule flags any variables referenced inside useEffect that are missing from the dependency array. If these variables change, the hook will not execute, leading to stale data bugs. Following the linter is required to prevent synchronization errors between states and effects.

Interviewer Note: 💡 Look for their compliance with the React 'Rules of Hooks' linting guidelines.

Tricky Question #5: Why does using a React component inside a loop without a key or using a random number key cause input fields to lose focus on typing?

Level: Tricky Question | Category: Fundamentals | Time: 10 mins

Expected Answer

Using random values (like Math.random()) as keys causes React's diffing algorithm to treat the component as a brand-new element on every render. As a result, React unmounts the old component and mounts a new one, destroying its DOM state and causing input fields to lose focus immediately on typing.

Interviewer Note: 💡 A classic rendering bug. Candidates must explain that stable keys are required to preserve input focus.

Tricky Question #6: Why does React 18/19 mount and unmount components twice in Dev mode under StrictMode? What side effects does this catch?

Level: Tricky Question | Category: Fundamentals | Time: 10 mins

Expected Answer

In Development mode, React's StrictMode mounts and unmounts components twice to identify side effects:

  • Side Effects: Double mounts verify that cleanup functions are configured correctly for timers, event listeners, and subscriptions.
  • Bugs Found: Uncaught memory leaks, uncleared intervals, or double-fetching errors.
Interviewer Note: 💡 Ensure they know this double-mounting behavior is completely disabled in Production builds.

Production Incident #1: E-commerce cart crashes at checkout due to unhandled promise rejections and boundary failures

Level: Production Incident | Category: Production Incidents | Time: 15 mins

Scenario

Users report that checking out crashes the entire e-commerce page, showing a blank screen instead of an error message.

Root Cause Analysis

The checkout API request failed with a network error. The promise rejection was not caught inside the action call, throwing a runtime error that crashed the rendering tree because there was no Error Boundary to capture it.

Resolution

  • Wrap the async call in a try/catch block to handle errors gracefully.
  • Configure **Error Boundaries** around critical features (like checkout panels) to prevent a localized crash from taking down the entire page.
Interviewer Note: 💡 Evaluate their strategy to handle runtime errors without crashing the main application UI.

Production Incident #2: Real-time search autocomplete triggers race conditions, overwriting search results with outdated payload responses

Level: Production Incident | Category: Production Incidents | Time: 15 mins

Scenario

Users typing in an autocomplete search input report that the final results shown sometimes match older queries they typed earlier.

Root Cause Analysis

API requests resolve at different times depending on server load and network latency. If an earlier request (e.g. search for 'a') takes longer to respond than a later request (e.g. search for 'ab'), the first request resolves last, overwriting the UI with outdated results.

Resolution

  • Cancel pending API requests using AbortController before sending new ones.
  • Or use TanStack Query, which automatically handles query cancellation and race conditions.
Interviewer Note: 💡 A common async bug. Verify they suggest request cancellation patterns rather than just debouncing inputs.

Production Incident #3: Browser memory leak crashes dashboard after repeatedly opening and closing charts modal

Level: Production Incident | Category: Production Incidents | Time: 15 mins

Scenario

A monitoring dashboard crashes the browser tab after users repeatedly open and close a modal containing real-time charts.

Root Cause Analysis

The chart component inside the modal subscribed to a global window event listener during initialization, but did not remove the listener when unmounting. The component instances remained in memory, causing usage to grow on every modal open until the browser crashed.

Resolution

  • Always return a cleanup function inside useEffect to remove listeners: window.removeEventListener(...).
Interviewer Note: 💡 Look for experience with locating memory leaks using Chrome DevTools Heap snapshots.

Production Incident #4: Dynamic routing path resolution crashes lazy-loaded chunks in production with ChunkLoadError

Level: Production Incident | Category: Production Incidents | Time: 15 mins

Scenario

Users clicking on dashboard links get a blank screen, with console logs showing ChunkLoadError: Loading chunk failed.

Root Cause Analysis

The application was updated and redeployed, replacing old compiled chunks on the server. Active users with cached pages tried to lazy-load routes that referenced the old, deleted chunks, crashing the app.

Resolution

  • Wrap lazy-loaded component imports in an Error Boundary that catches ChunkLoadError and triggers a page reload to fetch the new bundles automatically.
Interviewer Note: 💡 A common single-page application issue. Check if they have implemented fallback strategies for deployment updates.

Production Incident #5: Access token exposure in client-side Redux store allows CSRF hijacking

Level: Production Incident | Category: Production Incidents | Time: 15 mins

Scenario

An application security review identified that session tokens could be extracted from the Redux store by malicious browser extensions.

Root Cause Analysis

The application stored sensitive JWT access tokens in the global Redux store, making them accessible to any script running on the page.

Resolution

  • Store access tokens in memory (JavaScript variables) and keep refresh tokens in secure HttpOnly cookies, preventing access via client-side scripts.
Interviewer Note: 💡 Tests application security awareness. Candidates should explain token isolation principles.

Production Incident #6: Infinite re-rendering loop freezes the browser due to setting state directly in the render path

Level: Production Incident | Category: Production Incidents | Time: 15 mins

Scenario

A page freezes immediately on loading, making the browser tab completely unresponsive.

Root Cause Analysis

The component executed a state setter function (e.g. setCount) directly in its rendering path rather than wrapping it in an event handler or useEffect. This triggers a re-render on every render pass, creating an infinite rendering loop.

Resolution

  • Move state setter calls inside useEffect hooks or event handlers (like onClick).
Interviewer Note: 💡 A common beginner-to-intermediate bug. Ensure they understand React's rendering loop rules.

Frequently Asked Questions

What are the most common React interview questions?

Common React interview questions include React fundamentals, JSX, Virtual DOM, Props vs State, Hooks, Context API, Redux Toolkit, React Performance Optimization, Server Components, SSR, and React Architecture.

How should I prepare for a React interview?

Focus on React fundamentals, Hooks, state management, component design, performance optimization, debugging, and practical project experience. Senior candidates should also prepare for architecture and system design discussions.

What React topics are asked for 2–5 years of experience?

Interviewers commonly ask about JSX, Components, Props, State, Hooks, React Router, Context API, Forms, Redux Toolkit, Error Boundaries, and Performance Optimization.

What React topics are asked for senior developers?

Senior React interviews typically cover Reconciliation, Fiber Architecture, Concurrent Rendering, SSR, CSR, Hydration, React Query, State Management Strategies, Performance Tuning, and Production Debugging.

What is the difference between React and Angular?

React is a UI library focused on building component-based interfaces, while Angular is a complete frontend framework that includes routing, dependency injection, forms, and many built-in features.