Level: IntermediateInterview

React JS Interview Questions: 110 Most Asked, with Full Answers

Updated 59 min read
React JS Interview Questions featured image: topics from JSX to React 19

React JS interview questions show up in almost every frontend and full-stack interview, because React is still the most used library for building web user interfaces. This post gives you 110 of the most asked questions, grouped from basic to advanced, and every one of them now has a full answer in simple English, with code examples you can try.

Full-stack rounds often ask how the frontend talks to the backend, so the Go REST API tutorial and the Go REST API interview questions are good companions. For a short warm-up, also read our earlier React questions post. The answers here match React 19 and current best practice.

What Do React JS Interview Questions Cover?

React is a JavaScript library for building user interfaces from small, reusable pieces called components. You describe what the screen should look like for the current data, and React updates the page when that data changes.

Think of LEGO bricks. Each brick is a small component, such as a button or a card. You snap bricks together into bigger parts, such as a product list, and then into a full page. If one brick changes colour, you only swap that brick, not the whole model.

Most React JS interview questions test six areas: JSX and components, props and state, hooks, rendering and performance, routing and data, and testing. Senior rounds add React 19 features, architecture and real debugging scenarios.

How to Use These React JS Interview Questions

Do not try to learn 110 answers by heart. Instead, use the list in three passes.

  1. First, read each question and try to answer it in two or three sentences before you read the answer.
  2. Next, practise those out loud, with a small example you have built.
  3. Finally, type the components from the hands-on section into a new Vite project and run them.

The table below shows how interview rounds usually use these questions.

RoundFocusQuestion range
Phone screenJSX, components, props, stateQ1 to Q40
Technical roundHooks, rendering, forms, routingQ41 to Q90
Senior roundReact 19, testing, scenariosQ91 to Q110
Live codingBuild a small componentHands-on section

How React Works

React follows the same cycle every time data changes. Something updates state, React calls your component again, compares the new result with the old one, and changes only the parts of the real page that differ.

React JS interview questions diagram showing state change, render, reconciliation, commit and effects
A state change re-runs the component, React compares the result with the last render, updates only the changed DOM nodes, then runs effects.

This comparison step is called reconciliation. React builds a light copy of the UI in memory (often called the virtual DOM), finds the difference, and then updates the browser DOM in one batch. After that, your effects run, for example to fetch data or start a timer.

Basic React JS Interview Questions with Answers

These React JS interview questions check that you know the core ideas and terms. Freshers should be able to answer all of them, so type the small examples into a test project as you read.

React is an open-source JavaScript library for building user interfaces, made by Meta (Facebook) and released in 2013. You build the screen from small, reusable pieces called components, and React updates the page efficiently when your data changes.

It is popular for several reasons.

  • Components: you build once and reuse everywhere, such as a Button or ProductCard.
  • Declarative style: you describe what the UI should look like, and React handles the DOM updates.
  • Huge ecosystem: routers, state libraries, UI kits and frameworks like Next.js.
  • Strong job market and community: lots of tutorials, tools and developers.
  • React Native: the same ideas work for mobile apps.

Q2. Is React a library or a framework?

React itself is a library. It focuses on one job: building the UI. It does not decide how you handle routing, data fetching, forms or project structure, so you pick other tools for those.

That is why frameworks are built on top of React, such as Next.js and React Router in framework mode. They add routing, server rendering, data loading and build setup. So you can say “React is a UI library, and React frameworks turn it into a full solution”.

Q3. What is a single-page application (SPA)?

A single-page application loads one HTML page once, then updates the content with JavaScript as the user moves around, without full page reloads. When you click a link, the app changes the URL and shows a new view, and only data is fetched from the server.

SPAs feel fast and smooth, like a mobile app. The downsides are a larger first JavaScript download and weaker SEO if nothing is rendered on the server. Modern React frameworks fix this with server rendering, while keeping the SPA feel after the first load.

Q4. What is JSX?

JSX is a syntax extension for JavaScript that lets you write HTML-like code inside JavaScript. It makes UI code easy to read, because the markup and the logic for a component sit together.

function Greeting({ name }) {
  const hour = new Date().getHours();
  return (
    <h1 className="title">
      {hour < 12 ? "Good morning" : "Hello"}, {name}!
    </h1>
  );
}

Anything inside curly braces {} is a JavaScript expression. JSX is not HTML, so attributes use camelCase names like className, onClick and htmlFor.

Q5. Why does JSX need to be compiled, and what does it turn into?

Browsers do not understand JSX, so a build tool such as Vite (using esbuild or SWC) or Babel turns it into normal JavaScript before it runs. Each JSX tag becomes a function call that creates a React element, which is a plain object describing what to show.

// You write:
const el = <button className="buy">Buy now</button>;

// It becomes roughly (modern automatic JSX runtime):
import { jsx } from "react/jsx-runtime";
const el = jsx("button", { className: "buy", children: "Buy now" });

Older setups used React.createElement, which is why old files always had import React from "react". With the newer JSX runtime, that import is not needed.

Q6. What is the virtual DOM?

The virtual DOM is a lightweight copy of the UI kept in memory as plain JavaScript objects. When state changes, React creates a new virtual tree, compares it with the previous one, works out the smallest set of changes, and then updates the real browser DOM.

Think of editing a document by first writing your changes on a draft, then copying only the changed lines to the final copy. Updating the real DOM is slow compared with working with JavaScript objects, so this keeps updates efficient and lets you write simple code that “re-renders everything”.

Q7. How is the virtual DOM different from the real DOM?

The real DOM is the browser’s actual page structure that users see. The virtual DOM is React’s in-memory description of that page.

FeatureReal DOMVirtual DOM
What it isBrowser objects that draw the pagePlain JavaScript objects
Speed to changeSlower, can cause layout and repaintFast, just objects in memory
Who updates itBrowser APIsReact, during render
Shown to usersYesNo

So React changes the virtual DOM freely and touches the real DOM only where something really changed.

Q8. What is reconciliation?

Reconciliation is the process React uses to compare the new virtual tree with the previous one and decide what to change in the real DOM. React uses a fast comparison based on two simple rules.

  • If an element’s type changes, such as a div becoming a section, React throws away the old part and builds a new one.
  • In lists, React uses key to match old and new items, so it can move, add or remove the right ones.

After reconciliation, the commit phase applies the changes to the real DOM, and then effects run.

Q9. What is a component?

A component is a reusable piece of UI, written as a JavaScript function that returns JSX. It can take inputs (props), keep its own data (state) and contain other components. Components are like custom HTML tags you invent for your app.

function ProductCard({ name, price }) {
  return (
    <div className="card">
      <h3>{name}</h3>
      <p>₹{price}</p>
    </div>
  );
}

// Use it like a tag
<ProductCard name="Notebook" price={120} />

Q10. What is the difference between function components and class components?

Function components are plain functions that return JSX and use hooks for state and side effects. Class components extend React.Component, keep state in this.state and use lifecycle methods like componentDidMount.

FeatureFunction componentClass component
SyntaxA functionA class with render()
StateuseState, useReducerthis.state, this.setState
Side effectsuseEffectLifecycle methods
Code sizeShorterLonger, uses this
New featuresAll new React featuresFew new features

Both still work, but new code uses function components. The one thing that still needs a class is an error boundary.

Q11. Why do most teams use function components today?

Function components with hooks are shorter, easier to read and easier to test. You do not need to deal with this binding, and related logic stays together instead of being split across lifecycle methods.

Hooks also make it easy to share logic with custom hooks, which replaced older patterns like higher-order components and render props in most cases. All new React features, such as use, Server Components and Actions, are built for function components.

Q12. Why must a component name start with a capital letter?

JSX uses the first letter to decide what a tag is. A lowercase tag, such as <div> or <button>, is treated as a built-in HTML element. A capitalised tag, such as <ProductCard>, is treated as a component you defined.

So if you name a component productCard, React tries to create an HTML element called productcard, which does nothing. Always use PascalCase for component names.

Q13. What is a React Fragment, and why use one?

A component must return one parent element. A Fragment lets you group several elements without adding an extra div to the page. You write it as <>...</> or <Fragment>...</Fragment>.

function TableRow({ name, price }) {
  return (
    <>
      <td>{name}</td>
      <td>{price}</td>
    </>
  );
}

