Rates TodayNIFTY25,670-0.83%SENSEX83,630.7-0.83%Gold 24K ₹11,320.24/g down186.46Silver ₹134.77/g down2.72
InsightforGeeks

React interview questions and answers

26 questions · Easy, Medium and Hard

These React questions cover what interviewers ask most, from components and props to hooks, performance and how React decides to re-render. Each answer is short enough to say in an interview, with a small example where it helps.

The hard questions are the ones where a clear explanation of how React works, not just how to use it, makes the difference.

Easy 8Medium 11Hard 7

Easy questions

What is React?

React is a JavaScript library for building user interfaces out of small, reusable pieces called components. You describe what the screen should look like for the current data, and React works out what to change in the browser when the data changes. This is called a declarative approach.

Often asked next: How is a library different from a framework?

What is JSX?

JSX is a syntax that lets you write markup inside JavaScript. A build tool turns it into plain JavaScript function calls. A component must return one root element, which can be a fragment (<>...</>) if you do not want an extra wrapper. Inside JSX, curly braces {} hold JavaScript expressions, and attributes use camelCase, such as className and onClick.

function Greeting({ name }) {
  return (
    <>
      <h1>Hello, {name}</h1>
      <p className="note">Welcome back.</p>
    </>
  );
}

What is the difference between props and state?

Props are inputs passed from a parent to a child; the child should treat them as read-only. State is data a component owns and can change over time with a setter such as setCount. When state changes, the component re-renders.

Data flows one way, from parent to child. A child asks the parent to change something by calling a function the parent passed down as a prop.

What are controlled and uncontrolled components?

In a controlled component, React state is the single source of truth for a form field: you set value from state and update it in onChange. In an uncontrolled component, the DOM holds the value and you read it with a ref when you need it.

Controlled inputs make validation and conditional logic easy. Uncontrolled inputs are simpler for basic forms, or for file inputs, which cannot be controlled.

const [email, setEmail] = useState('');
<input value={email} onChange={(e) => setEmail(e.target.value)} />

Why do list items need a key?

key lets React identify which item is which between renders, so it can update, move or remove the right ones and keep each item's state. Use a stable, unique value from your data, such as an ID. Avoid the array index if items can be reordered, added or removed, because the keys then no longer match the items and state can end up on the wrong item.

What are hooks, and what are the rules of hooks?

Hooks are functions such as useState and useEffect that let function components use state and other React features. There are two rules: call hooks only at the top level of a component or custom hook (not inside loops, conditions or nested functions), and call them only from React function components or other hooks. React relies on the order of the calls staying the same on every render.

What is the virtual DOM?

The virtual DOM is React's lightweight description of the UI as a tree of JavaScript objects. When state changes, React builds a new tree, compares it with the previous one (reconciliation), and applies only the differences to the real DOM. This avoids touching the browser's DOM more than needed. It is an implementation idea, not a promise that React is always faster than hand-written DOM code.

What is the difference between function and class components?

Function components are plain functions that use hooks, and they are the standard way to write React today. Class components use this, state and lifecycle methods such as componentDidMount. Classes still work, and error boundaries still need a class component, but new code is normally written with functions.

Medium questions

How does useEffect work, and what is the dependency array?

useEffect runs code after React has rendered, for side effects such as fetching data, subscriptions or timers. The dependency array controls when it runs again: with [] it runs once after the first render, with [a, b] it runs when a or b change, and with no array it runs after every render.

If the effect starts something, return a cleanup function to stop it, for example to remove an event listener or cancel a request. Leaving out a value the effect uses is a common bug that causes stale data.

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);

Often asked next: What causes an infinite loop in useEffect?

Why should you not change state directly, and how do you update objects and arrays?

React decides whether to re-render by comparing the new state with the old using reference equality. If you mutate an object or array in place, the reference is the same, so React may not re-render. Always create a new value: spread for objects and arrays, or map, filter and slice for lists.

When the new state depends on the old one, pass a function to the setter, such as setCount((c) => c + 1), so you always work from the latest value.

setUser((u) => ({ ...u, name: 'Asha' }));
setItems((list) => [...list, newItem]);
setItems((list) => list.filter((i) => i.id !== id));

useState explained: updating objects and arrays →

What is useRef used for?

useRef gives you an object with a .current property that stays the same between renders and does not cause a re-render when changed. The two main uses are holding a reference to a DOM element (to focus an input, for example) and storing a mutable value you do not want to render, such as a timer ID or the previous value of a prop.

What is the difference between useMemo, useCallback and React.memo?

useMemo remembers the result of a calculation between renders. useCallback remembers a function so its reference stays the same. React.memo wraps a component so it skips re-rendering when its props have not changed.

They work together: passing a new function or object to a memoised child on every render defeats React.memo, which is where useCallback and useMemo help. Do not add them everywhere; measure first, because they have a cost too.

