ReactReact Interview

React Interview: Top 200 Questions 2025 with Answers

React

Great, let’s start with the first 20 most relevant React interview questions in 2025.
This is the React Fundamentals & JSX block, with answers, examples, and explanation for the Middle/Senior level.


🔥 React Interview Masterclass: Questions 1–20

🔹 1. What is React?

Answer:
React is a declarative, efficient, and flexible JavaScript library for building UI components. It lets developers create reusable UI elements and efficiently update and render the right components when data changes.


🔹 2. What is the Virtual DOM? How does it improve performance?

Answer:
The Virtual DOM is a lightweight JS object that represents the real DOM. On state change:

  1. React creates a new Virtual DOM tree.
  2. It diffs it with the previous version.
  3. React applies only the necessary updates to the real DOM.

This minimizes expensive DOM manipulations and improves performance.


🔹 3. What is JSX? Can a browser read it directly?

Answer:
JSX is a syntax extension that looks like HTML in JS. Browsers cannot read JSX directly. It must be transpiled (e.g., by Babel) into regular JavaScript.

Example:

const element = <h1>Hello</h1>;
// Transpiles to:
React.createElement('h1', null, 'Hello');

🔹 4. What are components in React?

Answer:
Components are the building blocks of a React app. There are two main types:

  • Function components (with hooks)
  • Class components (legacy, but still used)

Each component returns JSX and manages its own state/props.


🔹 5. Difference between Functional and Class Components?

FeatureFunctional ComponentClass Component
SyntaxFunctionsclass extends React.Component
StateuseState/useReducerthis.state
LifecycleHooks (useEffect etc.)lifecycle methods (componentDidMount etc.)
Simpler, preferred❌ (legacy)

🔹 6. What are props in React?

Answer:
Props (short for “properties”) are read-only inputs passed from parent to child components. They enable component reuse.

const Welcome = ({ name }) => <h1>Hello, {name}</h1>;

🔹 7. What is state in React?

Answer:
State is a local data storage specific to a component. It can change over time and cause re-renders when updated.

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

🔹 8. Can you explain the difference between state and props?

FeaturePropsState
MutabilityRead-onlyMutable (via setter)
SourceParent componentComponent itself
PurposeConfigurationLocal dynamic data

🔹 9. What is a key in React and why is it important in lists?

Answer:
A key is a unique identifier used by React to track elements in a list during re-rendering. Without keys, React can’t efficiently diff lists.

{items.map(item => <li key={item.id}>{item.name}</li>)}

🔹 10. What is React Fragment and when do you use it?

Answer:
<React.Fragment> or <>...</> lets you return multiple elements without adding extra nodes to the DOM.

<>
  <h1>Title</h1>
  <p>Paragraph</p>
</>

🔹 11. What is the difference between React.Fragment and div?

Answer:

  • <Fragment>: No extra DOM element
  • <div>: Adds a real DOM node, which can break layouts or CSS

🔹 12. What are controlled and uncontrolled components?

  • Controlled: Input value is driven by React state
<input value={value} onChange={e => setValue(e.target.value)} />
  • Uncontrolled: Uses ref to access DOM directly
<input ref={inputRef} />

🔹 13. How does React handle events?

Answer:
React uses a synthetic event system that wraps the browser’s native events for cross-browser consistency.

<button onClick={handleClick}>Click</button>

🔹 14. How does React re-render a component?

Answer:
Re-renders are triggered by:

  • State updates (setState, useState)
  • Prop changes from parent
  • Context value changes

React re-renders the component and its children unless optimized (e.g., React.memo).


🔹 15. What is lifting state up?

Answer:
Lifting state up is moving shared state to the closest common ancestor component.


🔹 16. What are pure components?

Answer:
A pure component renders the same output for the same props and state. You can use React.memo() for functional components.

const Pure = React.memo(({ value }) => <div>{value}</div>);

🔹 17. What is the difference between React.memo and useMemo?

FeatureReact.memouseMemo
Used forMemoizing componentsMemoizing values/functions
SyntaxReact.memo(Component)useMemo(() => compute(), [deps])
Re-renders?Prevents if props don’t changePrevents recomputation unless deps change

🔹 18. What is reconciliation in React?

Answer:
Reconciliation is the diffing process React uses to determine what parts of the DOM to update when state/props change.


🔹 19. Why should you not update state directly?

state.count = 5; // ❌ won't trigger re-render
setCount(5);     // ✅ triggers re-render

Answer:
Direct mutation does not notify React to re-render. Always use setState or setX() in hooks.


🔹 20. What are higher-order components (HOCs)?

Answer:
A HOC is a function that takes a component and returns an enhanced version of it.