This keeps the HTML clean and valid, for example inside tables where an extra div would break the layout. Use the long form <Fragment key={id}> when a fragment in a list needs a key.

Q14. How do you render a list in React?

Use JavaScript’s map() to turn an array of data into an array of JSX elements, and give each item a unique key.

function ProductList({ products }) {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name}: ₹{product.price}
        </li>
      ))}
    </ul>
  );
}

You can also filter() before mapping, for example to show only products in stock.

Q15. Why does each item in a list need a key?

The key tells React which item is which between renders. When the list changes, for example an item is added, removed or moved, React uses keys to match old and new items. So it can keep each item’s state and DOM node with the right data.

Without stable keys, React may reuse the wrong DOM node for an item, which causes bugs such as an input showing the text of another row. Keys must be unique among siblings and stay the same for the same item, so database IDs are ideal.

Q16. Why is using the array index as a key often a bad idea?

The index changes when items are added, removed or reordered. If you delete the first item, every other item gets a new index, so React thinks the items themselves changed. It may then keep state, such as typed text or a checkbox, attached to the wrong row.

Using the index is only safe when the list never changes order, never has items inserted or removed in the middle, and items have no state. Otherwise, use a stable ID from your data, or create one when the item is created, such as crypto.randomUUID().

Q17. How do you show something only when a condition is true?

There are a few common patterns for conditional rendering.

function Cart({ items, isLoggedIn }) {
  if (!isLoggedIn) {
    return <p>Please log in.</p>;          // early return
  }
  return (
    <div>
      {items.length > 0 && <CartList items={items} />}   {/* && */}
      {items.length === 0 ? <p>Cart is empty</p> : <CheckoutButton />} {/* ternary */}
    </div>
  );
}

Be careful with && and numbers. {count && <Badge />} shows 0 on the page when count is 0, so write {count > 0 && <Badge />} instead.

Q18. How do you add a CSS class in JSX, and why is it className?

In JSX, you use className instead of class, because class is a reserved word in JavaScript and JSX maps to DOM properties, where the property is also className.

<button className={isActive ? "tab active" : "tab"}>Orders</button>

You can also use inline styles with an object, such as style={{ color: "red", fontSize: 14 }}, CSS Modules, utility classes like Tailwind CSS, or CSS-in-JS libraries. Small helpers like clsx make joining classes easier.

Q19. How do you start a new React project today, now that Create React App is deprecated?

Create React App was officially deprecated in early 2025, so new projects should not use it. The React team now recommends two paths.

  • Use a framework for most apps: Next.js, React Router (framework mode) or Expo for mobile. You get routing, data loading and server rendering built in.
  • Use a build tool for a simple SPA or to learn: Vite is the most popular choice.
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

Q20. What are frameworks such as Next.js and React Router, and when do you need one?

React frameworks add the parts React itself leaves out, so you do not have to build them yourself.

  • Next.js: file-based routing, Server Components, server rendering, static generation, API routes and image optimisation.
  • React Router (framework mode, formerly Remix): nested routes with data loading and form actions, server rendering, and it also works as a simple client-side router.

You need a framework when your app needs SEO, fast first loads, server rendering or many pages with data loading. For an internal dashboard behind a login, a Vite SPA with React Router as a library can be enough.

Props and State React JS Interview Questions with Answers

Props and state are the heart of React. So almost every round starts with these React JS interview questions, and many “what does this print?” questions come from here.

Q21. What are props?

Props (short for properties) are the inputs a parent passes to a child component, like arguments to a function. They let you reuse one component with different data.

function Avatar({ name, size = 40 }) {
  return <img src={`/avatars/${name}.png`} alt={name} width={size} />;
}

function Profile() {
  return <Avatar name="asha" size={80} />;
}

Props can be any JavaScript value: strings, numbers, objects, arrays, functions and even JSX. Inside the component, you usually destructure them in the parameter list.

Q22. Can a child component change its props?

No. Props are read-only. A component must never change the props it receives, because they belong to the parent. React components should act like pure functions with respect to their props: the same props should give the same output.

If a child needs to change something, the parent passes down a function as a prop, such as onChange, and the child calls it. Then the parent updates its own state and passes new props down.

Q23. What is the children prop?

children is a special prop that holds whatever you put between a component’s opening and closing tags. It lets you build wrapper components, such as cards, modals and layouts, that do not know their content in advance.

function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div className="card-body">{children}</div>
    </div>
  );
}

<Card title="Order summary">
  <p>3 items</p>
  <p>Total: ₹1,250</p>
</Card>

Q24. How do you set a default value for a prop?

In function components, use JavaScript default values when you destructure the props.

function Button({ label = "Submit", variant = "primary", onClick }) {
  return <button className={`btn btn-${variant}`} onClick={onClick}>{label}</button>;
}

The default is used when the prop is missing or undefined, but not when it is null. The old defaultProps property is no longer supported for function components in React 19, so use default parameters instead.

Q25. What is prop drilling, and how do you avoid it?

Prop drilling means passing a prop through many layers of components that do not use it, just so a deep child can get it. For example, passing user from App to Layout to Sidebar to Menu to UserBadge. It makes code noisy and hard to change.

You can avoid it in a few ways.

  • Composition: pass components as children or props, so the parent renders the deep child directly.
  • Context: put shared data such as the theme or current user in a Context, and read it with useContext where needed.
  • State libraries: use Zustand, Redux Toolkit or similar for app-wide state.
  • Server state tools: use TanStack Query for data from the server, so any component can read it.

Q26. What is state?

State is data that a component owns and that can change over time, such as a counter, the text in an input, or whether a menu is open. When state changes, React re-renders the component to show the new value.

import { useState } from "react";

function LikeButton() {
  const [likes, setLikes] = useState(0);
  return <button onClick={() => setLikes(likes + 1)}>❤ {likes}</button>;
}

Each component instance has its own state. Two LikeButtons on the page keep separate counts.

Q27. What is the difference between props and state?

Props come from the parent and are read-only. State lives inside the component and changes over time with its setter. The table below sums up the main differences.

FeaturePropsState
Who owns itThe parent componentThe component itself
Can it change inside the componentNo, read-onlyYes, with the setter
DirectionFlows down to childrenLocal, can be passed down as props
Causes a re-renderWhen the parent passes new propsWhen you call the setter
ExampleA product name passed to a cardA counter or form input value
React JS interview questions comparison of props and state
Props flow down from the parent and are read-only, while state lives inside a component and changes over time.

So use props to configure a component from outside. Use state for data that the component itself changes over time. One component’s state often becomes another component’s props.

Q28. Why should you never change state directly?

React only re-renders when you call the state setter with a new value. If you change state directly, such as user.name = "Ravi" or items.push(item), React does not know anything changed, so the screen does not update. It can also break features that compare old and new values, such as React.memo.

So always create a new value and pass it to the setter: setUser({ ...user, name: "Ravi" }) or setItems([...items, item]). Treat state as read-only, just like props.

Q29. Why is a state update not visible right away in the same function?

Calling a setter does not change the state variable in the current render. It asks React to re-render with the new value. Inside the current function call, the variable still holds the old value, like a snapshot.

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

  function handleClick() {
    setCount(count + 1);
    console.log(count); // still 0 here, the new value shows in the next render
  }
  return <button onClick={handleClick}>{count}</button>;
}

If you need the new value right away, calculate it in a variable first, such as const next = count + 1; setCount(next);, and use next.

Q30. What is the updater function form, such as setCount(c => c + 1)?

Instead of a new value, you can pass a function to the setter. React calls it with the latest pending state and uses its return value. This matters when the new state depends on the old one, especially with several updates in a row.

function addThree() {
  setCount(count + 1); // uses the snapshot value
  setCount(count + 1); // same snapshot
  setCount(count + 1); // result: count + 1 only
}

function addThreeCorrect() {
  setCount((c) => c + 1);
  setCount((c) => c + 1);
  setCount((c) => c + 1); // result: count + 3
}

So use the updater form whenever the next state is based on the previous state.

Q31. What is lifting state up?

Lifting state up means moving shared state to the closest common parent of the components that need it. The parent then passes the state down as props, plus functions to change it.

