Technology

React JS Interview Questions and Answers

React JS interviews check that you understand how React thinks: components, props and state, hooks, rendering and reconciliation, and how to keep a growing app fast and maintainable. These ReactJS interview questions start with the basics asked of freshers and move to the performance, architecture and server rendering questions experienced developers face.

40 questions · Updated

Reading answers is not the same as saying them.Practise React JS questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
React JS Interview Questions with answers. Examples: What is React, and why is it used? What is JSX? What is the difference between props and state? What is the virtual DOM?
React JS Interview Questions: 40 questions with model answers on this page.

Topics interviewers ask about

JSXComponents & PropsStateHooksuseEffectuseMemo & useCallbackuseRefContext APICustom HooksVirtual DOM & ReconciliationKeys & ListsFormsReact RouterRedux ToolkitReact QueryPerformance OptimizationError BoundariesSuspense & Lazy LoadingServer ComponentsNext.jsReact Testing Library

Basic react js interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is React, and why is it used?

Answer flow · 3 steps
  1. React is a JavaScript library for building user interfaces out of reusable components.

  2. You describe what the UI should look like for a given state, and React updates the DOM when that state changes.

  3. It is popular because components are easy to reuse and test, data flows in one direction so bugs are easier to trace, and it has a huge ecosystem (Next.js, React Router, React Query, React Native).

2. What is JSX?

Answer flow · 3 steps
  1. JSX is a syntax extension that lets you write HTML-like markup inside JavaScript.

  2. It is not understood by the browser; a compiler such as Babel or SWC turns it into function calls (React.createElement or the newer jsx runtime) that return plain objects describing the UI.

  3. Differences from HTML include className instead of class, htmlFor instead of for, camelCase event names like onClick, and curly braces to embed JavaScript expressions.

3. What is the difference between props and state?

Answer flow · 4 steps
  1. Props are inputs passed from a parent to a child; the child reads them but must not change them.

  2. State is data a component owns and can change over time, using useState or useReducer.

  3. Changing state makes the component re-render.

  4. If two components need the same data, the state is lifted up to their closest common parent and passed down as props.

4. What is the virtual DOM?

Answer flow · 4 steps
  1. The virtual DOM is a lightweight JavaScript description of the UI.

  2. When state changes, React renders a new tree, compares it with the previous one (reconciliation, or "diffing"), and applies only the minimum changes to the real DOM.

  3. This makes declarative code practical: you re-describe the whole UI and React works out the cheap updates.

  4. It is not automatically faster than careful manual DOM code, but it is fast enough and much easier to maintain.

5. Why do lists in React need keys?

Answer flow · 3 steps
  1. Keys tell React which item is which between renders, so it can reuse, move or remove the right elements.

  2. A key must be stable and unique among siblings, usually an id from the data.

  3. Using the array index as the key causes bugs when items are added, removed or reordered: input values and component state get attached to the wrong row.

6. What are controlled and uncontrolled components?

Answer flow · 3 steps
  1. In a controlled component the form value lives in React state: value comes from state and onChange updates it, so React is the single source of truth and validation is easy.

  2. In an uncontrolled component the DOM keeps the value and you read it with a ref or from FormData on submit.

  3. Controlled inputs suit live validation and dependent fields; uncontrolled inputs are simpler for basic forms and file inputs.

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

Answer flow · 3 steps
  1. Hooks are functions such as useState, useEffect and useContext that let function components use state and other React features.

  2. There are two rules: call hooks only at the top level of a component or custom hook, never inside loops, conditions or nested functions; and call them only from React function components or custom hooks.

  3. React relies on hooks being called in the same order on every render to match each call to its stored state.

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

Answer flow · 4 steps
  1. Class components extend React.Component, keep state in this.state, update it with this.setState and use lifecycle methods such as componentDidMount.

  2. Function components are plain functions that use hooks for state and effects.

  3. Function components are shorter, easier to test and share logic through custom hooks, so they are the standard today.

  4. Class components still work, and error boundaries are the one feature that needs a class (or a library).

9. What are fragments in React?