function withLogging(Component) {
  return function Enhanced(props) {
    console.log('Rendered');
    return <Component {...props} />;
  };
}

Great! Moving on to the React Hooks block (questions 21–50) — one of the most important for interviews in 2025, especially at the Middle/Senior level.


⚛️ React Interview Masterclass: Questions 21–50 — Hooks Deep Dive


🔹 21. What are React Hooks?

Answer:
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Introduced in React 16.8 to replace class-based patterns.


🔹 22. What are the rules of Hooks?

  1. Only call hooks at the top level (not in loops, conditions).
  2. Only call hooks in React functions (or custom hooks).

🔹 23. What does useState do?

Answer:
useState creates a piece of local state in a function component.

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

🔹 24. What is useEffect used for?

Answer:
Performs side effects in function components (e.g., data fetching, subscriptions, DOM manipulation).

useEffect(() => {
  fetchData();
}, [dependency]);

🔹 25. What is the cleanup function in useEffect?

Answer:
A function returned from useEffect to clean up resources like subscriptions or timers.

useEffect(() => {
  const timer = setInterval(...);
  return () => clearInterval(timer);
}, []);

🔹 26. Difference between useEffect(() => {}, []) and useEffect(() => {})?

  • []: Runs once after initial render (componentDidMount)
  • No []: Runs after every render

🔹 27. When does useEffect run?

Answer:
After the render is committed to the screen (not during render). It is asynchronous in nature (but the callback is not async itself).


🔹 28. Can you make useEffect callback async?

Answer:
You can’t directly make the function passed to useEffect async.

✅ Correct:

useEffect(() => {
  const fetchData = async () => { ... };
  fetchData();
}, []);

🔹 29. What is useRef and when to use it?

Answer:

  • Access DOM nodes
  • Persist values across renders without causing re-renders
const inputRef = useRef();
<input ref={inputRef} />;

🔹 30. How is useRef different from createRef?

  • useRef: Same object across renders
  • createRef: New ref on every render (bad for functional components)

🔹 31. What is useMemo used for?

Answer:
Memoizes a computed value between renders unless dependencies change.

const expensive = useMemo(() => compute(a, b), [a, b]);

🔹 32. What is useCallback used for?

Answer:
Memoizes a callback function to prevent re-creation on each render.

const handleClick = useCallback(() => { ... }, [deps]);

🔹 33. Difference between useMemo and useCallback?

  • useMemo: returns value
  • useCallback: returns function

🔹 34. What is useContext?

Answer:
Lets you subscribe to a React Context without nesting <Context.Consumer>.

const user = useContext(UserContext);

🔹 35. What is a custom Hook?

Answer:
A JS function that uses built-in hooks and encapsulates reusable logic.

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return width;
}

🔹 36. Can you use hooks in regular JS functions or classes?

No. Hooks only work inside:

  • React function components
  • Other custom hooks

🔹 37. How to prevent infinite loops in useEffect?

Answer:
Use proper dependencies. Avoid putting non-stable references like functions or objects.


🔹 38. What happens if you update state inside useEffect with no dependencies?

Answer:
It triggers re-render, and the effect runs again — infinite loop.


🔹 39. Can you conditionally call a hook?

Answer:
No. Hooks must be called in the same order on every render. Use conditions inside the hook, not around it.


🔹 40. How does useReducer work?

Answer:
It’s an alternative to useState, useful for complex state logic or when next state depends on previous state.

const [state, dispatch] = useReducer(reducer, initialState);

🔹 41. useState vs useReducer?

FeatureuseStateuseReducer
Simpler state
Complex logic
Multiple updates in one

🔹 42. What are stale closures in hooks?

Answer:
When closures inside hooks refer to outdated state/props, causing bugs (especially in setInterval, event listeners).

Use useRef or closures carefully.


🔹 43. How to debounce input in React using hooks?

Example with useEffect and setTimeout:

useEffect(() => {
  const handler = setTimeout(() => {
    search(query);
  }, 500);
  return () => clearTimeout(handler);
}, [query]);

🔹 44. How to fetch data in useEffect properly?

useEffect(() => {
  let isMounted = true;
  const fetchData = async () => {
    const res = await fetch(...);
    if (isMounted) setData(await res.json());
  };
  fetchData();
  return () => (isMounted = false);
}, []);

🔹 45. What is useLayoutEffect and how is it different from useEffect?

HookRuns
useEffectAfter paint
useLayoutEffectBefore paint (blocking)

Used for layout measurements, scroll syncing, etc.


🔹 46. Is it bad to use multiple useEffect calls?

No. It is encouraged — separate concerns in multiple effects.


🔹 47. How to memoize a component with hooks?

Combine React.memo with useCallback / useMemo.