What is the Context API, and what is its main drawback?

Context lets you share a value, such as the theme or the logged-in user, with every component below a provider without passing props through each level (prop drilling). Components read it with useContext.

Every component that reads a context re-renders when its value changes. For values that change often, split the context into smaller ones, memoise the value, or use a state library.

React Context API: share data without prop drilling →

When would you use useReducer instead of useState?

Use useReducer when state has several related fields, or when the next state depends on the previous one through clear actions such as add, remove and toggle. It puts all update logic in one reducer function, which makes it easier to test and to reason about. For a single value like a counter or a toggle, useState is simpler.

What is lifting state up?

When two components need the same data, move the state to their closest common parent and pass it down as props, along with functions to change it. This keeps one source of truth. If the data has to travel through many layers, consider context or composition, where you pass components as children instead of passing data down.

What is a custom hook?

A custom hook is a function whose name starts with use and that calls other hooks. It lets you reuse stateful logic, such as fetching data, tracking window size or reading local storage, between components. Each component that calls it gets its own separate state.

function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved ? JSON.parse(saved) : initial;
  });
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
}

How do you fetch data in React, and how do you avoid race conditions?

The basic way is fetch inside useEffect, with state for loading, error and data. A race condition happens when an older request finishes after a newer one and overwrites its result. Avoid it by cancelling with an AbortController in the cleanup function, or by ignoring results from outdated effects.

In real projects a data library such as TanStack Query handles caching, retries and these edge cases for you.

useEffect(() => {
  const controller = new AbortController();
  fetch(url, { signal: controller.signal })
    .then((r) => r.json())
    .then(setData)
    .catch((e) => { if (e.name !== 'AbortError') setError(e); });
  return () => controller.abort();
}, [url]);

What is an error boundary?

An error boundary is a class component that catches errors thrown while rendering its children and shows a fallback UI instead of crashing the whole app. It catches errors in rendering and lifecycle methods, but not in event handlers, asynchronous code or the boundary itself. Libraries such as react-error-boundary give you a ready-made one.

How do you split code in React?

Use React.lazy with dynamic import() to load a component only when it is needed, and wrap it in Suspense to show a fallback while it loads. Split by route first, because users rarely need every page at once. This makes the first load smaller and faster.

const Settings = lazy(() => import('./Settings'));

<Suspense fallback={<p>Loading…</p>}>
  <Settings />
</Suspense>

Hard questions

What makes a React component re-render?

A component re-renders when its own state changes, when its parent re-renders (even if its props are the same, unless it is wrapped in React.memo), or when a context it reads changes. React does not compare props by default, which is why re-renders can cascade down a tree.

A re-render means React calls your function again; it does not always mean the DOM changes. React only updates the DOM where the output actually differs.

Often asked next: How would you find out why a component renders too often?

Why do you sometimes see stale values in effects or event handlers?

Every render creates new functions that close over that render's values. If an effect or a timer was created in an earlier render and its dependencies are missing, it keeps using the old values: a stale closure. Fix it by listing all values the effect uses in the dependency array, using the functional form of the state setter, or keeping the latest value in a ref.

Why does React StrictMode run effects and renders twice in development?

StrictMode deliberately renders components twice, and in React 18 and later mounts, unmounts and remounts them once, only in development. This exposes code that is not pure or an effect that does not clean up properly, which would otherwise show up as odd bugs later. It does not happen in production builds.

What problem do useTransition and useDeferredValue solve?

They are part of React 18's concurrent features. useTransition lets you mark a state update as non-urgent, so urgent updates such as typing stay responsive while a heavy update, such as filtering a big list, is processed in the background. useDeferredValue gives you a delayed copy of a value for the same purpose. They help with slow renders; they do not make the work itself faster.

What are React Server Components?

Server Components are components that render only on the server, so their code is never sent to the browser. They can read from a database or the file system directly and reduce the JavaScript users download. They cannot use state, effects or browser-only APIs. Interactive parts are written as Client Components, marked with "use client", and the two can be mixed in one tree. Frameworks such as Next.js use this model in their App Router.

How would you improve the performance of a slow React app?

Measure first with the React DevTools Profiler to see what is slow. Then fix the cause: avoid unnecessary re-renders with React.memo and stable props; keep state close to where it is used; virtualise long lists with a library such as react-window; split code by route; avoid expensive work during render, or move it into useMemo; and optimise images. Premature memoisation adds complexity without a measured gain.

How does React's reconciliation work, and why do keys matter in it?

When state changes, React compares the new element tree with the previous one. It assumes two elements of different types produce different trees, so it rebuilds that subtree. For lists, it uses keys to match old and new children, so it can reorder instead of recreating them. A changing or missing key makes React throw away and recreate components, losing their state.

Practise in code

Interviews often include a short coding task. These challenges run in your browser.

Keep learning

Handy free tools

More interview questions