Answer flow · 4 steps
  1. A component must return a single parent element.

  2. A fragment, written <>...</> or <React.Fragment>, groups several elements without adding an extra div to the DOM.

  3. This keeps the HTML clean and avoids breaking layouts such as flexbox, grid or tables, where an extra wrapper would be invalid.

  4. Use the long form when you need a key, for example when mapping a list into fragments.

10. How do you render something conditionally in React?

Answer flow · 3 steps
  1. Use an if statement before the return for larger branches, the ternary operator inside JSX for either/or, and the && operator to render something only when a condition is true.

  2. Be careful with && and numbers: {count && <Badge />} renders 0 when count is 0, so write {count > 0 && <Badge />}.

  3. Returning null renders nothing.

function Inbox({ user, count }) {
  if (!user) return <Login />;
  return (
    <div>
      {count > 0 ? <Badge count={count} /> : <p>No new messages</p>}
      {user.isAdmin && <AdminLink />}
    </div>
  );
}

11. How do you pass data from a child component to its parent?

Answer flow · 4 steps
  1. Data flows down through props, so the parent passes a callback function as a prop and the child calls it with the data, for example onSelect(item).

  2. The parent then updates its own state.

  3. If several siblings need the data, the state lives in their common parent.

  4. This one-way flow makes it easy to see where every change comes from.

12. What is props.children, and why is composition useful?

Answer flow · 3 steps
  1. children is whatever you place between a component's opening and closing tags.

  2. It lets you build wrapper components such as Card, Modal or Layout that do not need to know what they contain.

  3. React recommends composition over inheritance: you build complex UIs by nesting and combining components, and pass components as props for different slots, such as header and footer.

13. How does routing work in a React app?

Answer flow · 4 steps
  1. React itself has no router.

  2. In a single-page app, React Router maps URL paths to components, with nested routes and layouts, URL parameters read through useParams, links that change the URL without a full page reload, and loaders for data.

  3. Frameworks such as Next.js use file-based routing instead.

  4. In both, navigation keeps the app in memory, so moving between pages is fast.

14. What does React StrictMode do?

Answer flow · 4 steps
  1. StrictMode is a development-only tool that helps find bugs.

  2. It renders components twice and runs effects twice (mount, unmount, mount) to expose impure render logic and effects that are missing cleanup, and warns about deprecated APIs.

  3. It has no effect in production.

  4. If an effect breaks when run twice, it usually needs a cleanup function.

Intermediate react js interview questions

Applied problems, trade-offs and questions about your own projects.

15. Explain useEffect and its dependency array.

Answer flow · 4 steps
  1. useEffect runs side effects, such as fetching data, subscribing to events or setting timers, after React has painted.

  2. With no dependency array it runs after every render; with an empty array it runs once after mount; with values in the array it runs again whenever one of them changes.

  3. The function you return is the cleanup, run before the next effect and on unmount, which is where you unsubscribe or clear timers.

  4. Missing dependencies cause stale values, so I follow the exhaustive-deps lint rule.

16. When does a React component re-render?

Answer flow · 4 steps
  1. A component re-renders when its state changes, when its parent re-renders, or when a context value it reads changes.

  2. A new prop does not trigger a render on its own; the parent rendering is what passes it down.

  3. Re-rendering is usually cheap because React only touches the DOM where output changed.

  4. It becomes a problem for expensive components or long lists, which is when memoisation helps.

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

Answer flow · 4 steps
  1. useMemo caches the result of a calculation between renders until its dependencies change. useCallback caches a function so its identity stays the same.

  2. React.memo wraps a component so it skips re-rendering when its props are shallowly equal.

  3. They work together: React.memo is useless if the parent passes a new object or function on every render, so those props are stabilised with useMemo and useCallback.

  4. I only add them after the Profiler shows a real cost.

18. What is the Context API, and when would you not use it?

