Skip to content

React Fundamentals Interview Questions for MERN Stack

25 React Fundamentals questions with answers for mern stack roles — 13 easy, 12 medium.

About React Fundamentals

React builds user interfaces from reusable components. This topic covers JSX, props, state, rendering lists with keys, conditional rendering, forms, lifting state up, fragments, portals and routing with React Router. These fundamentals appear in almost every fresher and junior interview, often as live coding of a counter, todo list, form or data-fetching component.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is React and how does the virtual DOM help performance?

Save to ▾
Show answer
React is a JavaScript library for building user interfaces from reusable components. When state changes, React re-renders components into a lightweight in-memory tree called the virtual DOM, compares it with the previous tree through reconciliation, and applies only the minimal changes to the real DOM. Direct DOM updates are expensive, so batching and diffing keep updates efficient while letting developers write declarative code.
02

What is JSX and how is it converted into JavaScript?

Save to ▾
Show answer
JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. A compiler such as Babel, esbuild or SWC, used by Vite, turns each element into a function call that creates a React element object. JSX supports JavaScript expressions inside curly braces, uses className instead of class and htmlFor instead of for, and requires one parent element or a fragment.
03

What is the difference between props and state in React?

Save to ▾
Show answer
Props are inputs passed from a parent to a child component; they are read-only inside the child. State is data owned and managed by a component itself, created with useState or useReducer, and changing it triggers a re-render. A common pattern is that a parent keeps state and passes both the value and a setter function down as props to children.
04

Why are functional components preferred over class components today?

Save to ▾
Show answer
Functional components with hooks need less code, avoid confusion around this binding, and let you reuse stateful logic through custom hooks instead of higher-order components or render props. All new React features, such as Server Components and hooks like useActionState, target functions. Class components still work and appear in older codebases, and error boundaries still require a class or a library wrapper.
05

Why does React need keys in lists, and why is using the array index risky?

Save to ▾
Show answer
Keys tell React which list item is which between renders, so it can reuse, move or remove the correct DOM nodes and component state. Use stable unique ids, such as a MongoDB _id. Index keys break when items are inserted, removed or reordered: state such as input text or checkbox values can attach to the wrong item, and rendering becomes less efficient. Indexes are acceptable only for static lists.
06

What does lifting state up mean in React?

Save to ▾
Show answer
When two or more components need the same data, you move that state to their closest common parent and pass it down as props, along with functions to update it. For example, a filter bar and a product list both depend on the selected category, so the page component holds the category state. This keeps one source of truth and avoids components getting out of sync.
07

What are the common ways to render content conditionally in React?

Save to ▾
Show answer
Use an early return for whole-component cases like loading, an if statement outside JSX, the ternary operator for either-or markup, and logical && for show-or-hide. Be careful with && on numbers: count && <Badge /> renders 0 when count is zero, so use count > 0 && <Badge />. For many states, map a status value to components with an object lookup.
08

Two sibling components need to share data. How do you handle it?

Save to ▾
Show answer
Lift the shared state to their nearest common parent and pass the value to one sibling and an updater to the other. If the data is needed by many components deep in the tree, use Context or a state library like Zustand or Redux Toolkit. If the data comes from the server, a data-fetching library like TanStack Query can share the cached result across components.
09

How should a component display data loaded from an API in a user-friendly way?

Save to ▾
Show answer
Handle every state explicitly: show a skeleton or spinner while loading, an error message with a retry button if the request fails, an empty state with guidance when there is no data, and the content otherwise. Keep these in state variables or use a library like TanStack Query that provides isPending, isError and data. Never leave a blank screen or crash on undefined data.
10

Write a counter component using useState.

Save to ▾
Show answer
Use the functional updater when the new value depends on the old one. import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount((c) => c + 1)}>+</button> <button onClick={() => setCount((c) => c - 1)}>-</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); }
11

Write a controlled login form that submits to an API.

Save to ▾
Show answer
One state object and a shared change handler. function LoginForm() { const [form, setForm] = useState({ email: '', password: '' }); const onChange = (e) => setForm({ ...form, [e.target.name]: e.target.value }); const onSubmit = async (e) => { e.preventDefault(); const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) }); if (!res.ok) alert('Invalid credentials'); }; return ( <form onSubmit={onSubmit}> <input name='email' value={form.email} onChange={onChange} /> <input name='password' type='password' value={form.password} onChange={onChange} /> <button>Login</button> </form> ); }
12

Tell me about a time you received critical feedback on your UI code and how you responded.

Save to ▾
Show answer
Situation: in my internship, a senior reviewer rejected my pull request because my components were large and repeated logic. Task: fix it without missing the sprint deadline. Action: I asked for examples, split the page into smaller components, extracted a custom hook for the shared fetching logic and added prop types. Result: the PR was approved the next day, and the reviewer used my hook in another feature.
13

Why do you want to work as a MERN stack developer?

Save to ▾
Show answer
I enjoy building complete products, and MERN lets me use one language, JavaScript, across the database queries, the API and the user interface. In my projects, such as a job portal with React, Express and MongoDB, I liked seeing a feature go from schema to screen. The stack is widely used by startups and service companies in India, and I want to grow into a full stack engineer who owns features end to end.
14

What is the difference between controlled and uncontrolled components?

Save to ▾
Show answer
In a controlled component, form input values live in React state and change through onChange, so React is the single source of truth, which makes validation and conditional UI easy. In an uncontrolled component, the DOM holds the value and you read it with a ref or FormData when needed. Uncontrolled inputs mean fewer re-renders and suit simple forms and file inputs; libraries like React Hook Form use this approach.
15