🔹 48. How to share state between components using hooks?

  • Use Context + useContext
  • Global state (Redux, Zustand, Jotai)

🔹 49. Can hooks replace Redux or other state libraries?

Partially. For simple apps, hooks + context are enough. For large apps with shared/global state, use Redux/Zustand.


🔹 50. What libraries or tools extend the capabilities of hooks?

  • React Query / TanStack Query – caching & fetching
  • Zustand – global store
  • Jotai, Recoil – atomic state
  • SWR – data fetching
  • React Hook Form – forms

Let’s move on to one of the most discussed blocks in interviews: State Management (Redux, Context API, Zustand, etc.)


💡 React Interview Masterclass: Questions 51–75

🔹 State Management — Redux, Context API, Zustand, Performance


🔹 51. What are the different types of state in a React app?

Answer:

  1. Local stateuseState, useReducer
  2. Global state – Context API, Redux, Zustand
  3. Server state – React Query, SWR
  4. URL state – React Router (useParams, useLocation)

🔹 52. When should you use Redux instead of Context API?

Answer:
Use Redux when:

  • State logic is complex (middleware, devtools, normalization)
  • Many components need access to and modify global state
  • You need time-travel debugging, logging, middleware

Use Context when:

  • The global state is small and changes rarely (theme, auth)

🔹 53. What are the main concepts of Redux?

  1. Store – holds the state
  2. Actions – plain objects with a type
  3. Reducers – pure functions to update state
  4. Dispatch – sends actions to reducers
  5. Middleware – for async logic (e.g., redux-thunk)

🔹 54. What is a reducer in Redux?

A pure function that receives (state, action) and returns a new state.

function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    default:
      return state;
  }
}

🔹 55. What are Redux middlewares?

Functions that intercept actions between dispatch and reducer.
Used for logging, async flows (e.g., redux-thunk, redux-saga).


🔹 56. What is redux-thunk?

Middleware that lets you dispatch async functions instead of plain actions.

const fetchUser = () => async (dispatch) => {
  const res = await fetch("/user");
  const data = await res.json();
  dispatch({ type: "USER_LOADED", payload: data });
};

🔹 57. What is the role of useSelector and useDispatch in react-redux?

  • useSelector: selects data from the Redux store
  • useDispatch: sends actions to the store

🔹 58. How is Zustand different from Redux?

FeatureZustandRedux
BoilerplateMinimalVerbose
SetupNo provider neededNeeds Provider
AsyncNative supportNeeds middleware
APIHook-basedActions & reducers

🔹 59. How do you define a Zustand store?

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

🔹 60. How to persist Zustand state across sessions?

Use middleware like persist:

import { persist } from 'zustand/middleware';

const useStore = create(
  persist(
    (set) => ({ ... }),
    { name: 'my-storage-key' }
  )
);

🔹 61. What is Context API?

Built-in React mechanism to pass data down the component tree without props drilling.

const ThemeContext = React.createContext();

🔹 62. How to use Context in React?

  1. Create context
  2. Wrap app with provider
  3. Use useContext() in child
const theme = useContext(ThemeContext);

🔹 63. Pitfalls of Context API?

  • Triggers re-renders on any value change for all consumers
  • No partial updates
  • Bad for high-frequency updates (e.g. form inputs)

🔹 64. How to optimize performance when using Context?

  • Split context into smaller contexts
  • Use memoized values in Provider
  • Use libraries like use-context-selector

🔹 65. Can you update multiple states at once in Redux or Zustand?

✅ In Zustand, yes (batched by default).
Redux needs to handle batching carefully (React 18 helps with auto batching).


🔹 66. What is immer and how is it used in Redux Toolkit?

immer allows writing mutable code that safely returns immutable updates.

state.count++  // valid in Redux Toolkit with immer

🔹 67. What is Redux Toolkit?

A modern, opinionated way to use Redux. Features:

  • Less boilerplate
  • createSlice, createAsyncThunk
  • Built-in immer, devtools, batching

🔹 68. What is createSlice in Redux Toolkit?

It creates action creators + reducers automatically from one config.

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
  },
});

🔹 69. What is createAsyncThunk?

Handles async logic inside Redux Toolkit with minimal setup.

const fetchUser = createAsyncThunk('user/fetch', async () => {
  const res = await fetch('/user');
  return await res.json();
});

🔹 70. How to prevent unnecessary re-renders when using Redux or Zustand?

  • Use selectors to pick only necessary state
  • Memoize components
  • Avoid inline functions/objects
  • Use shallow equality comparison

🔹 71. What is the difference between global and local state?

TypeLocalGlobal
ScopeComponentEntire App
AccessuseState, useReducerRedux, Zustand, Context
PurposeUI stateShared logic/data