Answer flow · 4 steps
  1. Context passes a value through the component tree without threading props through every level, which suits rarely changing data such as the theme, current user or language.

  2. Every component that reads a context re-renders when its value changes, so one big frequently changing context can slow the app.

  3. For fast-changing shared state I split contexts, memoise the value, or use a store such as Zustand or Redux Toolkit.

  4. Server data belongs in React Query or SWR, not context.

19. What is a custom hook? Give an example.

Answer flow · 3 steps
  1. A custom hook is a function whose name starts with "use" and that calls other hooks, so stateful logic can be reused across components.

  2. For example, useDebounce(value, delay) can keep a debounced copy of a search term with useState and a setTimeout inside useEffect, so an API is only called once the user stops typing.

  3. Each component that uses the hook gets its own independent state.

20. What is the difference between useRef and useState?

Both keep a value between renders, but updating state triggers a re-render and updating ref.current does not. useRef is used to access DOM elements (focusing an input, measuring size) and to hold mutable values that do not affect the output, such as a timer id or the previous value of a prop. If the screen should change when the value changes, it belongs in state.

21. What are error boundaries?

Answer flow · 3 steps
  1. An error boundary is a component that catches JavaScript errors thrown while rendering its children and shows a fallback UI instead of a blank screen.

  2. It is written as a class component using getDerivedStateFromError and componentDidCatch, or with a library like react-error-boundary.

  3. Error boundaries do not catch errors in event handlers, async code or the boundary itself; those need try/catch.

22. When would you use useReducer instead of useState?

Answer flow · 3 steps
  1. useReducer suits state with several related values or complex update logic, where the next state depends on the previous one in different ways, such as a form, a shopping cart or a multi-step wizard.

  2. All updates go through one reducer function that takes the current state and an action and returns the new state, which makes changes predictable and easy to test.

  3. For a single simple value, useState is clearer.

function reducer(state, action) {
  switch (action.type) {
    case 'add': return { ...state, items: [...state.items, action.item] };
    case 'remove': return { ...state, items: state.items.filter((i) => i.id !== action.id) };
    default: return state;
  }
}
const [cart, dispatch] = useReducer(reducer, { items: [] });

23. What are higher-order components and render props, and why are hooks preferred now?

Answer flow · 4 steps
  1. A higher-order component is a function that takes a component and returns a new one with extra props or behaviour, such as withAuth(Dashboard).

  2. Render props pass a function as a prop that the component calls to render, sharing its state.

  3. Both share logic but create wrapper nesting and can clash over prop names.

  4. Custom hooks share the same logic directly inside components, so they have largely replaced both patterns.

24. What are portals in React?

Answer flow · 3 steps
  1. createPortal renders children into a different DOM node, usually one directly under body, while keeping them in the same place in the React tree.

  2. They are used for modals, tooltips, dropdowns and toasts, which must escape parent containers with overflow: hidden or stacking contexts.

  3. Events still bubble through the React tree as if the portal were in its original position, and context still works.

25. How do you access a DOM element in React, and what changed with forwardRef?

Answer flow · 3 steps
  1. Create a ref with useRef and attach it with the ref attribute; after rendering, ref.current is the DOM node, so you can focus an input, measure size or scroll into view.

  2. To let a parent pass a ref to an element inside a custom component, older React needed forwardRef.

  3. Since React 19, function components can accept ref as a normal prop. useImperativeHandle limits what a parent can do with the ref.

26. What is state batching in React?

Answer flow · 3 steps
  1. React groups several state updates into one re-render for performance.

  2. Since React 18, automatic batching applies everywhere, including inside promises, timeouts and native event handlers, not just React events.

  3. Because updates are batched and applied later, reading state right after setting it gives the old value; use the updater form setCount(c => c + 1) when the new value depends on the previous one.

27. What are common useEffect mistakes?

Missing dependencies, which cause stale values; objects or functions created during render in the dependency array, which make the effect run every render and can cause infinite loops; forgetting cleanup for subscriptions, timers and requests; race conditions when an old fetch finishes after a newer one; and using effects for things that do not need them, such as calculating derived values, which should simply be computed during render.

28. Why must state be updated immutably in React?