For example, a SearchBox and a ProductList both need the search text. If each kept its own copy, they would get out of sync. So you keep query in their parent ProductPage, pass query and onQueryChange to SearchBox, and pass query to ProductList. This keeps one source of truth.

Q32. What is a controlled component?

A controlled component is a form input whose value comes from React state. The input shows the state value, and every change goes through an onChange handler that updates the state.

function EmailInput() {
  const [email, setEmail] = useState("");
  return (
    <input
      type="email"
      value={email}
      onChange={(e) => setEmail(e.target.value)}
    />
  );
}

So React is the single source of truth, which makes it easy to validate as the user types, format input, or disable a button until the form is valid.

Q33. What is an uncontrolled component?

An uncontrolled component keeps its own value inside the DOM, like normal HTML. You set a starting value with defaultValue, and read the value when needed, for example with a ref or from the form data on submit.

function NewsletterForm() {
  function handleSubmit(e) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    console.log(data.get("email"));
  }
  return (
    <form onSubmit={handleSubmit}>
      <input name="email" type="email" defaultValue="" />
      <button>Subscribe</button>
    </form>
  );
}

It means less code and fewer re-renders, and it fits well with React 19 form Actions. File inputs are always uncontrolled.

Q34. How do you handle events such as onClick and onChange?

You pass a function to an event prop written in camelCase, such as onClick, onChange or onSubmit. Pass the function itself, do not call it.

function SaveButton() {
  function handleClick(event) {
    console.log("Saved!", event.type);
  }
  return <button onClick={handleClick}>Save</button>; // not handleClick()
}

Writing onClick={handleClick()} is a common mistake. It calls the function during render instead of on click. To stop a form from reloading the page, call event.preventDefault() in onSubmit.

Q35. What is a synthetic event?

A synthetic event is React’s wrapper around the browser’s native event. It has the same interface on every browser, such as e.target, e.preventDefault() and e.stopPropagation(), so your code behaves the same everywhere.

React attaches event listeners at the root of your app and sends events to your handlers (event delegation). If you need the original browser event, use e.nativeEvent.

Q36. How do you pass an argument to an event handler?

Wrap the call in an arrow function, so it runs only when the event happens.

function TodoList({ todos, onDelete }) {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>
          {todo.text}
          <button onClick={() => onDelete(todo.id)}>Delete</button>
        </li>
      ))}
    </ul>
  );
}

You can also use the event as well: onClick={(e) => onDelete(todo.id, e)}.

Q37. What is one-way data flow?

One-way data flow means data moves in one direction, from parent to child through props. A child cannot change the parent’s data directly. Instead, it tells the parent about events by calling a function prop, and the parent decides how to update its state.

This makes apps predictable and easy to debug. When something looks wrong, you follow the data up the tree to find which component owns it and changed it.

Q38. How do a parent and child talk to each other in both directions?

Parent to child is simple: pass props. Child to parent works by the parent passing a callback function as a prop, which the child calls with any data.

function Parent() {
  const [rating, setRating] = useState(0);
  return (
    <>
      <StarRating value={rating} onRate={setRating} />
      <p>You rated: {rating}</p>
    </>
  );
}

function StarRating({ value, onRate }) {
  return [1, 2, 3, 4, 5].map((n) => (
    <button key={n} onClick={() => onRate(n)}>
      {n <= value ? "★" : "☆"}
    </button>
  ));
}

For siblings, lift the state to their common parent. In rare cases, a parent can call a child’s function with a ref and useImperativeHandle, such as to focus an input.

Q39. What is derived state, and why should you avoid storing it?

Derived state is a value you can calculate from existing props or state, such as a full name from first and last name, or a filtered list from a list and a search term. Storing it in its own state means you must keep it in sync by hand, which often causes bugs where one updates and the other does not.

// Avoid: extra state plus an effect to sync it
const [visible, setVisible] = useState([]);
useEffect(() => setVisible(items.filter((i) => i.name.includes(query))), [items, query]);

// Better: calculate during render
const visible = items.filter((i) => i.name.includes(query));

If the calculation is expensive, wrap it in useMemo, or let the React Compiler handle it.

Q40. How do you update an object or array in state the right way?

Create a new object or array instead of changing the old one. Use spread syntax and array methods that return new arrays.

// Object: change one field
setUser((u) => ({ ...u, city: "Pune" }));

// Nested object
setUser((u) => ({ ...u, address: { ...u.address, pin: "411001" } }));

// Array: add, remove, update
setTodos((t) => [...t, newTodo]);
setTodos((t) => t.filter((todo) => todo.id !== id));
setTodos((t) => t.map((todo) => (todo.id === id ? { ...todo, done: true } : todo)));

Avoid methods that change arrays in place, such as push, splice and sort. Use toSorted() or copy first. For deeply nested state, a helper library like Immer lets you write simpler update code.

Hooks React JS Interview Questions with Answers

Hooks come up in every technical round. These React JS interview questions cover the built-in hooks, their rules and the newer hooks from React 19.

Q41. What are hooks, and why were they added?

Hooks are special functions whose names start with use, such as useState and useEffect. They let function components use React features like state, side effects, context and refs. They were added in React 16.8 (2019).

Before hooks, you needed class components for state and lifecycle methods, and sharing logic needed awkward patterns like higher-order components and render props. Hooks made components shorter, kept related logic together, and made it easy to share logic with custom hooks.

Q42. What are the rules of hooks?

There are two main rules.

  1. Only call hooks at the top level of a component or custom hook. Never call them inside loops, conditions, nested functions or after an early return.
  2. Only call hooks from React functions, meaning function components or custom hooks, not from normal JavaScript functions.

React keeps track of hooks by the order they are called in each render. If a hook is skipped in one render because of an if, the order changes and state gets mixed up. The eslint-plugin-react-hooks linter checks these rules for you. The newer use API is the one exception that can be called inside conditions.

Q43. What does useState do?

useState adds a piece of state to a function component. It returns an array with two items: the current value and a setter function. You give it the starting value.

const [name, setName] = useState("");
const [cart, setCart] = useState([]);
const [total, setTotal] = useState(() => calculateInitialTotal()); // lazy initial value

Calling the setter with a new value schedules a re-render with that value. If the starting value is expensive to compute, pass a function, so it runs only on the first render.

Q44. What does useEffect do?

useEffect lets you run side effects after React has updated the screen. Side effects are things outside rendering, such as fetching data, setting up a subscription, starting a timer or changing the page title.

useEffect(() => {
  document.title = `${count} items in cart`;
}, [count]);

The React team describes effects as a way to “synchronise with an external system”. If you are only calculating values from props or state, or handling a user event, you usually do not need an effect.

Q45. What does the dependency array in useEffect control?

The dependency array tells React when to re-run the effect. React compares each value with the one from the last render, and runs the effect again only if something changed.

Dependency arrayWhen the effect runs
Not givenAfter every render
[] (empty)Once after the first render (mount), cleanup on unmount
[userId, page]After the first render, and whenever userId or page changes

You must list every prop, state and function from the component that the effect uses. Leaving one out causes bugs with stale values, and the hooks lint rule warns you about it.

Q46. What happens if you leave the dependency array out?

Then the effect runs after every single render of the component. That is sometimes what you want, but often it is a mistake.

The classic bug is an effect that fetches data and stores it in state with no dependency array. Setting state causes a re-render, which runs the effect again, which sets state again, so you get an endless loop of requests. Always think about what the effect depends on and give the right array.

Q47. What is a cleanup function in useEffect?

An effect can return a function, called the cleanup. React runs it before the effect runs again and when the component is removed (unmounts). It undoes what the effect set up, so you do not leak timers, subscriptions or network work.

useEffect(() => {
  const id = setInterval(() => setSeconds((s) => s + 1), 1000);
  return () => clearInterval(id); // stop the timer
}, []);

useEffect(() => {
  const socket = connect(roomId);
  return () => socket.disconnect(); // leave the old room before joining a new one
}, [roomId]);

Q48. Why does an effect run twice in development with Strict Mode?

In development only, Strict Mode mounts each component, then unmounts it and mounts it again. So your effect runs, its cleanup runs, and then the effect runs again. This does not happen in production.

React does this on purpose to help you find effects without proper cleanup. If running it twice causes a bug, such as two subscriptions or two chat connections, your cleanup is missing or wrong. The fix is to write correct cleanup, not to remove Strict Mode.