🔹 72. How do you reset Redux or Zustand state?

Redux:

dispatch({ type: 'RESET' });

Zustand:

useStore.getState().reset();

🔹 73. Can you use both Redux and Context API together?

Yes, e.g., Context for theme, Redux for business logic.


🔹 74. What is selective context (e.g., use-context-selector)?

An advanced version of Context API that prevents re-rendering all consumers when only part of the context changes.


🔹 75. What are some modern alternatives to Redux?

  • Zustand
  • Jotai
  • Recoil
  • MobX
  • Valtio
  • React Query (for server state)

Let’s continue! In this block 76–100 — Routing, Forms & Validation, we will cover all the relevant questions about React Router v6.22+, react-hook-form, Zod/Yup, and practical scenarios that often appear in interviews in 2025.


🌐 React Interview Masterclass: Questions 76–100

Routing, Forms, and Validation (React Router, RHF, Zod/Yup)


🔹 76. What is React Router and why is it used?

Answer:
React Router is a standard routing library for React. It enables client-side routing, allowing your app to render different components based on the URL, without refreshing the page.


🔹 77. What’s new in React Router v6+?

Highlights:

  • Nested routes by default
  • <Routes> replaces <Switch>
  • Route objects (for data loaders, actions)
  • Data APIs: loader, action, useLoaderData, etc.
  • Error handling via errorElement

🔹 78. What is the difference between <Switch> and <Routes>?

Answer:
In React Router v6, <Switch> is replaced by <Routes>.

  • <Switch> renders the first match
  • <Routes> requires element props and matches exactly
<Routes>
  <Route path="/" element={<Home />} />
</Routes>

🔹 79. How do you define nested routes in React Router v6?

<Routes>
  <Route path="/dashboard" element={<Dashboard />}>
    <Route path="settings" element={<Settings />} />
  </Route>
</Routes>

Inside Dashboard.jsx, use <Outlet /> to render nested content.


🔹 80. What is <Outlet /> in React Router?

Answer:
A placeholder for nested route content.
Think of it as a slot where child components render inside the parent layout.


🔹 81. How do you programmatically navigate in React Router v6?

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/dashboard");

🔹 82. How to access route params in React Router v6?

const { id } = useParams();

🔹 83. How to handle 404 routes?

<Route path="*" element={<NotFound />} />

🔹 84. How to handle route protection (Private Routes)?

Use Navigate component:

const PrivateRoute = ({ children }) => {
  return isLoggedIn ? children : <Navigate to="/login" />;
};

🔹 85. What is lazy loading in routing and how to implement it?

Code-splitting routes using React.lazy:

const About = React.lazy(() => import('./About'));
<Route path="/about" element={<Suspense fallback={<Loading />}><About /></Suspense>} />

🔹 86. How to create a form in React using native state?

const [formData, setFormData] = useState({ name: "", email: "" });
<input value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} />

🔹 87. Why use react-hook-form over native state for forms?

Benefits:

  • Zero re-renders on input
  • Easy validation
  • Built-in integration with Yup/Zod
  • Smaller bundle size

🔹 88. How to register a field in react-hook-form?

const { register } = useForm();
<input {...register("email")} />

🔹 89. How to get form values and submit in react-hook-form?

const { register, handleSubmit } = useForm();
const onSubmit = (data) => console.log(data);
<form onSubmit={handleSubmit(onSubmit)} />

🔹 90. How to apply validation in react-hook-form without a schema?

<input {...register("email", { required: true, pattern: /^\S+@\S+$/i })} />

🔹 91. What is schema-based validation and how to implement it with RHF + Zod?

const schema = z.object({
  email: z.string().email(),
});

const { register, handleSubmit } = useForm({ resolver: zodResolver(schema) });

🔹 92. Difference between Yup and Zod?

FeatureYupZod
TypeScript-first
PerformanceSlowerFaster
API styleObject-orientedFunctional
Better DX✅ Zod wins for TS users

🔹 93. How to show errors in react-hook-form?

{errors.email && <span>Email is required</span>}

🔹 94. How to watch input values in react-hook-form?

const { watch } = useForm();
const password = watch("password");

🔹 95. How to reset or prefill a form in react-hook-form?

const { reset } = useForm();
reset({ name: "John", email: "test@example.com" });

🔹 96. How to integrate file inputs with react-hook-form?

<input type="file" {...register("file")} />

🔹 97. How to create dynamic fields (e.g., add/remove inputs) with RHF?

Use useFieldArray():

const { fields, append, remove } = useFieldArray({ control, name: "items" });

🔹 98. How to handle multiple forms on the same page with react-hook-form?

Use multiple useForm() hooks or isolate form state using FormProvider.