Answer flow · 3 steps
  1. React decides whether to re-render by comparing the old and new state references.

  2. If you mutate an object or array and set the same reference, React sees no change and the UI does not update, and memoised components that compare props also break.

  3. So you create new copies with the spread operator, map, filter or structuredClone, or use a library like Immer, which lets you write mutating code that produces immutable updates.

High level react js interview questions

System design, deep internals, leadership and tough follow-ups.

29. How would you optimise a slow React application?

Answer flow · 4 steps
  1. First I measure with the React Profiler and Lighthouse to find the real bottleneck.

  2. For slow rendering I move state closer to where it is used, memoise expensive components and calculations, virtualise long lists with a library like react-window, and use useTransition or useDeferredValue to keep typing responsive.

  3. For slow loading I code-split routes with React.lazy and Suspense, remove heavy dependencies, optimise images and render on the server.

  4. I re-measure after each change.

30. Explain reconciliation and the Fiber architecture.

Answer flow · 4 steps
  1. Reconciliation is how React compares the new element tree with the old one.

  2. It assumes elements of different types produce different trees, so it replaces them, and it uses keys to match children in lists, which keeps diffing close to linear time.

  3. Fiber, introduced in React 16, splits rendering into small units of work that can be paused, prioritised and resumed.

  4. That makes concurrent features possible: urgent updates such as typing can interrupt less urgent rendering.

31. What are concurrent features such as useTransition and Suspense?

Concurrent rendering lets React prepare a new UI in the background without blocking the main thread. useTransition marks an update as non-urgent, so a slow filtered list renders while the input stays responsive, and isPending can show a hint. useDeferredValue does the same for a value. Suspense shows a fallback while a lazily loaded component or data is not ready, and lets you control where loading states appear.

32. What are React Server Components, and how do they differ from SSR?

Answer flow · 4 steps
  1. Server-side rendering runs the normal components on the server to send HTML for a fast first paint, then sends all their JavaScript to the browser to hydrate.

  2. Server Components run only on the server and are never sent to the browser, so they can read the database directly and add no JavaScript to the bundle.

  3. Interactive parts are marked "use client" and hydrate as usual.

  4. In Next.js App Router components are server components by default.

33. How do you manage state in a large React application?

Answer flow · 6 steps
  1. I separate state by type.

  2. Local UI state stays in useState or useReducer next to where it is used.

  3. Server data goes in React Query or SWR, which handle caching, refetching and loading states.

  4. Truly global client state, such as the logged-in user or a cart, goes in context or a store like Redux Toolkit or Zustand.

  5. Filters and pagination live in the URL, and forms use a library such as React Hook Form.

  6. Most apps get simpler once server data is moved out of the global store.

34. How do you test React components?

Answer flow · 4 steps
  1. I use Jest or Vitest with React Testing Library, which tests components the way a user uses them: find elements by role or label, fire events with user-event, and assert on what appears on screen rather than on internal state.

  2. API calls are mocked at the network level with MSW.

  3. Custom hooks are tested with renderHook.

  4. A few end-to-end tests in Playwright or Cypress cover the critical user journeys.

35. What is new in React 19?

Answer flow · 4 steps
  1. Actions let async functions handle form submissions and transitions, with pending state, errors and optimistic updates managed for you through useActionState, useFormStatus and useOptimistic.

  2. The use API reads promises and context during render.

  3. Function components accept ref as a prop, so forwardRef is no longer needed.

  4. React can render title, meta and link tags anywhere and hoist them to the head, and Server Components and Server Actions are stable.

36. What is the React Compiler?

Answer flow · 3 steps
  1. The React Compiler is a build-time tool that automatically memoises components and values, so you rarely need to write useMemo, useCallback or React.memo by hand.

  2. It analyses your code to understand what depends on what, and only re-renders the parts whose inputs changed.

  3. It relies on code following the rules of React, such as pure render functions and no mutation of props or state, and its ESLint plugin flags code it cannot optimise.

37. What causes hydration errors, and how do you fix them?