How does routing work in a React single-page app using React Router?

Save to ▾
Show answer
React Router maps URL paths to components without full page reloads. You define routes, often with createBrowserRouter or Routes and Route elements, including nested routes that render inside a parent layout through Outlet. Link and NavLink change the URL, useNavigate navigates in code, and useParams reads dynamic segments like /products/:id. Recent versions also provide loaders and actions for data fetching and form submission.
16

How do class component lifecycle methods map to hooks?

Save to ▾
Show answer
componentDidMount maps to useEffect with an empty dependency array. componentDidUpdate maps to useEffect with specific dependencies. componentWillUnmount maps to the cleanup function returned from useEffect. shouldComponentUpdate is roughly React.memo, and getDerivedStateFromProps is usually replaced by computing values during render. The mindset shifts from lifecycle moments to synchronising with external systems whenever certain values change.
17

What are React fragments and portals?

Save to ▾
Show answer
A fragment, written <>...</> or <Fragment key={id}>, groups children without adding an extra DOM element, which keeps tables and flex layouts valid. A portal, created with createPortal(child, domNode), renders children into a different DOM node such as document.body while keeping them in the same React tree, so context and event bubbling still work. Portals are used for modals, tooltips and toasts that must escape overflow hidden containers.
18

Every time a user types in an input inside a list item, the input loses focus. What could be the cause?

Save to ▾
Show answer
The component is likely being remounted on each render. Common causes are generating keys randomly, such as key={Math.random()}, defining a component inside another component's body so it gets a new identity every render, or using index keys while the list reorders. Use stable ids as keys and move inner component definitions to the module level so React preserves their DOM and state.
19

You are building a registration form with ten fields and validation. How do you manage its state?

Save to ▾
Show answer
For a simple form, keep a single state object and update fields with a shared handler using the input name, for example setForm({ ...form, [e.target.name]: e.target.value }). Validate on blur and submit, storing errors in another object. For larger forms, use React Hook Form with a zod schema, which reduces re-renders and shares the validation schema with the Express backend.
20

How do you protect certain routes in React so that only logged-in users can access them?

Save to ▾
Show answer
Create a ProtectedRoute or layout component that reads auth state from context. If the user is not authenticated, return <Navigate to='/login' replace state={{ from: location }} />, otherwise render the Outlet or children. Show a loader while the session check is pending to avoid flicker. Remember that this is only for user experience; real protection must happen on the Express API by verifying tokens on every request.
21

A component calls setState inside useEffect and the app goes into an infinite render loop. Why?

Save to ▾
Show answer
The effect updates state, which re-renders, which runs the effect again. This happens when the dependency array is missing, or when a dependency is a new object or array created every render, or when the effect sets the same state it depends on. Add correct dependencies, move object creation inside the effect or memoize it, and ask whether the value can be calculated during render instead.
22

Fetch a list of users from an API inside useEffect with proper cleanup.

Save to ▾
Show answer
AbortController cancels the request if the component unmounts. function Users() { const [users, setUsers] = useState([]); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); fetch('/api/users', { signal: controller.signal }) .then((r) => r.json()) .then(setUsers) .catch((e) => { if (e.name !== 'AbortError') setError(e); }); return () => controller.abort(); }, []); if (error) return <p>Failed to load</p>; return <ul>{users.map((u) => <li key={u._id}>{u.name}</li>)}</ul>; }
23

Build a simple todo list in React with add and delete.

Save to ▾
Show answer
Update arrays immutably. function Todos() { const [todos, setTodos] = useState([]); const [text, setText] = useState(''); const add = (e) => { e.preventDefault(); if (!text.trim()) return; setTodos((t) => [...t, { id: crypto.randomUUID(), text }]); setText(''); }; const remove = (id) => setTodos((t) => t.filter((x) => x.id !== id)); return ( <form onSubmit={add}> <input value={text} onChange={(e) => setText(e.target.value)} /> <ul>{todos.map((t) => ( <li key={t.id}>{t.text} <button type='button' onClick={() => remove(t.id)}>x</button></li> ))}</ul> </form> ); }
24

Set up React Router with a layout, a list page and a detail page using useParams.

Save to ▾
Show answer
Data router setup with nested routes: import { createBrowserRouter, RouterProvider, Outlet, useParams } from 'react-router'; const Layout = () => (<><Navbar /><Outlet /></>); const ProductPage = () => { const { id } = useParams(); return <ProductDetails id={id} />; }; const router = createBrowserRouter([ { path: '/', element: <Layout />, children: [ { index: true, element: <Home /> }, { path: 'products', element: <ProductList /> }, { path: 'products/:id', element: <ProductPage /> } ] } ]); export default function App() { return <RouterProvider router={router} />; }
25

Tell me about a time you had to deliver a frontend feature under a tight deadline.

Save to ▾
Show answer
Situation: a client demo was moved two days earlier and our filters page was half done. Task: deliver a working version in time. Action: I agreed a reduced scope with the lead, reused existing components, built the three most-used filters first and wrote quick tests for them, and kept the team updated each evening. Result: the demo went well and the remaining filters shipped in the next sprint.

Frequently asked questions

How important is React Fundamentals in MERN Stack interviews?

React builds user interfaces from reusable components. This topic covers JSX, props, state, rendering lists with keys, conditional rendering, forms, lifting state up, fragments, portals and routing with React Router. These fundamentals appear in almost every fresher and junior interview, often as live coding of a counter, todo list, form or data-fetching component.

How should I use the React Fundamentals sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.