🔹 99. How to validate one field based on another?

Use schema-level validation in Zod/Yup:

z.object({
  password: z.string(),
  confirm: z.string()
}).refine(data => data.password === data.confirm, {
  message: "Passwords do not match",
  path: ["confirm"]
});

🔹 100. How to improve form performance in React?

✅ Use:

  • react-hook-form instead of useState
  • Memoized components (React.memo)
  • Debounced inputs (useDebounce)
  • Schema validation (Zod) instead of manual

Great! This is a super important block for the Middle/Senior level — it is often asked in interviews to test not just your knowledge of React, but also your architectural thinking, optimization, and testing skills.


⚙️ React Interview Masterclass: Questions 101–140

🔹 Performance Optimization, Patterns, Testing (Jest + RTL)


🧠 Performance Optimization (101–115)


🔹 101. What is React.memo and when to use it?

Answer:
React.memo is a higher-order component that prevents re-rendering if props haven’t changed (shallow comparison).

const MemoizedComponent = React.memo(MyComponent);

Use it for pure functional components with static or primitive props.


🔹 102. When does React.memo not help?

  • When props change on every render (e.g., new object/function)
  • When children re-render anyway
  • When comparison cost is higher than re-rendering

🔹 103. What is the difference between React.memo and useMemo?

FeatureReact.memouseMemo
What it memoizesWhole componentReturned value (primitive/object)
Used forAvoid re-renderAvoid recalculation

🔹 104. How do you avoid unnecessary re-renders in React?

✅ Use:

  • React.memo, useMemo, useCallback
  • Splitting contexts
  • Key-based list rendering
  • Avoiding anonymous functions in props

🔹 105. What is useCallback and how does it help with performance?

Memoizes a function reference so it doesn’t change on every render.

const handleClick = useCallback(() => doSomething(), []);

🔹 106. When should you not use useMemo?

When the calculation is cheap or dependencies change frequently — it can hurt performance due to overhead.


🔹 107. What are some ways to lazy-load components in React?

  • React.lazy() + <Suspense>
  • Dynamic imports with import()
const LazyComp = React.lazy(() => import('./Component'));

🔹 108. What is code splitting in React?

Code splitting allows loading parts of your app on demand, improving performance and reducing initial bundle size.


🔹 109. What are concurrent features in React?

Features introduced with React 18:

  • Automatic batching
  • Concurrent rendering
  • useTransition, startTransition
  • Suspense for data

🔹 110. What is useTransition and why is it useful?

useTransition marks part of state updates as non-urgent:

const [isPending, startTransition] = useTransition();
startTransition(() => setQuery(input));

Helps avoid UI blocking in expensive operations.


🔹 111. What is Suspense and what can it suspend?

Suspense lets you “wait” for async operations like:

  • Lazy-loaded components
  • Data loading (with concurrent features or libraries like React Query)

🔹 112. What is hydration in React?

Hydration is the process where React attaches event listeners to server-rendered HTML.


🔹 113. How to measure performance in React apps?

✅ Tools:

  • Chrome DevTools Profiler
  • React DevTools Profiler tab
  • Lighthouse
  • why-did-you-render

🔹 114. What is the key prop used for in lists?

Helps React identify and update changed elements efficiently during re-renders.


🔹 115. How to optimize large lists?

✅ Use:

  • react-window, react-virtualized
  • Pagination
  • Infinite scroll with IntersectionObserver

🧩 Design Patterns in React (116–125)


🔹 116. What are Higher Order Components (HOCs)?

A function that takes a component and returns a new component.

const withLogger = (Component) => (props) => {
  console.log("Rendered!");
  return <Component {...props} />;
};

🔹 117. What is the difference between HOC and Render Props?

PatternHOCRender Props
ReusabilityWrappingPassing a function
ExamplewithAuth(Component){(data) => <Child data={data} />}

🔹 118. What are compound components in React?

Components that work together and share implicit state via context.

<Tabs>
  <Tabs.List />
  <Tabs.Panel />
</Tabs>

🔹 119. What are controlled vs uncontrolled components?

  • Controlled: React state drives value
  • Uncontrolled: Native form element with ref access

🔹 120. What is Inversion of Control in React patterns?

Letting parent control logic by passing render functions (used in Render Props, Context, or slots).


🔹 121. What is a slot pattern in React?

Use children as a render placeholder. React children can be:

  • JSX
  • Function
  • Element array

🔹 122. What is state colocation and why is it useful?

Placing state close to where it’s used, reduces prop drilling and improves maintainability.


🔹 123. What is prop drilling and how to avoid it?

Passing data through multiple layers unnecessarily.

Avoid with:

  • Context API
  • Zustand / Redux
  • Custom hooks

🔹 124. What is function as children?

Also known as Render Props:

<DataFetcher url="/api">
  {(data) => <Table rows={data} />}
</DataFetcher>

🔹 125. What is Portal in React and when to use it?

Allows rendering a component outside the main DOM tree.

ReactDOM.createPortal(<Modal />, document.getElementById("modal-root"));

Used for modals, tooltips, dropdowns.


🧪 Testing React Apps (126–140)


🔹 126. What is the difference between unit and integration testing in React?

  • Unit: Testing small components in isolation
  • Integration: Testing interactions between components and behavior

🔹 127. What is Jest?

A JavaScript testing framework by Meta. Used with React for unit/integration testing.


🔹 128. What is React Testing Library (RTL)?

A testing utility focused on testing components as a user would interact with them.


🔹 129. How do you render a component in RTL?

import { render } from '@testing-library/react';
render(<MyComponent />);

🔹 130. How to query elements in RTL?

Prefer query by role/text:

screen.getByRole("button", { name: /submit/i });

🔹 131. How to simulate a click in RTL?

fireEvent.click(screen.getByText("Submit"));

🔹 132. How to test forms with React Testing Library?

fireEvent.change(screen.getByLabelText("Email"), {
  target: { value: "test@example.com" }
});
fireEvent.submit(formElement);

🔹 133. What is mocking and why is it used?

Mocking replaces real dependencies (like APIs) in tests.

Used to:

  • Avoid real network calls
  • Test edge cases
  • Improve test speed

🔹 134. How to mock API requests in tests?

Use jest.mock() or libraries like MSW (Mock Service Worker).


🔹 135. What is MSW (Mock Service Worker)?

Intercepts real network requests at runtime and returns mocked responses.

Advantages:

  • Closer to real usage
  • Works with fetch/XHR
  • Reusable in dev/test

🔹 136. How to test asynchronous behavior?

Use waitFor, findBy..., or async/await.

await waitFor(() => expect(screen.getByText("Loaded")).toBeInTheDocument());

🔹 137. What is act() in React testing?

Ensures all updates related to state/effects have been flushed before assertions.


🔹 138. How to test a custom hook?

Use @testing-library/react-hooks:

const { result } = renderHook(() => useCounter());

🔹 139. What is snapshot testing?

Saves a rendered component’s output and compares it on future runs to detect unexpected changes.

expect(tree).toMatchSnapshot();

🔹 140. When should you avoid snapshot testing?

When:

  • Component output changes frequently
  • Test becomes hard to maintain
  • Better tested with user-focused queries

Great! Let’s move on to the final master block – these are the topics that Senior interviewers, CTOs or architects pay attention to. Here it is important to demonstrate not just knowledge of React, but the ability to build scalable, stable and multi-client systems.


🏗️ 12. Build & Deployment in React 2025: Webpack, Vite & CI/CD

In 2025, performance and scalability are not just development concerns — they’re key to successful production. Let’s dive into how to build, optimize, and deploy React apps using modern tooling and CI/CD pipelines.

Vite vs Webpack in 2025

  • Vite is now the standard for most React apps. It uses native ESM, is blazingly fast, and supports TypeScript, Hot Module Replacement (HMR), and Tree Shaking out of the box.
  • Webpack is still used in large-scale, highly-customized enterprise apps (e.g., mono repos, complex SSR).

🔧 Example: Building with Vite

npm run build

This creates a production-ready dist/ folder, optimized for modern browsers.

🛠️ Webpack Alternative (for custom setups)

If you’re customizing builds for micro-frontends, legacy compatibility, or SSR:

webpack --mode production

⚙️ Environment Configuration

Use .env files to manage environment variables:

VITE_API_BASE_URL=https://api.myapp.com

Access via:

const baseUrl = import.meta.env.VITE_API_BASE_URL;

🚀 Deployment Options in 2025

PlatformIdeal ForFeatures
VercelReact/Next.js appsInstant CI/CD, preview URLs, edge functions
NetlifySPAs, JAMstackFree hosting, deploy previews, forms
RenderFullstack appsDocker, background workers, databases
RailwayFull MERN stacksPostgreSQL/Mongo + Node hosting
Docker + NginxSelf-hosted infraHigh control, scalable, secure

🤖 CI/CD Integration (GitHub Actions)

CI/CD pipelines ensure automated testing and deployment on every commit or merge.

🧪 Example: GitHub Actions for React + Vite

name: React CI

on:
push:
branches: [main]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: latest
- run: pnpm install
- run: pnpm run build

🌐 13. Fullstack React + Node.js (MERN) Integration in 2025