A hydration error happens when the HTML rendered on the server does not match what React renders first in the browser. Common causes are using Date.now(), Math.random() or the user's locale during render, reading window or localStorage during render, browser extensions changing the HTML, and invalid HTML nesting such as a div inside a p. Fixes are to render client-only values inside useEffect after mount, pass consistent data from the server, fix the HTML, and use suppressHydrationWarning only for unavoidable differences such as timestamps.

38. How do you structure a large React codebase?

Answer flow · 3 steps
  1. I organise by feature rather than by file type: each feature folder holds its components, hooks, API calls, types and tests, with a small shared folder for UI components and utilities.

  2. Features expose a public index and avoid importing each other's internals.

  3. I separate server state from UI state, keep components small and focused, use TypeScript, path aliases and lint rules to enforce boundaries, and document conventions so new developers follow them.

39. How do you keep a React app secure?

Answer flow · 3 steps
  1. React escapes values in JSX by default, which prevents most XSS.

  2. The risks are dangerouslySetInnerHTML with untrusted content (sanitise with DOMPurify), user-supplied URLs in href that can contain javascript: links (validate them), and secrets in client code, since anything in the bundle is public.

  3. I keep auth tokens in HttpOnly cookies, use a Content Security Policy, keep dependencies updated, and validate everything again on the server.

40. How do you choose between Context, Redux Toolkit and Zustand?

Answer flow · 4 steps
  1. Context is built in and ideal for rarely changing values like theme and current user, but every consumer re-renders on change.

  2. Zustand is a tiny store with selectors, so components re-render only for the slice they use, and very little boilerplate, which suits most apps.

  3. Redux Toolkit adds strict structure, middleware, excellent devtools and RTK Query, which suits large teams and complex state.

  4. In all cases, server data is better handled by React Query or RTK Query than by hand.

React JS machine coding round questions

Tasks you build live in 30 to 60 minutes. What interviewers look for, plus a compact solution to compare with yours.

Build a search box that only calls the API after the user stops typing.

Tests effects, cleanup and debouncing in React. A strong answer debounces with a custom hook, cancels outdated requests, and handles empty input, loading and errors.

function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

function Search() {
  const [q, setQ] = useState('');
  const [results, setResults] = useState([]);
  const query = useDebounce(q);

  useEffect(() => {
    if (!query) return setResults([]);
    const controller = new AbortController();
    fetch('/api/search?q=' + encodeURIComponent(query), { signal: controller.signal })
      .then((r) => r.json())
      .then(setResults)
      .catch(() => {});
    return () => controller.abort();
  }, [query]);

  return (
    <>
      <label>Search <input value={q} onChange={(e) => setQ(e.target.value)} /></label>
      <ul>{results.map((r) => <li key={r.id}>{r.name}</li>)}</ul>
    </>
  );
}

Build a modal dialog using a portal.

Answer flow · 3 steps
  1. Tests portals, effects and accessibility.

  2. Close on Escape and on backdrop click, label the dialog, and in a full answer move focus into the dialog and return it on close.

  3. The native dialog element is a good alternative to mention.

function Modal({ open, onClose, title, children }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;
  return createPortal(
    <div className="backdrop" onClick={onClose}>
      <div role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
        <h2>{title}</h2>
        {children}
        <button onClick={onClose}>Close</button>
      </div>
    </div>,
    document.body
  );
}

Build a star rating component.

Small but revealing: state for the value and the hover preview, keyboard and screen-reader support, and a clean props API with value and onChange so it works as a controlled component.

function StarRating({ value, onChange, max = 5 }) {
  const [hover, setHover] = useState(0);
  return (
    <div role="radiogroup" aria-label="Rating" onMouseLeave={() => setHover(0)}>
      {Array.from({ length: max }, (_, i) => i + 1).map((n) => (
        <button key={n} type="button" role="radio" aria-checked={n === value}
          aria-label={n + (n === 1 ? ' star' : ' stars')}
          onMouseEnter={() => setHover(n)} onClick={() => onChange(n)}>
          {n <= (hover || value) ? '★' : '☆'}
        </button>
      ))}
    </div>
  );
}
Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Interview questions by react js skill

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields