
In this guide
React is the most requested front-end skill in job listings for web developers, so a React round is almost guaranteed if you apply for a front-end or full stack role. This guide has 51 React interview questions and answers, from "what is JSX?" to hooks, rendering performance, React 18 and React 19 features, plus coding exercises you can type out yourself.
Answers are written to be spoken in under a minute. Use Expand all to read everything at once, or open one question at a time as a self-test. Questions that mention a "gotcha" are the ones interviewers use to see whether you have actually built something.
Before you start
- React questions assume solid JavaScript. If you are rusty, go through our JavaScript interview questions first.
- Hooks (
useState,useEffect) and how rendering works are asked in nearly every interview. - Have one project you can walk through: what state it had, where, and why.
Learn React the Way Companies Hire For It
Leave your number and a Codeksha counsellor will call you back about the Frontend Development course and a free demo class.
React basics 12 questions
1What is React and why is it popular?
React is an open-source JavaScript library from Meta for building user interfaces out of reusable components. It is popular because of its component model, a declarative style (you describe what the UI should look like for a given state and React updates the DOM), a huge ecosystem and strong job demand.
2What is the virtual DOM and how does it work?
The virtual DOM is a lightweight JavaScript representation of the real DOM. When state changes, React builds a new virtual tree, compares it with the previous one (a process called reconciliation) and applies only the differences to the real DOM. Touching the real DOM less is what keeps updates fast.
3What is JSX?
JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. It is not valid JavaScript by itself; a compiler such as Babel or SWC turns it into function calls. JSX must return a single root element, uses className instead of class, and embeds JavaScript expressions in { }.
function Welcome({ name }) {
return <h1 className="title">Hello, {name}!</h1>;
}4What is the difference between a function component and a class component?
Function components are plain functions that return JSX and use hooks for state and lifecycle behaviour. Class components extend React.Component and use this.state and lifecycle methods. Function components with hooks are the modern standard; classes still work but are rarely written in new code. The one thing only classes can do is be an error boundary.
5What is the difference between props and state?
- Props are inputs passed from a parent to a child. They are read-only for the child.
- State is data a component owns and can change over time. Changing state re-renders the component.
Data flows one way, down the tree, from parent to child.
6Why do we need key when rendering lists?
Keys help React identify which items in a list were added, removed or reordered so it can update the DOM efficiently and keep the right component state attached to the right item. Use a stable unique id from your data. Using the array index as a key causes bugs when the list is reordered or filtered.
{todos.map(todo => <TodoItem key={todo.id} todo={todo} />)}7What are controlled and uncontrolled components?
In a controlled component, React state is the single source of truth for the input value (value plus onChange). In an uncontrolled component the DOM holds the value and you read it with a ref when needed. Controlled inputs make validation and instant feedback easy; uncontrolled inputs are simpler for basic forms.
const [email, setEmail] = useState("");
<input value={email} onChange={e => setEmail(e.target.value)} />8What does "lifting state up" mean?
When two sibling components need the same data, you move that state to their closest common parent and pass it down as props (with a callback to update it). It keeps one source of truth instead of two copies that can drift apart.
9What is a Fragment and why use it?
A Fragment (<>...</> or React.Fragment) lets a component return several elements without adding an extra wrapper div to the DOM. This keeps the HTML cleaner and avoids breaking layouts such as tables and flexbox.
10How do you render something conditionally in React?
Use a ternary (cond ? <A /> : <B />), the && operator for "show or nothing", or an early return. Be careful with && and numbers: {count && <List />} renders a literal 0 when count is 0, so write {count > 0 && ...}.
11What is the difference between an element and a component?
An element is a plain object describing what to show on screen (<div /> or <Button /> creates one). A component is a function (or class) that accepts props and returns elements. Components are the reusable blueprints; elements are what they produce each render.
12What is the children prop?
children is whatever you place between a component's opening and closing tags. It lets you build wrapper components like cards, modals and layouts that do not need to know what goes inside them.
function Card({ children }) {
return <div className="card">{children}</div>;
}
<Card><p>Anything goes here</p></Card>Hooks 14 questions
Hooks replaced most class-component patterns, so these questions are the core of a modern React interview.
13What are React hooks?
Hooks are functions that let function components use state and other React features. They were added in React 16.8. Examples are useState, useEffect, useContext, useRef, useMemo and useCallback. You can also write your own.
14What are the rules of hooks?
- Call hooks only at the top level of a component or custom hook, never inside loops, conditions or nested functions.
- Call hooks only from React function components or custom hooks, not regular JavaScript functions.
React tracks hooks by the order they are called, so that order must be the same on every render. The eslint-plugin-react-hooks rule checks this for you.
15How does useState work?
useState(initial) returns the current value and a setter function. Calling the setter schedules a re-render with the new value. When the new state depends on the previous one, pass a function so you never read a stale value.
const [count, setCount] = useState(0);
setCount(prev => prev + 1); // safe when updates are batched16Why is state update asynchronous, and what is batching?
setState does not change the variable immediately; it queues an update and React re-renders afterwards. Since React 18, updates inside event handlers, timeouts, promises and native events are all batched into one render for performance. If you read the state right after calling the setter, you still see the old value.
17How does useEffect work? What is the dependency array?
useEffect runs side effects (fetching data, subscriptions, timers, changing the document title) after the component renders. The dependency array decides when it re-runs:
- No array: after every render.
[]: once, after the first render.[a, b]: after the first render and wheneveraorbchanged.
useEffect(() => {
fetch("/api/courses").then(r => r.json()).then(setCourses);
}, []);18What is the cleanup function in useEffect?
If the effect returns a function, React runs it before the effect re-runs and when the component unmounts. Use it to remove event listeners, clear timers, close sockets and cancel requests so you do not leak memory or update an unmounted component.
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id); // cleanup
}, []);19What is the difference between useEffect and useLayoutEffect?
useEffect runs after the browser has painted, so it does not block the screen update. useLayoutEffect runs synchronously after DOM changes but before paint, which is useful for measuring layout (element sizes) and avoiding flicker. Use useEffect by default.
20What is useRef and when do you use it?
useRef returns a mutable object ({ current: ... }) that persists across renders and does not cause a re-render when changed. Use it to reach a DOM node (focus an input) or to keep a value between renders such as a timer id.
const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>21What is useMemo?
useMemo(fn, deps) caches the result of an expensive calculation and recomputes it only when its dependencies change. Do not wrap everything in it; measure first, because memoisation itself has a cost.
const visible = useMemo(
() => items.filter(i => i.price < max),
[items, max]
);22What is useCallback and how is it different from useMemo?
useCallback(fn, deps) returns the same function instance between renders unless the dependencies change. useMemo caches a value, useCallback caches a function (it is shorthand for useMemo(() => fn, deps)). It matters mainly when you pass a function to a child wrapped in React.memo.
23What is useContext and the Context API?
Context lets you share data such as theme, language or the logged-in user with any component in the tree without passing props through every level (prop drilling). You create it with createContext, provide a value with Context.Provider and read it with useContext. All consumers re-render when the value changes.
24When would you use useReducer instead of useState?
When state has several related values or complex update logic, such as a form or a shopping cart. A reducer function takes the current state and an action and returns the next state, which makes transitions predictable and easy to test.
function reducer(state, action) {
switch (action.type) {
case "add": return [...state, action.item];
case "remove": return state.filter(i => i.id !== action.id);
default: return state;
}
}
const [cart, dispatch] = useReducer(reducer, []);25What is a custom hook?
A custom hook is a function whose name starts with use and that calls other hooks to package reusable stateful logic, for example useFetch, useLocalStorage or useDebounce. Each component that calls it gets its own separate state.
function useLocalStorage(key, initial) {
const [value, setValue] = useState(
() => JSON.parse(localStorage.getItem(key)) ?? initial
);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}26What is a stale closure in hooks?
If an effect or callback captures a variable from one render and its dependency array does not list it, the function keeps seeing the old value. For example an interval that reads count but has [] as dependencies always logs the first value. Fix it by adding the dependency, using the functional form of the setter (setCount(c => c + 1)) or a ref.
Interview tip: Mentioning stale closures shows you understand hooks beyond the syntax.
Rendering and performance 6 questions
27What is reconciliation and how does React's diffing work?
Reconciliation is how React decides what to change in the DOM. It compares the old and new element trees with two assumptions: elements of different types produce different trees (so the whole subtree is rebuilt), and keys identify stable children in a list. This gives a fast O(n) comparison instead of a full tree diff.
28Why does a component re-render?
- Its own state changed.
- Its parent re-rendered (even if the props are the same).
- A context it consumes changed.
Re-rendering is cheap on its own; it only becomes a problem when it is slow or triggered too often. Props changing is not a separate trigger: a child re-renders because its parent did.
29What does React.memo do?
React.memo(Component) skips re-rendering a component when its props are shallowly equal to the previous props. It works best together with useCallback and useMemo so that object and function props keep the same identity between renders.
30What is code splitting, React.lazy and Suspense?
Code splitting breaks your bundle into smaller chunks that load on demand. React.lazy loads a component only when it is first rendered, and Suspense shows a fallback (such as a spinner) while it loads.
const Dashboard = React.lazy(() => import("./Dashboard"));
<Suspense fallback={<p>Loading...</p>}>
<Dashboard />
</Suspense>31How do you optimise a slow React app?
- Measure first with the React DevTools Profiler.
- Avoid unnecessary re-renders with
React.memo,useMemoanduseCallbackwhere it measurably helps. - Keep state as close as possible to where it is used.
- Virtualise long lists (react-window or similar).
- Split code with
React.lazyand optimise images. - Use stable keys and avoid creating components inside components.
32What is the difference between client-side rendering and server-side rendering?
With client-side rendering (CSR) the browser downloads JavaScript and builds the page on the device, which can be slow to show content and weak for SEO. With server-side rendering (SSR) the server sends ready HTML first and React then "hydrates" it to make it interactive, giving faster first paint and better SEO. Frameworks such as Next.js handle SSR and static generation.
Advanced and ecosystem 14 questions
Expect these in interviews for candidates with some experience or an internship.
33What is prop drilling and how do you avoid it?
Prop drilling is passing props through many layers of components that do not use them, just to reach a deeply nested child. Avoid it with the Context API, component composition (passing JSX as children) or a state library such as Redux Toolkit or Zustand.
34When would you use Redux instead of Context?
Context is good for low-frequency, app-wide values like theme or user. Redux (with Redux Toolkit) is better for large apps with complex shared state, frequent updates, middleware (async logic) and great debugging tools, because it lets components subscribe to only the slices they need. For many projects, local state plus Context or a small library like Zustand is enough.
35What is a higher-order component (HOC)?
A function that takes a component and returns a new component with extra behaviour, such as withAuth(Dashboard). HOCs were a common reuse pattern before hooks; custom hooks now cover most of those cases more simply.
36What are error boundaries?
An error boundary is a class component that catches JavaScript errors in its child tree during rendering and shows a fallback UI instead of crashing the whole app. They are written with componentDidCatch or static getDerivedStateFromError, or you can use the react-error-boundary library. They do not catch errors in event handlers or async code.
37What are portals?
ReactDOM.createPortal(children, domNode) renders children into a different DOM node outside the parent hierarchy, while keeping them in the same React tree. It is used for modals, tooltips and dropdowns that must escape overflow: hidden or z-index issues.
38What is StrictMode?
<React.StrictMode> is a development-only wrapper that highlights problems: it double-invokes render functions and effects to surface impure code and missing cleanups. It has no effect on the production build. If your useEffect seems to run twice in development, this is why.
39What changed in React 18?
- Concurrent rendering so React can interrupt and prioritise updates.
- Automatic batching of updates everywhere, not just in event handlers.
createRootas the new root API.useTransitionanduseDeferredValueto keep the UI responsive during heavy updates.- Streaming server rendering with
Suspense.
40What is new in React 19?
- Actions and the
useActionStatehook to handle form submissions and pending/error state. useOptimisticfor instant, optimistic UI updates.- The
useAPI to read a promise or context during render. refcan be passed as a normal prop in function components, soforwardRefis rarely needed.- Native support for document metadata (
<title>,<meta>) and stable Server Components support in frameworks.
Check the official React blog for the current version before an interview, because details keep evolving.
41What are React Server Components?
Server Components render on the server and send only the result to the browser, so their code and heavy dependencies never ship in the client bundle. They can read databases or files directly. Interactive parts are Client Components marked with "use client". They are used mainly through frameworks such as Next.js.
42What are synthetic events in React?
React wraps native browser events in a cross-browser object called a SyntheticEvent so that onClick, onChange and others behave the same everywhere. Handlers receive this object, and you can call e.preventDefault() and e.stopPropagation() on it.
43How do you handle forms and validation in React?
For simple forms use controlled inputs with useState. For bigger forms use a library such as React Hook Form (less re-rendering) together with a schema validator like Zod or Yup. Always validate on the server as well; client-side checks are for user experience, not security.
44How do you fetch data in a React component?
The basic pattern is fetch or Axios inside useEffect with loading and error state, plus a cleanup to ignore results from outdated requests. In real projects, a data library such as TanStack Query (React Query) or SWR handles caching, retries and refetching for you.
useEffect(() => {
let ignore = false;
fetch("/api/courses")
.then(r => r.json())
.then(data => { if (!ignore) setCourses(data); });
return () => { ignore = true; };
}, []);45How does routing work in React?
React itself has no router. React Router (or the file-based routers in Next.js) maps URLs to components without a full page reload. Key pieces are BrowserRouter, Routes/Route, Link/NavLink for navigation, and hooks like useParams and useNavigate.
46How do you test React components?
Use Jest or Vitest as the test runner and React Testing Library to render components and interact with them the way a user does (find by text or role, click, type) rather than testing implementation details. Use Playwright or Cypress for end-to-end tests.
Coding questions 5 questions
Small components that interviewers ask you to build live. Practise writing them from memory.
47Build a counter component with increment, decrement and reset.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(c => c - 1)}>-</button>
<button onClick={() => setCount(c => c + 1)}>+</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}48Build a search filter for a list.
function CourseList({ courses }) {
const [query, setQuery] = useState("");
const shown = courses.filter(c =>
c.title.toLowerCase().includes(query.toLowerCase())
);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
<ul>{shown.map(c => <li key={c.id}>{c.title}</li>)}</ul>
</>
);
}49Write a useDebounce hook.
function useDebounce(value, delay = 400) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}50Fetch and display users with loading and error states.
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(r => { if (!r.ok) throw new Error("Request failed"); return r.json(); })
.then(setUsers)
.catch(setError)
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Something went wrong</p>;
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}51Build a toggle (show/hide) component.
function Toggle() {
const [open, setOpen] = useState(false);
return (
<>
<button onClick={() => setOpen(o => !o)}>{open ? "Hide" : "Show"} details</button>
{open && <p>Here are the details.</p>}
</>
);
}How to Prepare for a React Interview
- Build two or three real apps. A to-do list with filters, a weather or news app that calls an API, and a small dashboard cover state, effects, lists, forms and routing.
- Learn why, not only how. Be ready to explain why a component re-rendered or why an effect ran twice. React DevTools Profiler helps you see it.
- Practise the coding questions above without looking, then compare. Interviewers care about clean state handling more than clever code.
- Know one state tool and one data-fetching approach. For example Context or Zustand, plus TanStack Query or plain
useEffectwith loading and error states. - Read the official docs. The react.dev learn section is the best free resource and is what many interviewers themselves rely on.
- Learn the stack around it. Git, a CSS approach, REST APIs and, for full stack roles, Node.js and a database. The full stack developer roadmap shows the order.
Frequently Asked Questions
What are the most asked React interview questions for freshers?
Freshers are usually asked: what is React, the virtual DOM, JSX, props vs state, keys in lists, controlled components, useState and useEffect, and how to share state between components. All of these are covered above.
Do I need to know class components?
You should recognise them because older codebases use them, and you may be asked about lifecycle methods or error boundaries. For new work, write function components with hooks.
Is React hard to learn for a beginner?
It is manageable if you already know JavaScript well: functions, arrays, objects, destructuring and async code. Most struggles come from weak JavaScript, not from React itself. Plan about four to six weeks of regular practice to be comfortable with core React.
Should I learn React or Angular first?
For most beginners, React: it has more job listings and a gentler start, and its ideas transfer to other frameworks. Angular is a full framework that is common in some large enterprises. Choose based on the jobs near you.
Is Next.js asked in React interviews?
For many product companies and startups, yes. Basic questions on SSR vs CSR, routing and data fetching are common. Learn core React first, then Next.js.
Want to Build React Projects With a Mentor?
Codeksha's Frontend Development course in Rajkot teaches HTML, CSS, JavaScript and React through live classes and real projects. Book a free demo class and see a session for yourself.
Book a Free Demo ClassGet Syllabus, Fees & a Free Demo
Tell us your number and a Codeksha counsellor will call you back about the Frontend Development course in Rajkot.