In 2025, the MERN stack (MongoDB, Express, React, Node.js) remains one of the most in-demand fullstack configurations — especially for building MVPs, SaaS products, and admin panels.

Let’s walk through how to build a real-world fullstack React app with backend integration.


🧰 Fullstack Stack Setup

LayerTech
FrontendReact 19 + Vite + Tailwind CSS + React Query
BackendNode.js + Express
DatabaseMongoDB Atlas
AuthJWT / OAuth2
Dev ToolsTypeScript, Prettier, ESLint, Husky

🔌 API Integration Pattern

Use a clean separation between API services and UI components.

api/users.ts

export const getUser = async (id: string) => {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error('Failed to load user');
return res.json();
};

In your component:

const { data, error } = useQuery(['user', id], () => getUser(id));

🔐 Auth Flow with JWT

  1. User logs in → Frontend sends credentials to backend.
  2. Backend returns a JWT stored in HttpOnly cookie.
  3. On refresh, frontend fetches /auth/me to get user info.

🛠 Backend Sample (Express + TypeScript)

app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
const user = await findUserByEmail(email);
if (!user || !verifyPassword(user, password)) {
return res.status(401).send('Unauthorized');
}

const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
res.cookie('token', token, { httpOnly: true });
res.json({ user });
});

⚛️ Frontend State Management: React Query

Avoid redundant Redux boilerplate. Use TanStack Query for data fetching, caching, and mutation.

const mutation = useMutation(loginUser, {
onSuccess: () => queryClient.invalidateQueries('me'),
});

📂 Suggested Folder Structure for Fullstack Project

my-app/
├── client/ # React + Vite
│ ├── src/
│ └── public/
├── server/ # Node + Express
│ ├── src/
│ └── .env
├── shared/ # Types/interfaces
├── docker/
└── README.md

🐳 Docker Deployment (Frontend + Backend)

Dockerfile (React Frontend)

FROM node:18
WORKDIR /app
COPY . .
RUN npm install && npm run build
RUN npm install -g serve
CMD ["serve", "-s", "dist"]

Docker Compose

services:
client:
build: ./client
ports:
- "3000:3000"
server:
build: ./server
ports:
- "5000:5000"

🌍 Connecting Frontend to Backend in Prod

Use environment variables in Vite:

VITE_API_URL=https://api.myapp.com

In code:

fetch(`${import.meta.env.VITE_API_URL}/users`)

🚀 Bonus: Fullstack Deployment Options

PlatformFeatures
RenderDeploy backend + frontend + database
RailwayDeploy React + Node + Mongo in 1 click
Vercel + API ProxyHost frontend, proxy API to backend
Docker + VPSFull control, great for SaaS MVPs

✅ Conclusion

With Vite, React Query, CI/CD, and MERN architecture, React development in 2025 is faster and more powerful than ever before. Here’s your full checklist:

✅ Use Vite for lightning-fast builds
✅ Deploy via GitHub Actions, Vercel, or Render
✅ Use JWT + HttpOnly Cookies for secure auth
✅ Use TanStack Query for scalable data fetching
✅ Dockerize your app for production readiness
✅ Keep backend and frontend loosely coupled

These fullstack and deployment best practices will help you ship high-performance, real-world React applications that are maintainable, secure, and scalable.

🧱 React Interview Masterclass: Questions 176–200

System Design, Scaling, and Advanced Scenarios


⚖️ Load Balancing, Caching, Stress (176–182)


🔹 176. How would you scale a React app to handle high traffic?

  • Use CDNs to serve static assets
  • SSR/ISR with Next.js for pre-rendering
  • Lazy loading + code splitting
  • Cache APIs + use React Query
  • Horizontal scaling with load balancer

🔹 177. How do CDNs improve React app performance?

CDNs (e.g., Cloudflare, Vercel edge) cache and deliver content from edge locations, reducing latency, improving TTFB, and offloading your origin server.


🔹 178. What types of caching do you apply in fullstack apps?

  • Browser cache (headers, service workers)
  • CDN cache (Cloudflare, Akamai)
  • API cache (Redis, Varnish)
  • Data cache (React Query, SWR)

🔹 179. What is HTTP caching and how to use it?

Using headers like Cache-Control, ETag, Expires, you can instruct browser/CDN to cache assets or responses.

Cache-Control: public, max-age=86400

🔹 180. What tools do you use to test performance under load?

  • Lighthouse (frontend)
  • K6, Artillery (API load)
  • React Profiler, Web Vitals
  • Datadog / New Relic for fullstack metrics

🔹 181. How to prevent React app from crashing under load?

  • Debounce high-frequency events
  • Use pagination/virtualization for big lists
  • Avoid memory leaks (clean up effects)
  • Apply graceful fallback UIs with Suspense + ErrorBoundary

