React JS Interview Questions and Answers With Examples (2025)

Before diving into React interview questions, your fundamentals must be solid. If you’re shaky on HTML, CSS, or JavaScript, you’re going to struggle with real-world React code, let alone interviews. Ensure you spend time mastering the core building blocks of the frontend before delving into React-specific concepts.
That said, let’s walk through some of the most frequently asked React.js interview questions. Each one covers not just the “what,” but the “why,” and includes code examples to help you understand how it works.
At a high level, we will cover:
- Core React Interview Questions
- React Router Questions
- React Testing Questions
- State Management Questions
- React Performance Questions
This chapter goes deep on the core topics. For a wider question bank, including hooks, React 19, Server Components, and senior-level questions, see 300+ React interview questions and answers.
Let’s begin!
Core React Interview Questions
What are props and state in React, and what’s the difference?
Props are read-only values passed from a parent component to a child. State is local data managed within an element itself. Props are immutable from the child’s perspective, while state can be updated via hooks like useState.
// Functional component with both props and state
import React, { useState } from "react";
function Counter({ title }) {
const [count, setCount] = useState(0); // state: owned by this component
return (
<div>
<h2>{title}</h2> {/* prop: passed from parent */}
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
What is the Virtual DOM, and how does it work?
The Virtual DOM is an in-memory representation of the actual Document Object Model (DOM). When state or props change, React creates a new virtual DOM tree, compares it with the previous one (diffing), and updates only the parts of the real DOM that changed, minimizing expensive DOM operations.
What is React Fiber, and what are its main goals?
React Fiber is the internal engine behind React’s rendering. It allows React to break rendering work into small units and pause or resume it, improving responsiveness for complex UI updates. Its primary goals are concurrency, interruptible rendering, and better scheduling.
What are Higher-Order Components (HOCs) in React?
A Higher-Order Component is a function that takes a component and returns a new element with enhanced behavior. It’s a typical pattern for code reuse.
// A simple HOC that adds a "theme" prop
function withTheme(Component) {
return function ThemedComponent(props) {
return <Component {...props} theme="dark" />;
};
}
function Button(props) {
return <button className={props.theme}>Click</button>;
}
const ThemedButton = withTheme(Button);
What’s the difference between useMemo and useCallback?
useMemo caches a computed value; useCallback caches a function. Use useMemo when you want to avoid expensive recalculations (see the useMemo docs). Use useCallback when you want to avoid re-creating a function on every render.
import React, { useMemo, useCallback, useState } from "react";
function Example({ items }) {
const [count, setCount] = useState(0);
// Cached sorted items (useMemo)
const sorted = useMemo(() => {
return [...items].sort();
}, [items]);
// Cached click handler (useCallback)
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<button onClick={handleClick}>Increment</button>
<ul>{sorted.map(i => <li key={i}>{i}</li>)}</ul>
</div>
);
}
How do you memoize a component and why?
Use React.memo to memoize functional components. It prevents unnecessary re-renders when props haven’t changed. This is useful for optimizing performance, especially in large lists or deeply nested UIs.
const Greeting = React.memo(function Greeting({ name }) {
console.log("Rendered!");
return <p>Hello, {name}!</p>;
});
// Will only re-render if `name` changes
How do you loop inside JSX to create elements?
You can loop using JavaScript’s map() function to generate JSX dynamically. This is commonly used to render lists.
function List({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
Why should you not update props in React?
Props are meant to be immutable — the parent component controls them. Updating props inside a child breaks the unidirectional data flow in React and can cause unpredictable bugs.
// ❌ Never do this
function MyComponent(props) {
props.title = "New Title"; // Invalid
}
Can you use async/await In React?
Yes. You can use async/await inside event handlers, or inside useEffect (just not directly in the effect function — you must define an async function inside it).
import { useEffect, useState } from "react";
function UserProfile() {
const [user, setUser] = useState(null);
useEffect(() => {
async function fetchUser() {
const res = await fetch("/api/user");
const data = await res.json();
setUser(data);
}
fetchUser(); // Call the async function
}, []);
return user ? <p>Hello {user.name}</p> : <p>Loading...</p>;
}
What are the most commonly used hooks in React?
React provides a number of built-in hooks to manage state, side effects, and performance. Some of the most commonly used ones include:
useState– For managing local stateuseEffect– For running side effects after renderuseMemo– For memoizing expensive valuesuseCallback– For memoizing functionsuseRef– For persisting values between renders (without re-rendering)useContext– For accessing context across your component tree
What are custom hooks and when should you use them?
Custom hooks let you extract reusable logic from components into separate functions that can be reused across your app. They follow the same rules as built-in hooks and start with the word use.
// Custom hook to get current window width
import { useState, useEffect } from "react";
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
// Usage
function App() {
const width = useWindowWidth();
return <p>Current width: {width}px</p>;
}
What’s the difference between functional and class-based components?
Class components use class syntax and require you to use this, while functional components are simpler, more concise, and use hooks for state and lifecycle logic. As of today, functional components are the standard in modern React.
// Class component
class Greeting extends React.Component {
render() {
return <p>Hello {this.props.name}</p>;
}
}
// Functional component (preferred)
function Greeting({ name }) {
return <p>Hello {name}</p>;
}
Why does the virtual DOM exist?
The virtual DOM exists to improve performance and simplify UI updates. Manipulating the real DOM is slow. React batches updates in a virtual DOM (a lightweight JS object), then figures out the minimal set of changes needed, and updates the real DOM efficiently.
What are error boundaries in React?
Error boundaries are React components that catch JavaScript errors in their child components and display a fallback UI instead of breaking the app. You can only define error boundaries using class components (see the React docs on error boundaries).
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Caught error:", error);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
What are React lifecycle methods (or hook equivalents)?
In class components, lifecycle methods include:
componentDidMountcomponentDidUpdatecomponentWillUnmount
In functional components, the equivalent is the useEffect hook.
// Equivalent of componentDidMount
useEffect(() => {
console.log("Component mounted");
}, []);
What happens if the dependency array in useEffect is empty?
If the dependency array is empty [], the effect runs only once after the first render — like componentDidMount. If you omit the dependency array entirely, the effect runs on every render, which can lead to performance issues.
What is a ref in React, and why is it useful?
A ref is a way to access and interact with DOM elements or store a mutable value without triggering a re-render. Useful for focusing inputs, measuring layout, or storing timeouts.
import { useRef, useEffect } from "react";
function InputFocus() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus(); // Access DOM node directly
}, []);
return <input ref={inputRef} />;
}
What is useContext and when would you use it?
useContext gives you access to values provided by a React Context provider without the need for prop drilling. Use it when you need to share state across multiple components (such as themes or authentication).
// Create context
const ThemeContext = React.createContext("light");
// Use it in a component
function ThemeLabel() {
const theme = React.useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
// Wrap part of the app
<ThemeContext.Provider value="dark">
<ThemeLabel />
</ThemeContext.Provider>
What are the different phases of a React component’s lifecycle?
React components go through these phases:
- Mounting – Component is created and added to the DOM
- Updating – Component re-renders due to props or state change
- Unmounting – Component is removed from the DOM
In functional components, you use useEffect with dependencies to handle each phase. You can return a cleanup function from useEffect to mimic componentWillUnmount.
useEffect(() => {
// Mounting
console.log("Component mounted");
// Cleanup
return () => {
console.log("Component unmounted");
};
}, []);
React Router Interview Questions
What is the purpose of push and replace in React Router history?
The history.push() and history.replace() methods let you navigate programmatically in React Router. The difference is:
push()adds a new entry to the history stack (user can go back).replace()replaces the current entry (user can’t go back).
history.push("/dashboard"); // Navigate to dashboard, keep history
history.replace("/login"); // Navigate to login, replace current entry
How do you programmatically navigate using React Router 4+?
You can use the useNavigate hook in React Router v6+ or the useHistory hook in v5 to navigate programmatically.
// React Router v6+
import { useNavigate } from "react-router-dom";
function RedirectButton() {
const navigate = useNavigate();
return (
<button onClick={() => navigate("/home")}>Go Home</button>
);
}
// React Router v5
import { useHistory } from "react-router-dom";
function RedirectButton() {
const history = useHistory();
return (
<button onClick={() => history.push("/home")}>Go Home</button>
);
}
How do you get query parameters from React Router?
In React Router v6, use useSearchParams(). In React Router v5, use useLocation() with the browser’s URLSearchParams API.
// React Router v6
import { useSearchParams } from "react-router-dom";
function Page() {
const [searchParams] = useSearchParams();
const user = searchParams.get("user");
return <p>User: {user}</p>;
}
// React Router v5
import { useLocation } from "react-router-dom";
function Page() {
const location = useLocation();
const query = new URLSearchParams(location.search);
const user = query.get("user");
return <p>User: {user}</p>;
}
How do you pass parameters with history.push() in React Router 4?
You can pass route parameters using the URL or state object.
// Using URL params
history.push("/user/123");
// Using state
history.push({
pathname: "/user",
state: { userId: 123 },
});
—
React Testing Interview Questions
What is shallow rendering in React testing?
Shallow rendering is a technique where only the component itself is rendered, not its children. It’s useful when testing a component in isolation without worrying about its descendants.
// With Enzyme
import { shallow } from "enzyme";
import MyComponent from "./MyComponent";
const wrapper = shallow(<MyComponent />);
What is the react-test-renderer package?
react-test-renderer is a package from React that allows you to render components to pure JavaScript objects without depending on the DOM. It’s useful for snapshot testing.
import renderer from "react-test-renderer";
import MyComponent from "./MyComponent";
const tree = renderer.create(<MyComponent />).toJSON();
expect(tree).toMatchSnapshot();
What is Jest?
Jest is a JavaScript testing framework created by Meta and now maintained by the OpenJS Foundation. It’s used to write unit tests, mock functions, and create snapshots. Jest is the default test runner for most React apps (like those created with Create React App).
What are the advantages of Jest over Jasmine?
Jest builds on top of Jasmine but adds powerful features like:
- Built-in mocking and spies
- Zero config setup with CRA
- Snapshot testing support
- Better DX with watch mode and rich assertions
Can you show a simple Jest test case using React?
// Counter.js
export function Counter({ count }) {
return <p>Count: {count}</p>;
}
// Counter.test.js
import { render, screen } from "@testing-library/react";
import { Counter } from "./Counter";
test("renders count", () => {
render(<Counter count={5} />);
expect(screen.getByText(/Count: 5/)).toBeInTheDocument();
});
State Management Interview Questions
What are the pros and cons of using Redux?
Pros:
- Centralized state management
- Predictable state transitions through pure reducers
- Time-travel debugging with Redux DevTools
- Great ecosystem and middleware support (like Thunks, Sagas)
Cons:
- Boilerplate-heavy without proper abstraction
- Can be overkill for small to medium apps
- Steeper learning curve for new developers
What’s the difference between mapStateToProps and mapDispatchToProps?
mapStateToProps connects Redux state to your component’s props, while mapDispatchToProps connects action dispatchers to your props so you can trigger state changes.
// Example:
const mapStateToProps = (state) => ({
count: state.counter,
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: "INCREMENT" }),
});
At a high level, how do Redux patterns work?
Redux follows a unidirectional data flow:
- Action: A plain JS object that describes what happened.
- Reducer: A pure function that takes the current state and the action, and returns the new state.
- Dispatch: Sends the action to the Redux store to update the state.
// Action
const incrementAction = { type: "INCREMENT" };
// Reducer
function counterReducer(state = 0, action) {
if (action.type === "INCREMENT") {
return state + 1;
}
return state;
}
// Dispatch
dispatch(incrementAction);
What’s the difference between React Context and React Redux?
Both allow you to share state across your app, but they serve different purposes:
- React Context: A Simple, built-in tool for global values (like theme or language).
- Redux: Full-blown state management library with predictable state handling, devtools, and middleware for side effects.
If you’re passing values deeply and only need read/write access in a few places, it useContext works well. If you’re managing complex app-wide state with multiple async flows, Redux might be a better fit.
What are the downsides of using Redux?
The most significant downsides are complexity and boilerplate. For simple apps, Redux can feel like too much work to wire up. It also introduces more abstraction, which can confuse newer devs if not well-documented. Performance isn’t always better unless it is carefully optimized.
Should you keep all your component state in the Redux store?
No. Only keep **shared state** that multiple components rely on in Redux. UI-specific or temporary state (like modals, inputs, animations) should stay local in the element using useState.
What’s the proper way to access the Redux store?
In React-Redux, use the useSelector hook to read the state and useDispatch to send actions. This is the recommended approach in functional components.
import { useSelector, useDispatch } from "react-redux";
function Counter() {
const count = useSelector((state) => state.counter);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: "INCREMENT" })}>Add</button>
</div>
);
}
What is a Redux Thunk?
A Redux Thunk is a middleware that lets you write action creators that return a function instead of an object. It’s commonly used to handle asynchronous logic, such as fetching data. The Redux docs on thunks cover the pattern in depth.
export const fetchUser = () => {
return async (dispatch) => {
dispatch({ type: "USER_LOADING" });
const res = await fetch("/api/user");
const data = await res.json();
dispatch({ type: "USER_SUCCESS", payload: data });
};
};
How do you measure Redux performance?
Use the Redux DevTools extension. It allows you to inspect every dispatched action, see how state changes over time, and track slow reducers or significant updates.
How do you improve Redux performance?
Some key ways to improve Redux performance:
- Use
React.memoanduseMemoto avoid unnecessary re-renders - Split large reducers to avoid full app updates
- Use selector libraries like
reselectto memoize computed data - Keep your store flat and normalized
When should you use Redux over useContext or useState?
Use useState for the local state. Use useContext for a lightweight global state (themes, authentication user, etc.). Use Redux when:
- You have shared state across many components
- You need middleware or complex side-effect handling
- You want predictable, debuggable state transitions
That said, if your app doesn’t have complex global state, stick to useState and useContext — They’re lighter and easier to work with.
React Performance Optimization Interview Questions
How do you solve performance corner cases with React?
It depends on the root cause, but in general:
- Use
React.memoto avoid unnecessary re-renders - Use
useCallbackanduseMemoto memoize values and handlers - Use virtualization (e.g.,
react-window,react-virtualized) for long lists - Lazy load components using
React.lazyandSuspense - Throttle or debounce expensive state updates (like scroll listeners)
How do you audit your React app to find performance bottlenecks?
Use React DevTools Profiler to record a render pass and inspect which components are re-rendering too often or taking too long. You can also:
- Track prop changes with the
why-did-you-renderpackage - Use console timing (
console.time()) to measure function execution - Inspect slow components with the Flamegraph view in Profiler
Are there any online tools available to help with performance auditing?
Yes. These tools help audit your bundle size, load times, and runtime performance:
- Lighthouse (Chrome DevTools) – Page load, TTI, and performance score
- WebPageTest.org – Waterfall breakdowns and paint metrics
- Bundlephobia – Package size insights
- SpeedCurve – Continuous front-end performance monitoring
If Redux is a bottleneck, how can it be optimized?
A few things to try:
- Use
useSelectorwith memoized selectors (likereselect) - Split reducers to avoid full app updates on every action
- Normalize deeply nested state
- Use
React.memoto prevent re-renders on unchanged props - Avoid dispatching actions on every keystroke — debounce or batch them
If your initial page load is slow, how would you optimize it?
Some ways to speed up your initial load:
- Code-split with
React.lazyandSuspense - Preload critical assets using
<link rel="preload"> - Use smaller bundle sizes (analyze with
webpack-bundle-analyzer) - Serve assets via CDN and compress them (gzip or brotli)
- Inline critical CSS and defer non-essential JS
How do you measure page load time?
You can use:
- Lighthouse – First Contentful Paint (FCP), Largest Contentful Paint (LCP)
- Performance tab in Chrome DevTools – Record load timeline
window.performance.timing– For custom tracking- Third-party tools like SpeedCurve or New Relic
You want to run a performance experiment. How would you measure improvements?
Use A/B testing or feature flags:
- Measure time-based metrics like TTI, LCP, scroll jank before/after
- Track render time of specific components (e.g. using
performance.now()) - Use Mixpanel or custom analytics events to compare user impact
Compare metrics across real user sessions to validate gains.
Scrolling feels janky and stutters. How would you fix it?
Common fixes:
- Use
requestAnimationFramefor smooth animations - Debounce scroll handlers to prevent frequent re-renders
- Use virtualized lists to avoid DOM overload
- Avoid triggering layout thrashing (e.g., calling
getBoundingClientRectrepeatedly)
How do you measure scroll performance?
Use the Chrome DevTools Performance tab:
- Record a scroll session
- Look for long scripting or layout paint times
- Watch for forced reflows or excessive layout recalculations
You can also track scroll FPS using Chrome’s rendering tab or `fps-meter` overlays.
How do you detect memory leaks in React?
Memory leaks in React usually happen when components retain references after unmounting — like open subscriptions, timeouts, or event listeners that were never cleaned up.
To detect them:
- Use Chrome DevTools → Performance → Heap snapshot tab
- Watch for detached DOM nodes in the memory graph
- Use the
why-did-you-renderlibrary to spot unnecessary renders - Use
useEffectcleanup functions to remove listeners, timers, or subscriptions
useEffect(() => {
const interval = setInterval(() => {
// polling logic
}, 1000);
return () => {
clearInterval(interval); // Clean up to prevent memory leaks
};
}, []);
How do you add security to a React application?
While React handles UI, it’s still your job to secure the app from common threats:
- Prevent XSS: Avoid using
dangerouslySetInnerHTMLunless properly sanitized - Use HTTPS: Always serve over HTTPS to protect data in transit
- Escape user input: Never trust user-generated content directly in the DOM
- Use HTTP-only cookies: For storing auth tokens (avoid localStorage when possible)
- Set CORS headers properly: Especially on APIs
- Rate limit and throttle: Backend endpoints to prevent abuse
Also consider tools such as Content Security Policy (CSP), security headers, and automated scanners like npm audit or OWASP ZAP during the CI/CD process.
The questions above would cover a majority of React JS interview questions. Now, let’s move on to Frontend Trivia questions.