Q49. What is the difference between useEffect and useLayoutEffect?

Both run after React updates the DOM, but at different times. useEffect runs after the browser has painted the screen, so it does not block what the user sees. useLayoutEffect runs after the DOM update but before the browser paints, and it blocks painting until it finishes.

Use useLayoutEffect only when you must measure the layout and change something before the user sees it, such as positioning a tooltip based on its size, to avoid a flicker. For everything else, use useEffect, because useLayoutEffect can slow down rendering.

Q50. What does useRef do, and how is it different from state?

useRef gives you a box ({ current: value }) that keeps its value between renders. Changing ref.current does not cause a re-render. It is used for two main things: holding a reference to a DOM element, and keeping a value that should not trigger renders, such as a timer ID.

function SearchBox() {
  const inputRef = useRef(null);
  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  );
}
FeatureuseStateuseRef
Change causes re-renderYesNo
Read during renderYes, it is meant for UIAvoid, values can be out of date
Typical useData shown on screenDOM nodes, timer IDs, previous values

Q51. What does useMemo do?

useMemo caches the result of a calculation between renders. React recalculates it only when one of its dependencies changes.

const visibleProducts = useMemo(
  () => products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase())),
  [products, query]
);

It is used for expensive calculations, such as filtering or sorting thousands of items, and to keep the same object or array identity so memoised children or effects do not run again. It is a performance tool, so your code should still work correctly without it.

Q52. What does useCallback do?

useCallback caches a function between renders, so you get the same function object until its dependencies change. Normally, a function defined in a component is a new object on every render.

const handleAdd = useCallback((id) => {
  setCart((c) => [...c, id]);
}, []);

return <ProductList onAdd={handleAdd} />; // ProductList is wrapped in React.memo

It is mainly useful when you pass a function to a child wrapped in React.memo, or when a function is a dependency of an effect. useCallback(fn, deps) is the same as useMemo(() => fn, deps).

Q53. When is useMemo or useCallback a waste?

They have a cost: extra code, memory for the cache and comparing dependencies on every render. So they are a waste when there is nothing to gain.

  • Cheap work: the calculation is small, such as adding two numbers or filtering 20 items.
  • No memoised user: the function or value is not passed to a memoised child or used as an effect dependency.
  • Changing inputs: the dependencies change on every render anyway, so the cache never helps.

Measure with the React DevTools Profiler first. Also, the React Compiler now adds memoization automatically, so in projects that use it, you rarely need to write these hooks by hand.

Q54. What does useContext do?

useContext reads a value from a React Context, so any component deep in the tree can get shared data without prop drilling. You create a context, wrap part of the tree in its provider with a value, and read it where needed.

const ThemeContext = createContext("light");

function App() {
  const [theme, setTheme] = useState("dark");
  return (
    <ThemeContext value={theme}>   {/* React 19: use the context directly as a provider */}
      <Page />
    </ThemeContext>
  );
}

function Button() {
  const theme = useContext(ThemeContext);
  return <button className={`btn-${theme}`}>Save</button>;
}

When the provider’s value changes, every component that reads that context re-renders.

Q55. What is useReducer, and when is it better than useState?

useReducer manages state with a reducer function: (state, action) => newState. You send actions with dispatch, and the reducer decides how the state changes. It is the same idea as Redux, but local to one component.

function cartReducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.item];
    case "remove":
      return state.filter((i) => i.id !== action.id);
    case "clear":
      return [];
    default:
      return state;
  }
}

const [cart, dispatch] = useReducer(cartReducer, []);
dispatch({ type: "add", item: { id: 7, name: "Pen" } });

It is better than useState when state has many related fields, when the next state depends on complex rules, or when many event handlers change the same state. The reducer is a pure function, so it is easy to test.

Q56. What is a custom hook?

A custom hook is your own function whose name starts with use and that calls other hooks. It lets you pull reusable logic out of components, such as fetching data, reading window size or handling a form.

function useOnlineStatus() {
  const [online, setOnline] = useState(navigator.onLine);
  useEffect(() => {
    const goOnline = () => setOnline(true);
    const goOffline = () => setOnline(false);
    window.addEventListener("online", goOnline);
    window.addEventListener("offline", goOffline);
    return () => {
      window.removeEventListener("online", goOnline);
      window.removeEventListener("offline", goOffline);
    };
  }, []);
  return online;
}

function StatusBar() {
  const online = useOnlineStatus();
  return <p>{online ? "Online" : "Offline"}</p>;
}

Q57. Can two components that use the same custom hook share state?

No. A custom hook shares logic, not state. Each component that calls the hook gets its own separate state, just as if it had called useState itself. So two components using useCounter() each have their own count.

To share the actual data, lift the state to a common parent, put it in a Context, or use a store like Zustand. A custom hook can read from such a shared store, which gives the effect of shared state.

Q58. What does useId do?

useId creates a unique ID that stays the same between renders and matches between server and client rendering. It is mainly used to connect form labels and inputs, and for accessibility attributes like aria-describedby.

function EmailField() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Email</label>
      <input id={id} type="email" />
    </>
  );
}

Do not use it for list keys. Keys should come from your data.

Q59. What do useTransition and useDeferredValue do?

Both help keep the UI responsive during heavy updates, using concurrent rendering. They let React treat some updates as less urgent, so typing and clicking stay smooth.

  • useTransition marks a state update as a transition. React can pause it to handle urgent updates first, and gives you isPending to show a loading hint.
  • useDeferredValue gives you a “lagging” copy of a value. The urgent part, such as the input, updates at once, while the slow part, such as a big list, uses the deferred value and catches up.
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
// <input value={query} onChange={e => setQuery(e.target.value)} />
// <SlowResults query={deferredQuery} />

Q60. What is useEffectEvent, and what problem does it solve?

useEffectEvent (stable since React 19.2) lets you create an “effect event”: a function used inside an effect that always sees the latest props and state, but is not a dependency of the effect. It solves the problem where an effect re-runs just because a value it only reads, not reacts to, has changed.

function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showToast("Connected!", theme); // always the latest theme
  });

  useEffect(() => {
    const conn = createConnection(roomId);
    conn.on("connected", () => onConnected());
    conn.connect();
    return () => conn.disconnect();
  }, [roomId]); // theme is not a dependency, so changing theme does not reconnect
}

Without it, changing the theme would disconnect and reconnect the chat. Only call effect events from inside effects.

Q61. What does the use API do in React 19?

use is a React 19 API that reads the value of a resource during render. It works with promises and with context. With a promise, the component “suspends” until the promise resolves, and the nearest <Suspense> shows a fallback meanwhile.

import { use, Suspense } from "react";

function Comments({ commentsPromise }) {
  const comments = use(commentsPromise); // waits for the data
  return comments.map((c) => <p key={c.id}>{c.text}</p>);
}

<Suspense fallback={<p>Loading comments...</p>}>
  <Comments commentsPromise={fetchComments(postId)} />
</Suspense>

Unlike other hooks, use can be called inside conditions and loops. The promise should come from a framework, a cache or a Server Component, not be created fresh on every render.

Q62. What does useActionState do?

useActionState (React 19) manages state for a form Action. You give it an action function and a starting state. It returns the current state, a wrapped action to use in the form, and an isPending flag.

async function subscribe(prevState, formData) {
  const email = formData.get("email");
  const res = await fetch("/api/subscribe", { method: "POST", body: JSON.stringify({ email }) });
  return res.ok ? { message: "Subscribed!" } : { message: "Something went wrong" };
}

function NewsletterForm() {
  const [state, formAction, isPending] = useActionState(subscribe, { message: "" });
  return (
    <form action={formAction}>
      <input name="email" type="email" required />
      <button disabled={isPending}>{isPending ? "Saving..." : "Subscribe"}</button>
      <p>{state.message}</p>
    </form>
  );
}

It removes a lot of manual useState code for loading flags, errors and results.

Q63. What does useOptimistic do?

useOptimistic (React 19) shows the expected result of an action right away, before the server confirms it. If the action succeeds, the real data replaces the optimistic value. If it fails, React goes back to the real state automatically.

function LikeButton({ likes, likeAction }) {
  const [optimisticLikes, addLike] = useOptimistic(likes, (current) => current + 1);

  async function handleLike() {
    addLike();          // the screen updates at once
    await likeAction(); // then the server call finishes
  }
  return <button onClick={() => startTransition(handleLike)}>❤ {optimisticLikes}</button>;
}

This makes apps feel fast, for example in chat messages, likes and to-do items.

Q64. What does useFormStatus do?

useFormStatus (from react-dom, React 19) lets a component read the status of the form it is inside, such as whether it is submitting, without passing props down. It must be called from a component rendered inside a <form>.

import { useFormStatus } from "react-dom";

function SubmitButton() {
  const { pending } = useFormStatus();
  return <button disabled={pending}>{pending ? "Saving..." : "Save"}</button>;
}

<form action={saveProfile}>
  <input name="name" />
  <SubmitButton />
</form>

It makes reusable form parts, like a submit button for a design system, easy to build.

Q65. How do you fetch data with useEffect without race conditions?

A race condition happens when an older request finishes after a newer one, so the screen shows old data. For example, the user types “go”, then “golang”, and the slow “go” response arrives last. The fix is to ignore or cancel stale requests in the cleanup.

function useProducts(query) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/products?q=${encodeURIComponent(query)}`, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(setData)
      .catch((err) => {
        if (err.name !== "AbortError") setError(err);
      });
    return () => controller.abort(); // cancel the old request
  }, [query]);

  return { data, error };
}

In real apps, prefer a data library such as TanStack Query or your framework’s data loading, which handles caching, retries and races for you.

Rendering and Performance React JS Interview Questions with Answers

Senior candidates are judged on how well they understand rendering. These React JS interview questions go deeper into when and why components re-render, and how to make apps fast.

Q66. What causes a component to re-render?

A component re-renders in these situations.

  • Its own state changes, through a useState setter or useReducer dispatch.
  • Its parent re-renders, which by default re-renders all its children.
  • A context it reads with useContext gets a new value.
  • A custom hook it uses changes its internal state.

“Re-render” means React calls your component function again to get new JSX. It does not mean the real DOM changes. React only updates the DOM where the result is different. Changing a normal variable or a ref does not cause a re-render.

Q67. Does a parent re-render always re-render its children?

By default, yes. When a parent re-renders, React re-renders every child component in its JSX, even if their props did not change. Usually this is fast enough and not a problem.

There are exceptions. A child wrapped in React.memo skips re-rendering if its props are the same. Elements passed in as children or other props from higher up are not re-rendered just because the wrapper’s state changed. The React Compiler also skips unchanged children automatically. So moving state down, closer to where it is used, is a simple way to avoid extra renders.

Q68. What is React.memo?

React.memo wraps a component and tells React to skip re-rendering it when its props have not changed. React compares each prop with a shallow equality check (Object.is).

const ProductRow = React.memo(function ProductRow({ product, onAdd }) {
  return (
    <tr>
      <td>{product.name}</td>
      <td><button onClick={() => onAdd(product.id)}>Add</button></td>
    </tr>
  );
});

Use it for components that render often with the same props and are expensive to render, such as rows in a big table. Do not wrap everything, because the prop comparison itself has a small cost.

Q69. Why can a new object or function passed as a prop break React.memo?

React.memo compares props by reference. A function, object or array created inside the parent’s render is a brand-new value every time, even if it looks the same. So the comparison sees a “changed” prop and the memoised child re-renders anyway.

function Parent() {
  const [count, setCount] = useState(0);
  // New function and new object on every render: ProductRow always re-renders
  return <ProductRow onAdd={(id) => addToCart(id)} style={{ color: "red" }} />;
}

The fix is to keep the same reference with useCallback for functions and useMemo for objects, or move constant objects outside the component. The React Compiler does this for you automatically.

Q70. What is the React Compiler, and how does it change manual memoization?

The React Compiler is a build-time tool, stable since late 2025, that automatically optimises your components and hooks. It analyses your code and adds memoization where it helps, so components and values are only recalculated when their inputs really change.

This means you rarely need to write useMemo, useCallback or React.memo by hand. The code stays simpler, and performance is often better than manual memoization. It works best when your code follows the rules of React, such as not changing props or state directly, so the ESLint plugin helps you spot code the compiler cannot optimise. You add it as a Babel or build plugin, and frameworks like Next.js and Vite templates support it.

Q71. What is batching of state updates?

Batching means React groups several state updates into one re-render instead of re-rendering after each one. Since React 18, this happens automatically everywhere: in event handlers, promises, setTimeout and native events.

function handleClick() {
  setName("Asha");
  setAge(30);
  setCity("Pune");
  // Only one re-render happens, after the handler finishes
}

This makes apps faster and avoids showing half-updated UI. In the rare case you need the DOM updated at once, such as before measuring it, you can use flushSync from react-dom.

Q72. What is code splitting?

Code splitting means breaking your JavaScript bundle into smaller chunks that load only when needed, instead of one big file at the start. For example, the admin page or a heavy chart library loads only when a user opens that page.

This makes the first page load faster, especially on slow mobile networks. Bundlers like Vite and webpack split code automatically at dynamic import() calls, and React frameworks split by route for you.

Q73. What do React.lazy and Suspense do?

React.lazy loads a component’s code only when it is first rendered. Suspense shows a fallback, such as a spinner, while that code (or data) is loading.

import { lazy, Suspense } from "react";

const ReportsPage = lazy(() => import("./ReportsPage"));

function App() {
  return (
    <Suspense fallback={<p>Loading reports...</p>}>
      <ReportsPage />
    </Suspense>
  );
}

Suspense also works with data loading through use, Server Components and libraries that support it. You can place several Suspense boundaries, so parts of the page appear as soon as they are ready.

Q74. What is an error boundary, and why is it still a class component?

An error boundary is a component that catches JavaScript errors in its child tree during rendering, shows a fallback UI instead of a blank screen, and can log the error. It does not catch errors in event handlers, async code or the boundary itself.

class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    logErrorToService(error, info.componentStack);
  }
  render() {
    return this.state.hasError ? <p>Something went wrong.</p> : this.props.children;
  }
}

It still needs a class because React has no hook for getDerivedStateFromError and componentDidCatch yet. Most teams use the small react-error-boundary package, which gives a ready-made component with a reset feature.

Q75. What is a portal, and when do you need one?

A portal lets a component render its children into a different DOM node, outside its parent’s DOM hierarchy, while still behaving like a normal React child for state, context and events.

import { createPortal } from "react-dom";

function Modal({ children }) {
  return createPortal(
    <div className="modal-backdrop">{children}</div>,
    document.body
  );
}

You need one for modals, tooltips, dropdowns and toasts. If they are rendered inside a parent with overflow: hidden or a low z-index, they get cut off or hidden. A portal moves them to the end of body, so they appear on top.

Q76. What is Strict Mode, and what does it check?

<StrictMode> is a development-only helper that wraps your app and finds common bugs early. Production builds ignore it.

  • Double rendering: components render twice to find impure rendering code.
  • Effect re-run: effects run, then clean up, then run again, to find missing cleanup.
  • Ref re-run: ref callbacks run twice to find missing ref cleanup.
  • Warnings: it warns about deprecated APIs.

So if something breaks only in Strict Mode, it usually points to a real bug that would show up later, for example with fast navigation or Activity.

Q77. How do you find slow components with the React DevTools Profiler?

Install the React Developer Tools browser extension and open the Profiler tab. Click record, do the slow action in your app, such as typing in a search box, then stop recording.

The Profiler shows each commit and a flame chart of which components rendered, how long each took and why it rendered (turn on “Record why each component rendered”). Look for components that render often or take a long time. Then fix the cause, such as moving state down, splitting a big component, memoising, virtualising a long list or using a transition. Browser performance tools and React Performance Tracks give even more detail.

Q78. What is list virtualisation, and when do you need it?

List virtualisation (or windowing) means rendering only the list items that are visible on screen, plus a few extra, instead of all of them. As the user scrolls, items are swapped in and out. So a list of 10,000 rows only has about 20 rows in the DOM at a time.

You need it when you show very long lists or tables and scrolling or typing becomes slow. Libraries like TanStack Virtual and react-window make it easy. For short lists, it is not worth the extra complexity.

Q79. What is concurrent rendering?

Concurrent rendering, added in React 18, means React can prepare several versions of the UI at the same time and pause, resume or drop rendering work. Before this, rendering was one blocking task that ran until it finished.

So React can handle urgent updates first, such as typing, while slower updates, such as a filtered list, render in the background. You turn this on for specific updates with useTransition, useDeferredValue and Suspense. It keeps apps responsive even when some screens are expensive to render.

Q80. What is hydration, and what is a hydration mismatch?

With server rendering, the server sends ready HTML so the page appears fast. Hydration is when React runs in the browser, builds the same component tree, and attaches event handlers and state to that existing HTML, making it interactive.

A hydration mismatch happens when the HTML React renders in the browser is different from what the server sent. Common causes are using Date.now(), Math.random(), window or localStorage during render, or invalid HTML nesting like a div inside a p. React then shows a warning and may re-render that part. Fix it by rendering the same output on both sides, and moving browser-only values into useEffect.

Routing, Forms and Data React JS Interview Questions with Answers

Real apps need pages, forms and data from a backend. These React JS interview questions cover the tools and patterns you will use every day.

Q81. How does client-side routing work?

In client-side routing, the browser loads the app once, and JavaScript changes what is shown when the URL changes, without asking the server for a new HTML page. The router listens to URL changes using the browser History API, matches the URL to a route, and renders the matching component.

import { BrowserRouter, Routes, Route, Link } from "react-router";

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link> | <Link to="/products">Products</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/products" element={<Products />} />
        <Route path="/products/:id" element={<ProductDetail />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

Link changes the URL without a page reload. The server must also send the app’s HTML for any path, so direct visits and refreshes work.

Q82. How do you read URL parameters in React Router?

Use useParams for path parameters, such as /products/:id, and useSearchParams for the query string, such as ?sort=price&page=2.

import { useParams, useSearchParams } from "react-router";

function ProductDetail() {
  const { id } = useParams();                         // "/products/42" -> "42"
  const [searchParams, setSearchParams] = useSearchParams();
  const tab = searchParams.get("tab") ?? "details";   // "?tab=reviews"

  return (
    <div>
      <h1>Product {id}</h1>
      <button onClick={() => setSearchParams({ tab: "reviews" })}>Reviews</button>
      <p>Showing: {tab}</p>
    </div>
  );
}

Values from the URL are always strings, so convert them, such as Number(id), and validate them.

Q83. How do you protect a route that needs login?

Wrap protected routes in a component that checks if the user is logged in, and redirects to the login page if not.

import { Navigate, Outlet, useLocation } from "react-router";

function RequireAuth() {
  const { user } = useAuth();
  const location = useLocation();
  if (!user) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }
  return <Outlet />; // render the child routes
}

// <Route element={<RequireAuth />}>
//   <Route path="/orders" element={<Orders />} />
// </Route>

Remember that this only protects the UI. The real security must be on the server: every API call must check the user’s token and permissions, because anyone can change front-end code.

Q84. How do you handle forms with many fields?

For many fields, avoid one useState per field. Here are good options.

  • One state object: keep all values in one object and use a single onChange that uses the input’s name.
  • useReducer: for forms with complex rules between fields.
  • Uncontrolled inputs with FormData: read all values on submit, which works well with React 19 form Actions.
  • A form library: such as React Hook Form, for validation, errors and big forms.
function SignupForm() {
  const [form, setForm] = useState({ name: "", email: "", city: "" });

  function handleChange(e) {
    const { name, value } = e.target;
    setForm((f) => ({ ...f, [name]: value }));
  }

  return (
    <form>
      <input name="name" value={form.name} onChange={handleChange} />
      <input name="email" value={form.email} onChange={handleChange} />
      <input name="city" value={form.city} onChange={handleChange} />
    </form>
  );
}

Q85. When would you use a form library such as React Hook Form?

Use a form library when forms get big or complex: many fields, field-level validation, error messages, dynamic fields (such as adding more addresses), multi-step wizards, or dependent fields. React Hook Form is popular because it uses uncontrolled inputs, so typing does not re-render the whole form, which keeps big forms fast.

It pairs well with schema validation libraries like Zod, so the same rules can validate data on the client and the server. For a simple login or contact form, plain React or React 19 Actions are usually enough.

Q86. What is the Context API, and when is it not enough?

The Context API shares values with many components without passing props through every level. It is ideal for data that changes rarely and is needed in many places, such as the theme, language, current user or a feature flag.

It is not enough when shared state changes often and many components read it. Every component that uses the context re-renders when the value changes, even if it only needs one small part. It also has no built-in tools for caching server data, devtools or selectors. For those cases, use a state library with selectors (such as Zustand or Redux Toolkit) or a server state library (such as TanStack Query).

Q87. When would you use Redux Toolkit, Zustand or another state library?

You need a global state library when lots of client state is shared across distant parts of the app, changes often, and needs clear rules. Examples are a complex editor, a multi-step booking flow or a dashboard with many filters.

LibraryGood forStyle
Redux ToolkitLarge apps, strict patterns, strong devtoolsStore, slices, actions, reducers
ZustandSmall to medium apps wanting simple global stateSmall hook-based store
JotaiFine-grained shared stateSmall independent atoms
Context + useReducerSimple shared state, no extra libraryBuilt into React

Many apps need much less global state than they think, because most “global” data is actually server state, which is better handled by TanStack Query or framework data loading.

Q88. What is server state, and why do tools like TanStack Query exist?

Server state is data that lives on the server and is shown in your app, such as products, orders and user profiles. It is different from client state (such as an open menu), because it can change without your app knowing, it needs fetching and it can be out of date.

Handling it with useEffect and useState means writing a lot of code for loading states, errors, caching, retries, refetching, pagination and avoiding duplicate requests. TanStack Query (React Query) and SWR do all of this for you.

import { useQuery } from "@tanstack/react-query";

function Orders() {
  const { data, isPending, error } = useQuery({
    queryKey: ["orders"],
    queryFn: () => fetch("/api/orders").then((r) => r.json()),
    staleTime: 60_000, // treat data as fresh for 1 minute
  });
  if (isPending) return <p>Loading...</p>;
  if (error) return <p>Could not load orders.</p>;
  return data.map((o) => <p key={o.id}>{o.id}: ₹{o.total}</p>);
}

Q89. How do you show loading and error states while data loads?

Every data request has three states: loading, error and success. Show a clear UI for each, so users are never left with a blank screen.

function UserProfile({ userId }) {
  const { data: user, isPending, error, refetch } = useUser(userId);

  if (isPending) return <Spinner label="Loading profile" />;
  if (error) {
    return (
      <div role="alert">
        <p>Could not load the profile.</p>
        <button onClick={() => refetch()}>Try again</button>
      </div>
    );
  }
  return <h1>{user.name}</h1>;
}

With Suspense, you can move loading UI into a <Suspense fallback={...}> boundary and errors into an error boundary. Skeleton screens that look like the final layout often feel faster than spinners.

Q90. How do you store a login token safely in a React app?

The safest common approach is to keep the session token in an HttpOnly, Secure, SameSite cookie set by the server. JavaScript cannot read an HttpOnly cookie, so a cross-site scripting (XSS) bug cannot steal it. Add CSRF protection, such as SameSite=Lax or Strict plus CSRF tokens for risky requests.

Storing tokens in localStorage is simple but risky, because any XSS bug or bad third-party script can read and steal them. If you must hold a token in JavaScript, such as an access token for an API, keep it in memory only, keep it short-lived, and get new ones with a refresh token stored in an HttpOnly cookie. Also, prevent XSS in the first place: do not use dangerouslySetInnerHTML with user input, and add a Content Security Policy.

Modern React and Testing React JS Interview Questions with Answers

React 19 added several features that interviewers now ask about. These React JS interview questions cover them, plus testing, accessibility, TypeScript and linting.

Q91. What are Server Components?

React Server Components (RSC) are components that run only on the server, either at build time or for each request. They can read from a database, the file system or private APIs directly, and they send the finished UI to the browser without sending their own JavaScript code.

// app/products/page.jsx (Next.js App Router): a Server Component by default
export default async function ProductsPage() {
  const products = await db.product.findMany(); // runs only on the server
  return (
    <ul>
      {products.map((p) => <li key={p.id}>{p.name}</li>)}
    </ul>
  );
}

The benefits are a smaller JavaScript bundle, faster first loads, simple data fetching with async/await, and secrets that stay on the server. You use them through a framework that supports them, such as Next.js. Keep the framework and React packages up to date, because server-side features have had serious security fixes.

Q92. What is the difference between a Server Component and a Client Component?

Server Components run on the server and send rendered output. Client Components are the “normal” React components you already know. They are also rendered on the server for the first HTML, but their code is sent to the browser, so they can be interactive.

FeatureServer ComponentClient Component
Runs onServer onlyServer for first HTML, then browser
JavaScript sent to browserNoYes
State and effects (useState, useEffect)NoYes
Event handlers (onClick)NoYes
Direct database or secret accessYesNo
Marked withDefault in RSC frameworks"use client" at the top of the file

A good pattern is to keep pages and data loading in Server Components, and make small leaf components, like a “Like” button or a search box, Client Components.

Q93. What does the “use client” directive do?

"use client" is a line at the very top of a file that marks the boundary between Server and Client Components. It tells the bundler that this module, and everything it imports, runs on the client and must be included in the browser bundle.

You add it to components that use state, effects, event handlers or browser APIs. You do not need it in every client file, only at the entry points where Server Components import client code. It does not mean “render only in the browser”, because client components are still pre-rendered to HTML on the server.

Q94. What are Server Functions (Server Actions)?

Server Functions are async functions that run on the server but can be called from client code, like a normal function. They are marked with the "use server" directive. When used as form actions or inside transitions, they are often called Server Actions.

// actions.js
"use server";

export async function addToCart(formData) {
  const productId = formData.get("productId");
  const user = await getSessionUser();      // always check auth on the server
  await db.cart.add(user.id, productId);
}

// In a component
<form action={addToCart}>
  <input type="hidden" name="productId" value="42" />
  <button>Add to cart</button>
</form>

The framework creates the network call for you. Treat every Server Function like a public API endpoint: check authentication, permissions and input, because anyone can call it.

Q95. What are Actions in React 19, and how do they help forms?

In React 19, an Action is an async function used in a transition, often passed to a form’s action prop. React then handles the boring parts for you: pending state, errors, optimistic updates and resetting the form after a successful submit.

function UpdateName() {
  const [error, submitAction, isPending] = useActionState(async (prev, formData) => {
    const result = await updateName(formData.get("name"));
    return result.error ?? null;
  }, null);

  return (
    <form action={submitAction}>
      <input name="name" />
      <button disabled={isPending}>Update</button>
      {error && <p role="alert">{error}</p>}
    </form>
  );
}

Together with useActionState, useFormStatus and useOptimistic, Actions remove a lot of manual useState code, and forms can even work before JavaScript loads when used with server rendering.

Q96. How can you pass ref as a normal prop in React 19?

Since React 19, function components can receive ref as a normal prop. You no longer need to wrap them in forwardRef.

// React 19
function TextInput({ label, ref, ...props }) {
  return (
    <label>
      {label}
      <input ref={ref} {...props} />
    </label>
  );
}

function Form() {
  const inputRef = useRef(null);
  return <TextInput label="Name" ref={inputRef} />;
}

forwardRef still works but will be deprecated in the future. React 19 also lets ref callbacks return a cleanup function, which runs when the element is removed.

Q97. What is the Activity component?

<Activity> (stable since React 19.2) lets you hide and show parts of the UI while keeping their state. It has two modes: visible and hidden. When hidden, the content is hidden from the screen, its effects are cleaned up, and its updates get low priority, but its state stays in memory.

<Activity mode={activeTab === "settings" ? "visible" : "hidden"}>
  <SettingsPanel />
</Activity>

This is useful for tabs, so a half-filled form or scroll position is not lost when switching tabs. You can also pre-render a screen the user is likely to open next in the background.

Q98. What is the difference between SSR, SSG and CSR?

These are three ways to render a React page.

MethodWhen HTML is madeGood forTrade-off
CSR (client-side rendering)In the browser, after JavaScript loadsDashboards behind loginSlow first paint, weak SEO
SSR (server-side rendering)On the server, for each requestPersonalised, frequently changing pages with SEOServer work on every request
SSG (static site generation)At build timeBlogs, docs, marketing pagesData can be out of date until rebuilt

Modern frameworks mix them per page, and add incremental regeneration and streaming SSR with Suspense, which sends parts of the page as soon as they are ready.

Q99. How do you test a component with React Testing Library?

React Testing Library (RTL) renders your component and lets you interact with it the way a user would: find elements by role, label or text, click, type and check what appears. It usually runs with Vitest or Jest, plus @testing-library/user-event for realistic interactions.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";

test("increases the count when clicked", async () => {
  const user = userEvent.setup();
  render(<Counter />);

  await user.click(screen.getByRole("button", { name: /add/i }));

  expect(screen.getByText("Count: 1")).toBeInTheDocument();
});

The idea is to test behaviour, not implementation details like state variables, so tests do not break when you refactor.

Q100. Why should tests find elements by role or label instead of class names?

Users do not see class names or test IDs. They see buttons, links, headings and labelled inputs. Queries like getByRole("button", { name: "Save" }) and getByLabelText("Email") find elements the same way users and screen readers do.

So your tests break only when the real user experience changes, not when you rename a CSS class. As a bonus, if a test cannot find an element by role or label, your UI probably has an accessibility problem. Use getByTestId only as a last resort.

Q101. How do you mock an API call in a component test?

The most popular approach is Mock Service Worker (MSW). It catches network requests at the network level and returns fake responses, so your component’s real fetch code runs unchanged.

import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";

const server = setupServer(
  http.get("/api/orders", () =>
    HttpResponse.json([{ id: 1, total: 499 }])
  )
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test("shows orders", async () => {
  render(<Orders />);
  expect(await screen.findByText(/499/)).toBeInTheDocument();
});

You can also mock a module with vi.mock or jest.mock, but MSW tests are closer to real behaviour, and the same mocks can be reused in development.

Q102. How do you test a custom hook?

Use renderHook from React Testing Library. It renders the hook inside a small test component and gives you its current return value.

import { renderHook, act } from "@testing-library/react";
import { useCounter } from "./useCounter";

test("useCounter increments", () => {
  const { result } = renderHook(() => useCounter(5));

  act(() => result.current.increment());

  expect(result.current.count).toBe(6);
});

Wrap state changes in act, so React finishes updating before you check. If the hook needs a provider, such as a QueryClient or Context, pass a wrapper option. Often it is even better to test the hook through a component that uses it.

Q103. What is accessibility (a11y), and how do you make a React app accessible?

Accessibility means making your app usable by everyone, including people who use screen readers, keyboards only, voice control or who have low vision. “a11y” is short for the 11 letters between “a” and “y”. It is also a legal requirement in many places.

Here are the key practices in React.

  • Use semantic HTML: button for actions, a for links, nav, main, headings in order.
  • Give every input a label, and images useful alt text.
  • Make everything work with the keyboard, with visible focus styles.
  • Manage focus in modals and after route changes, and trap focus inside open dialogs.
  • Use ARIA attributes only when HTML cannot express it, such as aria-expanded on a menu button.
  • Check colour contrast, and test with tools like axe, Lighthouse and eslint-plugin-jsx-a11y.

Q104. How do you add TypeScript types to props?

Define a type or interface for the props and use it in the component’s parameter. TypeScript then checks every place that uses the component.

type ButtonProps = {
  label: string;
  variant?: "primary" | "secondary";   // optional, only these two values
  onClick: () => void;
  children?: React.ReactNode;
};

function Button({ label, variant = "primary", onClick }: ButtonProps) {
  return <button className={`btn-${variant}`} onClick={onClick}>{label}</button>;
}

// For native elements, extend their props:
type InputProps = React.ComponentProps<"input"> & { label: string };

Most teams no longer use React.FC, because plain typed functions are simpler. Hooks infer types too, and you can give them explicitly, such as useState<User | null>(null).

Q105. How do you set up linting for hooks with ESLint?

Install eslint-plugin-react-hooks, the official plugin from the React team. Its rules check the rules of hooks and the dependency arrays of effects, and its newer rules also report code that breaks the rules of React, which the React Compiler needs.

// eslint.config.js (flat config)
import reactHooks from "eslint-plugin-react-hooks";

export default [
  reactHooks.configs.flat.recommended,
];

Run ESLint in your editor and in CI. Treat exhaustive-deps warnings seriously, because a missing dependency is a common source of stale data bugs. Vite and framework templates usually include this setup already.

Scenario React JS Interview Questions with Answers

For each scenario, explain what you would check first, and why. Interviewers care more about your steps than a perfect answer, so these answers follow a clear “find, fix, prevent” order.

Q106. A page freezes when the user types in a search box. How do you fix it?

First, find what is slow. Record the typing in the React DevTools Profiler and the browser Performance panel. Usually, each key press re-renders a big list or runs an expensive filter.

Then fix it with one or more of these steps.

  • Keep the input fast: use useDeferredValue (or useTransition) so the input updates at once and the heavy list renders in the background.
  • Debounce network calls: wait about 300 ms after typing stops before calling the API.
  • Make rendering cheaper: memoise the filtered list with useMemo (or rely on the React Compiler), and wrap list rows in React.memo.
  • Render less: virtualise long lists, so only visible rows are in the DOM.
  • Move state down: keep the search text in the search component, so the rest of the page does not re-render on each key.
function Search({ products }) {
  const [query, setQuery] = useState("");
  const deferredQuery = useDeferredValue(query);
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <ProductList products={products} query={deferredQuery} />
    </>
  );
}

Q107. An effect fetches data in a loop and never stops. What is wrong?

The effect sets state, the state change causes a re-render, and the effect runs again, which sets state again, forever. There are a few usual causes.

  • No dependency array, so the effect runs after every render.
  • An object or array dependency created during render, such as useEffect(..., [filters]) where filters = { page: 1 } is a new object every time.
  • A function dependency that is recreated on every render.
  • The effect sets a value it depends on, such as fetching and then updating the same filters state.

Fix it by giving the correct dependency array with primitive values ([page, query]), moving object creation inside the effect, using useMemo or useCallback for objects and functions, or using a data library like TanStack Query. The network tab in DevTools shows the repeated calls clearly.

Q108. A list shows the wrong item after you delete one row. Why?

This is almost always a key problem. The list probably uses the array index as the key, key={index}. When you delete row 2, every row after it moves up one index, so React thinks row 2 still exists with new data and keeps the old DOM and state (such as an input’s text or a checkbox) on the wrong item.

// Bug
{items.map((item, index) => <Row key={index} item={item} />)}

// Fix: a stable, unique ID from the data
{items.map((item) => <Row key={item.id} item={item} />)}

If the data has no ID, create one when the item is created, such as crypto.randomUUID(), never during render.

Q109. Your app bundle is 3 MB and loads slowly. How do you shrink it?

First, measure what is inside. Use a bundle analyser, such as rollup-plugin-visualizer for Vite or @next/bundle-analyzer for Next.js, to see which packages are biggest.

Then shrink it step by step.

  • Code split by route with React.lazy and dynamic import(), so each page loads its own code.
  • Lazy load heavy features, such as charts, editors and maps, only when used.
  • Replace heavy libraries, such as moment.js with date-fns or Intl, and import only what you use (lodash-es/debounce instead of all of lodash).
  • Remove unused code and duplicate packages, and check that tree shaking works.
  • Use Server Components in a framework, so server-only code never reaches the browser.
  • Optimise assets: compress images, use modern formats, and serve everything with compression and caching from a CDN.

Finally, set a bundle size budget in CI, so it does not grow back.

Q110. Design the component structure for a shopping cart page.

Split the page into small components with clear jobs, keep server data in a data library, and keep cart state in one place.

CartPage                      // route page: loads cart data, handles layout
├── CartHeader                // title and item count
├── CartItemList              // maps items to rows
│   └── CartItemRow           // image, name, price, QuantitySelector, remove button
│       └── QuantitySelector  // + and - buttons, calls onChange(newQty)
├── CouponForm                // input + apply button (form Action)
├── OrderSummary              // subtotal, discount, tax, total (derived values)
└── CheckoutButton            // disabled when cart is empty or updating

Here are the key decisions to explain.

  • State: the cart lives on the server and is read with TanStack Query or a Server Component. Updates go through mutations or Server Actions, with useOptimistic so quantity changes feel instant.
  • Derived values: subtotal and total are calculated from items during render, not stored in separate state.
  • Props down, events up: CartItemRow gets an item and calls onQuantityChange(id, qty) and onRemove(id).
  • Keys: use the cart item ID, never the index.
  • Empty, loading and error states: an empty cart message, skeleton rows while loading and a retry on error.
  • Accessibility: real buttons with labels like “Increase quantity of Notebook”, and announce total changes for screen readers.
  • Tests: test adding, removing and changing quantities with React Testing Library and MSW.

Hands-On React JS Interview Questions Practice

Interviewers often ask you to build a small component live. Here is a counter that answers questions 30, 43 and 71.

import { useState } from "react";

// Counter shows a number and buttons to change it.
export default function Counter() {
  const [count, setCount] = useState(0); // count starts at 0

  function addThree() {
    // The updater form uses the latest value each time,
    // so this adds 3, not 1.
    setCount((current) => current + 1);
    setCount((current) => current + 1);
    setCount((current) => current + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Add 1</button>
      <button onClick={addThree}>Add 3</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

The first button uses the current count directly, which is fine for one update. The Add 3 button uses the updater form, because React batches the three calls and each one gets the newest value. If you wrote setCount(count + 1) three times, the count would only go up by one.

Next, here is a custom hook that fetches data safely. It answers questions 47, 56 and 65.

import { useEffect, useState } from "react";

// useUser loads one user and ignores late responses.
export function useUser(userId) {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController(); // lets us cancel the request

    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then((response) => {
        if (!response.ok) throw new Error("Request failed");
        return response.json();
      })
      .then((data) => setUser(data))
      .catch((err) => {
        if (err.name !== "AbortError") setError(err); // ignore cancelled requests
      });

    // Cleanup runs before the next effect or when the component unmounts.
    return () => controller.abort();
  }, [userId]); // run again only when userId changes

  return { user, error };
}

// UserCard uses the hook and shows loading, error or the user.
export function UserCard({ userId }) {
  const { user, error } = useUser(userId);
  if (error) return <p>Could not load user.</p>;
  if (!user) return <p>Loading...</p>;
  return <h2>{user.name}</h2>;
}

When userId changes quickly, the cleanup aborts the old request, so a slow old response can never replace newer data. The dependency array holds only userId, so the effect does not run on every render. In larger apps, a library such as TanStack Query adds caching and retries on top of this pattern.

Common Mistakes in React JS Interview Questions

  • Changing state directly: always create a new object or array, then call the setter.
  • Using the index as a key: use a stable ID from your data instead.
  • Missing effect dependencies: list every value the effect reads, or the effect uses stale data.
  • Overusing useMemo and useCallback: add them only when profiling shows a problem.
  • Storing derived data in state: compute it during render instead.

Best Practices for Answering React JS Interview Questions

  • Explain the render cycle: state change, render, compare, commit, effects.
  • Write small components with one clear job each.
  • Mention modern tools, such as Vite or a framework, the React Compiler and React 19 Actions.
  • Talk about accessibility and testing in every component answer.
  • Use real examples, such as a slow list you fixed with virtualisation.

Practice Task

To practise these React JS interview questions, build a small todo app with Vite. It should add, complete and delete items, filter by status, and keep items after a page refresh. Hint: store the list in state, use the item ID as the key, and save to localStorage inside a useEffect.

Official Resources

Quick Recap

  • React JS interview questions focus on JSX, components, props, state, hooks and rendering.
  • Props flow down and are read-only, while state belongs to a component and changes over time.
  • Use stable keys, the updater form for state, and cleanup functions in effects.
  • Reach for memoization only when needed, or let the React Compiler handle it.
  • Know React 19 features such as Actions, use, and Server Components.
  • Every one of the 110 questions now has a full answer, with code you can try.
  • Practise building small components live, because coding rounds are common.

What’s Next?

You now have question lists for Docker, Kubernetes, CI/CD, AWS and React. Next, see the backend side of full-stack apps with the Go REST API tutorial. For every topic in one place, browse the Go interview questions hub.