🔹 182. How to handle rate limiting on frontend/backend?

  • Backend: throttle via API Gateway, Redis buckets
  • Frontend: debounce inputs, exponential backoff for retries

🌍 Edge Rendering, Serverless, Modern Deploys (183–187)


🔹 183. What is edge rendering in Next.js?

Rendering pages close to the user (on CDN/edge location) for better latency.
Use export const runtime = 'edge' inside route files.


🔹 184. What’s the difference between edge functions and serverless functions?

FeatureEdgeServerless
LocationGlobal/CDNRegion-based
Startup timeInstantCold start possible
Use casePersonalization, A/BDB ops, heavy lifting

🔹 185. How do serverless platforms (Vercel, Netlify) benefit React devs?

  • Zero config deploy
  • Built-in CI/CD
  • Serverless + edge functions
  • Caching, domains, preview URLs

🔹 186. How to handle database access in serverless architecture?

  • Use a pooled proxy (e.g., Neon, Supabase edge functions)
  • Avoid direct DB from client
  • Use API route/functions as backend middleware

🔹 187. How to use environment variables securely in frontend?

  • In Next.js: NEXT_PUBLIC_ prefix for public use
  • Keep private keys in backend API
  • Use .env.local, never commit secrets

🧩 Multi-Tenant, Micro Frontends (188–192)


🔹 188. What is multi-tenancy and how do you build it in React?

Serving multiple clients (tenants) from the same app instance.

Techniques:

  • Subdomain or path-based tenant routing
  • Tenant context for branding/config
  • Data segregation via API (e.g., tenantId in DB queries)

🔹 189. How do you dynamically theme React apps per tenant?

  • Use a ThemeProvider (styled-components, MUI)
  • Load configs from DB/API
  • Cache on load + SSR preload if needed

🔹 190. What are micro frontends and when would you use them?

Breaking large frontend apps into independently deployable pieces.

Use cases:

  • Large teams
  • Feature ownership
  • Different tech stacks

🔹 191. How to implement micro frontends in React?

  • Module Federation (Webpack 5)
  • iFrames (legacy)
  • Single-spa or import remote modules at runtime

🔹 192. What are the downsides of micro frontends?

  • Increased complexity
  • Shared state and routing challenges
  • Initial setup overhead

🌐 Internationalization & Accessibility (193–196)


🔹 193. How to implement i18n in React apps?

Use react-i18next:

  • Language detector
  • Async JSON translations
  • Context integration
t("welcome.message");

🔹 194. How to handle dynamic routing with i18n (e.g., /en, /fr)?

  • Use next-i18next
  • Prefix routes or use domain routing
  • Automatically detect locale via browser

🔹 195. How to ensure accessibility (a11y) in React?

  • Use semantic HTML (<button>, <label>)
  • ARIA attributes (aria-label)
  • Keyboard navigation
  • Use Lighthouse + axe-core

🔹 196. What tools help test a11y in React?

  • axe-core browser extension
  • Lighthouse audit
  • eslint-plugin-jsx-a11y

🧠 Real Interview Scenarios (197–200)


🔹 197. Design a multi-tenant dashboard in Next.js with role-based access.

Approach:

  • getServerSideProps validates token, role, and tenant
  • RBAC middleware
  • Theme and config loading per tenant
  • API routes with tenantId filtering

🔹 198. A page loads slowly. How do you debug and fix it?

Steps:

  • Lighthouse, DevTools → find largest blocking resources
  • Network tab → API or image bottlenecks
  • Lazy load, reduce payload, use CDN
  • Use React Profiler

🔹 199. How would you design a system with offline support?

  • Use IndexedDB, localStorage
  • Sync when online (service workers)
  • Use libraries like react-query + persistor

🔹 200. How do you ensure your app is production-ready?

✅ Checklist:

  • Error boundaries + fallback UIs
  • SEO + meta tags
  • Analytics (GA, Posthog)
  • CI/CD setup with preview
  • Load tested
  • Monitoring & logging

🏁 Masterclass Complete ✅

🔹 200 of the latest interview questions from React, Next.js, architecture, and production.

Related posts
ReactReact Interview

React.js Interview Questions 2025: The Ultimate Guide for Frontend Developers

React.js continues to dominate the frontend development landscape in 2025, making it essential for…
Read more
ReactReact Interview

🧠 Top React Interview Questions and Answers for 2025: The Ultimate Developer’s Guide

Introduction If you’re preparing for a React interview in 2025, you’re in the right…
Read more
ReactReact Interview

🚀 React Tutorial 2025: The Ultimate Guide to Building Modern Web Apps

Introduction React has firmly established itself as the cornerstone of modern front-end…
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *