25 React Interview Questions
Click any question to expand the detailed answer. These cover the most commonly tested React concepts in interviews for frontend and full stack roles.
The virtual DOM (vDOM) is a lightweight JavaScript representation of the real DOM tree. React keeps a copy of the UI in memory. When state changes, React creates a new virtual DOM tree, diffs it against the previous one (reconciliation), and applies only the minimal set of changes to the real DOM.
Why this matters: Direct DOM manipulation is expensive. By batching and minimizing real DOM operations, React delivers fast, smooth UI updates even for complex applications.
Process:
- State/prop change triggers a re-render → React creates a new vDOM tree.
- React's diffing algorithm compares old vDOM vs new vDOM (O(n) complexity using heuristics).
- React computes the minimal set of DOM operations needed.
- React applies those changes to the real DOM in one pass.
React 18 introduced concurrent rendering which allows React to interrupt, pause, and resume rendering work — making the UI even more responsive.
The distinction is about who owns form element state: React or the DOM.
Controlled component: React state is the single source of truth. The input's value is driven by state, and every change updates state via an onChange handler.
function ControlledInput() {
const [value, setValue] = useState("");
return (
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
);
// React owns the value — DOM can't change it without setState
}
Uncontrolled component: The DOM manages its own state. You read the value using a ref when needed (e.g., on submit).
function UncontrolledInput() {
const inputRef = useRef();
function handleSubmit() {
console.log(inputRef.current.value); // read from DOM
}
return <input ref={inputRef} defaultValue="initial" />;
}
Rule of thumb: Prefer controlled components — they make validation, conditional disabling, and testing straightforward. Use uncontrolled for file inputs (<input type="file"> is always uncontrolled) or when integrating with non-React libraries.
useState is the fundamental React hook for adding local state to a functional component. It returns a state value and a setter function.
const [count, setCount] = useState(0);
// Update based on current value — use functional form
setCount(prev => prev + 1); // safe for multiple calls
// Lazy initial state (expensive computation runs once)
const [data, setData] = useState(() => parseHeavyData());
State updates are asynchronous. React does not immediately re-render after calling setState. It schedules a re-render. Reading state right after setting it gives the old value:
setCount(count + 1);
console.log(count); // still old value — React hasn't re-rendered yet
Batching (React 18+): React automatically batches multiple state updates in the same event handler (and now also in async callbacks, timeouts, and Promises) into a single re-render:
function handleClick() {
setCount(c => c + 1);
setName("Sai");
setVisible(true);
// React batches all three → ONE re-render
}
Before React 18, batching only happened inside React event handlers. With React 18's automatic batching, it works everywhere.
useEffect lets you perform side effects in functional components — things like fetching data, setting up subscriptions, updating the document title, or manually manipulating the DOM.
useEffect(() => {
// Side effect code here
return () => {
// Cleanup (runs before next effect or on unmount)
};
}, [dependencies]);
Dependency array controls when the effect runs:
useEffect(fn)— no array: runs after every render.useEffect(fn, [])— empty array: runs once after mount (likecomponentDidMount).useEffect(fn, [a, b])— runs after mount and wheneveraorbchanges.
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // only runs when count changes
// Data fetching pattern
useEffect(() => {
let cancelled = false;
async function load() {
const data = await fetchUser(userId);
if (!cancelled) setUser(data);
}
load();
return () => { cancelled = true; }; // cleanup prevents stale updates
}, [userId]);
useEffect always runs after the browser has painted — it is asynchronous and non-blocking. This differs from componentDidMount and componentDidUpdate which also run after render but are synchronous (blocking paint).
Lifecycle equivalents:
componentDidMount→useEffect(fn, [])componentDidUpdate→useEffect(fn, [dep])componentWillUnmount→ cleanup function returned fromuseEffectshouldComponentUpdate→React.memo/useMemo
// Class component lifecycle
componentDidMount() { this.fetchData(); }
componentDidUpdate(prevProps) {
if (prevProps.id !== this.props.id) this.fetchData();
}
componentWillUnmount() { this.subscription.unsubscribe(); }
// Equivalent with useEffect
useEffect(() => {
fetchData(id);
return () => subscription.unsubscribe();
}, [id]);
If you need to run synchronously before the browser paints (e.g., to measure DOM layout), use useLayoutEffect instead.
Prop drilling is when you pass data through multiple layers of components just to get it to a deeply nested child, even though intermediate components don't use that data themselves.
// Prop drilling — user passed through 3 levels
function App() {
const user = { name: "Sai" };
return <Page user={user} />;
}
function Page({ user }) {
return <Header user={user} />; // Page doesn't use user
}
function Header({ user }) {
return <Avatar user={user} />; // Header doesn't use user
}
function Avatar({ user }) {
return <img alt={user.name} />; // finally used here
}
Solutions:
- Context API — create a context, provide at the top, consume anywhere. Best for low-frequency updates (theme, auth user).
- Redux / Zustand / Jotai — global state stores. Better for high-frequency, complex state.
- Component composition — lift rendering responsibility to the parent, pass JSX as children or render props instead of data.
// Context solution
const UserContext = createContext(null);
function App() {
const user = { name: "Sai" };
return (
<UserContext.Provider value={user}>
<Page /> {/* no prop needed */}
</UserContext.Provider>
);
}
function Avatar() {
const user = useContext(UserContext); // access directly
return <img alt={user.name} />;
}
useContext lets a component subscribe to a React context and read its current value. When the context value changes, any component consuming it re-renders.
// 1. Create the context (usually in a separate file)
const ThemeContext = createContext('light');
// 2. Provide a value (wrap the subtree that needs it)
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Layout />
</ThemeContext.Provider>
);
}
// 3. Consume anywhere in the tree
function Button() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
className={theme === 'dark' ? 'btn-dark' : 'btn-light'}
onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}
>
Toggle Theme
</button>
);
}
Performance note: Every component consuming the context re-renders when the context value changes — even if they only use part of the value. For this reason, split contexts by concern (a ThemeContext separate from a UserContext) or use state management libraries for high-frequency updates.
useReducer is an alternative to useState for managing complex state logic. It works like Redux: you dispatch an action, a pure reducer function computes the next state.
const initialState = { count: 0, step: 1 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { ...state, count: state.count + state.step };
case 'decrement': return { ...state, count: state.count - state.step };
case 'setStep': return { ...state, step: action.payload };
case 'reset': return initialState;
default: throw new Error(`Unknown action: ${action.type}`);
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>
);
}
Use useReducer over useState when:
- State has multiple sub-values that update together.
- Next state depends on the previous state in complex ways.
- You have many related state transitions (a form with many fields and validation rules).
- You want to co-locate state logic in one reducer function for readability.
React.memo is a higher-order component that memoizes a functional component. If the component's props haven't changed (shallow comparison), React skips re-rendering and reuses the last rendered output.
// Without memo — re-renders every time parent re-renders
function ProductCard({ product }) {
console.log("re-render", product.name);
return <div>{product.name}: ${product.price}</div>;
}
// With memo — skips re-render if props are the same
const ProductCard = React.memo(function ProductCard({ product }) {
console.log("re-render", product.name);
return <div>{product.name}: ${product.price}</div>;
});
// Custom comparison
const ProductCard = React.memo(
function ProductCard({ product }) { /* ... */ },
(prevProps, nextProps) => prevProps.product.id === nextProps.product.id
);
Important caveats:
- React.memo only does a shallow comparison. If you pass a new object/array reference each render (even with same values), it still re-renders.
- Don't over-optimize — adding memo everywhere adds overhead. Use it when a component is expensive to render and its parent re-renders often with the same props.
- Combine with
useCallbackfor callback props — otherwise the new function reference breaks memoization.
Both are memoization hooks — they cache a value and only recompute when dependencies change. The difference is what they memoize.
useMemo — caches the result of a computation (a value).
// Expensive filter/sort runs only when products or filter changes
const filteredProducts = useMemo(() => {
return products
.filter(p => p.category === selectedCategory)
.sort((a, b) => a.price - b.price);
}, [products, selectedCategory]);
useCallback — caches a function reference. Returns the same function object as long as dependencies don't change.
// Without useCallback — new function reference every render
// breaks React.memo on ProductCard
const handleAddToCart = useCallback((productId) => {
dispatch({ type: 'ADD', payload: productId });
}, [dispatch]); // same function reference as long as dispatch doesn't change
// Now React.memo(ProductCard) works correctly
<ProductCard onAdd={handleAddToCart} />
Mental model: useMemo(() => computeValue(), deps) vs useCallback(() => doSomething(), deps) — the difference is useMemo calls the function and caches the return value, while useCallback caches the function itself without calling it.
Reconciliation is the process React uses to determine what changed in the virtual DOM tree and how to efficiently update the real DOM. React's algorithm (called Fiber since React 16) makes two key assumptions to achieve O(n) complexity:
- Different element types produce different trees. If the root element type changes (e.g.,
<div>→<section>), React tears down the old tree and builds a new one. - Keys hint at stable identity. When rendering lists, keys tell React which items are the same across renders — enabling it to reorder/update only what changed.
// Same type — React updates props
// Old: <Button color="blue" />
// New: <Button color="red" />
// → React updates color prop only, doesn't remount
// Different type — React remounts
// Old: <Input />
// New: <TextArea />
// → React destroys Input, mounts TextArea (all state lost!)
// Conditional rendering pitfall
{isLoggedIn ? <UserPanel /> : <GuestPanel />}
// Both are at the same position — React swaps components when isLoggedIn changes
Understanding reconciliation explains why keys matter, why component position in JSX affects state preservation, and why you should never define components inside render.
Keys give React a stable identity for each item in a list across renders. Without keys, React compares list items by position — which breaks when items are added, removed, or reordered.
// BAD — using index as key (breaks on add/remove/reorder)
products.map((p, i) => <ProductCard key={i} product={p} />)
// GOOD — using stable unique ID
products.map(p => <ProductCard key={p.id} product={p} />)
// Why index keys break:
// Before: [A(0), B(1), C(2)]
// After prepend: [X(0), A(1), B(2), C(3)]
// React thinks: "0's content changed" → updates A's DOM with X's data
// → incorrect — all items are re-rendered instead of just inserting X
// With ID keys:
// React sees: "A is still A, B is still B — just insert X before A"
// → minimal update, correct component identity
Rules for keys:
- Must be unique among siblings (not globally).
- Must be stable — same item = same key across renders.
- Use database IDs, UUIDs, or any stable unique property.
- Never use Math.random() as a key — generates new key every render.
Code splitting is the technique of splitting your JavaScript bundle into smaller chunks that are loaded on demand, rather than loading everything upfront. This reduces the initial load time of your app.
// Without code splitting — entire app in one bundle
import CheckoutPage from './pages/Checkout'; // loaded even if user never goes to checkout
// With React.lazy — loaded only when the component is rendered
const CheckoutPage = React.lazy(() => import('./pages/Checkout'));
const ProductDetail = React.lazy(() => import('./pages/ProductDetail'));
// Suspense shows a fallback while the chunk loads
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/checkout" element={<CheckoutPage />} />
<Route path="/product/:id" element={<ProductDetail />} />
</Routes>
</Suspense>
);
}
How it works under the hood: Bundlers (Webpack, Vite) see the dynamic import() call and split that module into a separate chunk file. The browser only downloads that chunk when React renders the lazy component for the first time.
In Next.js, route-level code splitting happens automatically — each page is its own chunk.
A Higher-Order Component (HOC) is a function that takes a component and returns a new enhanced component. It's a pattern for reusing component logic — a form of composition.
// HOC: withAuth — wraps any component with auth check
function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
const { isAuthenticated } = useAuth();
if (!isAuthenticated) {
return <Navigate to="/login" />;
}
return <WrappedComponent {...props} />;
};
}
// Usage
const ProtectedDashboard = withAuth(Dashboard);
const ProtectedCheckout = withAuth(CheckoutPage);
// HOC: withLoadingSpinner
function withLoading(WrappedComponent) {
return function({ isLoading, ...props }) {
if (isLoading) return <Spinner />;
return <WrappedComponent {...props} />;
};
}
HOCs were the primary code-reuse pattern before hooks. Today, custom hooks are generally preferred — they're less verbose, easier to compose, and avoid wrapper hell. HOCs are still useful for cross-cutting concerns like authentication guards and analytics wrappers.
The render props pattern shares code by passing a function as a prop — that function tells the component what to render. The component calls it with its internal state.
// MouseTracker provides mouse position via render prop
function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div onMouseMove={e => setPos({ x: e.clientX, y: e.clientY })}>
{render(pos)} {/* call the render prop with internal state */}
</div>
);
}
// Usage — consumer decides what to render with the position
<MouseTracker render={({ x, y }) => (
<p>Mouse: {x}, {y}</p>
)} />
// Also common via children prop
<MouseTracker>
{({ x, y }) => <p>{x}, {y}</p>}
</MouseTracker>
Like HOCs, render props solve code-sharing but pre-date hooks. Custom hooks now handle most of these cases more cleanly. Render props are still valuable for library authors (e.g., Downshift, React Table's older API) and for component APIs that need to expose internal state to the consumer.
Functional components (with hooks) are the modern standard. Class components still exist in legacy codebases.
// Class component
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.increment = this.increment.bind(this);
}
increment() { this.setState({ count: this.state.count + 1 }); }
componentDidMount() { document.title = `Count: ${this.state.count}`; }
render() {
return <button onClick={this.increment}>{this.state.count}</button>;
}
}
// Functional component (equivalent)
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => { document.title = `Count: ${count}`; }, [count]);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
Key differences:
- Functional components are simpler — no
this, no constructor, less boilerplate. - Hooks allow functional components to do everything class components can (and more).
- Only class components have
componentDidCatch/getDerivedStateFromError— Error Boundaries still require classes (though React 19 is introducing hook-based error boundaries). - Functional components capture props/state at render time (closures) — class components access current values via
this.
A custom hook is a JavaScript function that starts with use and can call other hooks. It extracts stateful logic so it can be shared between components without altering component hierarchy.
// Custom hook: useLocalStorage
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
} catch { return initialValue; }
});
const setStoredValue = useCallback((newValue) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
}, [key]);
return [value, setStoredValue];
}
// Usage — feels just like useState, but persists to localStorage
function Cart() {
const [items, setItems] = useLocalStorage('cart', []);
// items survive page refresh!
}
// Another example: useFetch
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(r => r.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);
return { data, loading, error };
}
Custom hooks are the recommended replacement for HOCs and render props when you want to share logic. They compose naturally and don't add extra DOM nodes.
Both solve the problem of sharing state across the component tree — but they are designed for different use cases.
- Context API: Built into React. Simple. Best for low-frequency state (theme, language, auth user). Every consumer re-renders when context changes — can cause performance issues if overused with high-frequency updates.
- Redux: Predictable state container with a single global store, action dispatching, and pure reducers. Excellent DevTools (time-travel debugging). Better for large apps with complex, high-frequency state (cart, filters, real-time data). More boilerplate but more control.
// Context — simple, built-in
const ThemeContext = createContext('light');
// Provider → Consumer via useContext
// Redux Toolkit — structured, scalable
const cartSlice = createSlice({
name: 'cart',
initialState: [],
reducers: {
addItem: (state, action) => { state.push(action.payload); },
removeItem: (state, action) => state.filter(i => i.id !== action.payload),
}
});
export const { addItem, removeItem } = cartSlice.actions;
// dispatch(addItem(product)) anywhere in the app
Rule of thumb: Start with Context. Migrate to Redux (or Zustand) when Context causes performance issues or state logic becomes too complex to manage across components.
React Portals allow you to render a child component into a DOM node that exists outside the parent component's DOM hierarchy — while still maintaining React's event bubbling and context access.
// Without portals — modal is nested inside the component tree
// Can get clipped by overflow:hidden, z-index stacking issues
// With portals — modal renders at document.body level
import { createPortal } from 'react-dom';
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
{children}
</div>
</div>,
document.body // render here — outside component's DOM parent
);
}
// In parent:
<Modal isOpen={showModal} onClose={() => setShowModal(false)}>
<h2>Confirm Order</h2>
</Modal>
Common uses: Modals/dialogs, tooltips, dropdown menus, notifications, any overlay that needs to break out of overflow: hidden containers or z-index stacking contexts. Events from the portal still bubble up through the React tree (not the DOM tree).
Dynamic import (import()) is a JavaScript language feature that loads a module asynchronously on demand, returning a Promise. It works for any module — not just React components.
React.lazy wraps a dynamic import specifically for React components, integrating it with React's rendering and Suspense system.
// Dynamic import — general purpose, any module
async function loadChart() {
const { Chart } = await import('chart.js');
new Chart(canvas, config);
}
// Dynamic import for non-component data
const { data } = await import('./largeDataset.json');
// React.lazy — wraps dynamic import for React components
// Must return a module with a default export that is a React component
const ProductDetail = React.lazy(() => import('./pages/ProductDetail'));
const AdminPanel = React.lazy(() => import('./pages/AdminPanel'));
// Must be wrapped in Suspense
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/product/:id" element={<ProductDetail />} />
<Route path="/admin" element={<AdminPanel />} />
</Routes>
</Suspense>
);
}
Think of React.lazy as dynamic import + React.Suspense integration. The component chunk only downloads when that route/component is first rendered.
React.StrictMode is a development-only tool that helps you find potential problems in your application. It renders nothing in the DOM but activates extra checks and warnings.
// Enable Strict Mode for the whole app (in main.jsx/index.js)
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// Or for just part of your app
function AdminSection() {
return (
<React.StrictMode>
<AdminPanel />
</React.StrictMode>
);
}
What Strict Mode does (in development):
- Double-invokes render functions and state updater functions to catch side effects in pure functions.
- Warns about deprecated lifecycle methods (
componentWillMount, etc.). - Detects components that use string refs.
- Warns about using legacy Context API.
- Mounts, unmounts, and re-mounts components once on initial render to verify cleanup behavior.
Does NOT affect production builds. If you see a useEffect running twice on mount in development, Strict Mode is the reason — and it's intentional.
React uses a synthetic event system — it wraps native DOM events in a cross-browser compatible wrapper called SyntheticEvent. Rather than attaching event listeners to each DOM node, React attaches a single listener at the root of the DOM tree (event delegation at the framework level).
// Looks like native event handling, but it's synthetic
function Button() {
function handleClick(e) {
// e is a SyntheticEvent — normalized across browsers
e.preventDefault(); // works the same as native
e.stopPropagation(); // works the same
console.log(e.nativeEvent); // access native event if needed
}
return <button onClick={handleClick}>Click</button>;
}
// Key differences:
// 1. camelCase event names: onClick, onChange, onSubmit (not onclick)
// 2. Pass function references, not strings: onClick={fn} not onclick="fn()"
// 3. In React 17+, events attach to the root container, not document
// 4. SyntheticEvent pooling was removed in React 17 (no longer need e.persist())
The synthetic event system ensures consistent behavior across browsers (especially important for older IE quirks) and enables React to optimize event handling through delegation.
Suspense is a React component that lets you declaratively specify a loading state for any part of the component tree that is "waiting" for something — originally designed for code splitting, now extended to data fetching.
// Code splitting with Suspense (widely available)
const ProductPage = React.lazy(() => import('./ProductPage'));
function App() {
return (
<Suspense fallback={<PageSkeleton />}>
<ProductPage />
</Suspense>
);
}
// Data fetching with Suspense (via frameworks like Next.js, Relay, React Query)
// The component "suspends" by throwing a Promise
// React catches it, shows the fallback, then re-renders when it resolves
function UserProfile({ userId }) {
const user = use(fetchUser(userId)); // React 19 use() hook
return <div>{user.name}</div>;
}
// Nested Suspense — granular loading states
<Suspense fallback={<LayoutSkeleton />}>
<Layout>
<Suspense fallback={<ContentSkeleton />}>
<MainContent />
</Suspense>
</Layout>
</Suspense>
Suspense shifts the loading state pattern from imperative (if (loading) return <Spinner>) to declarative — the component simply renders its final state, and the parent handles loading.
useRef returns a mutable ref object with a .current property. Two key characteristics distinguish it from state:
- Changing
ref.currentdoes NOT trigger a re-render. - The ref object persists for the full lifetime of the component.
// Use case 1: Access a DOM element directly
function SearchBar() {
const inputRef = useRef(null);
function focus() {
inputRef.current.focus(); // direct DOM access
}
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focus}>Focus</button>
</>
);
}
// Use case 2: Store mutable values without triggering re-render
function Timer() {
const intervalRef = useRef(null);
function start() {
intervalRef.current = setInterval(() => {
console.log("tick");
}, 1000);
}
function stop() {
clearInterval(intervalRef.current); // access the stored interval ID
}
return <><button onClick={start}>Start</button><button onClick={stop}>Stop</button></>;
}
// Use case 3: Capture previous value
function usePrevious(value) {
const ref = useRef();
useEffect(() => { ref.current = value; }); // runs after render
return ref.current; // returns previous value
}
React is fast by default, but common mistakes can cause unnecessary re-renders, memory leaks, and slow UI:
- Inline object/array props:
<Component style={{ color: 'red' }} />creates a new object reference every render, breakingReact.memo. Fix: define outside component or useuseMemo. - Inline arrow functions as props:
<Button onClick={() => handleClick(id)} />creates a new function each render. Fix:useCallbackor wrap differently. - Defining components inside render: React treats inner components as new types each render, unmounting/remounting them. Always define components at module scope.
- Missing useEffect cleanup: Event listeners, intervals, and subscriptions left running cause memory leaks and stale state bugs.
- Not using keys properly: Using index as key breaks reconciliation and causes incorrect state on reordering.
- Over-fetching in useEffect: Missing or wrong dependencies cause infinite request loops or stale data.
- Context causing unnecessary re-renders: Putting frequently changing state in a context that many components consume — every consumer re-renders on each change.
- Not code splitting large routes: Loading the entire app bundle upfront increases initial load time.
Profiling tools: React DevTools Profiler shows which components re-render and why. Use it before optimizing — don't guess.
Ready to nail your React interview?
Ramayai builds React developers who ship production apps.
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →