ReactJS Developers play an important role in building fast and interactive web applications. They create reusable UI components to managing state, React developers work with modern JavaScript libraries and frameworks. Also build dynamic front-end interfaces. Companies around the world hire React developers for websites, SaaS platforms, dashboards, and mobile apps using React Native.
This React JS Interview Questions guide provides comprehensive preparation for all experience levels. The guide covers basic to intermediate concepts for freshers, hooks and performance optimization for experienced developers, and scenario based questions.
These questions are designed to help candidates prepare for junior to senior ReactJS roles, ensuring thorough coverage of essential React concepts and advanced techniques needed in modern web development.
Table of Contents
React JS Interview Questions and Answers for Freshers
Que 1. What is ReactJS used for?
Answer:
ReactJS is a JavaScript library used to build user interfaces, especially for single-page applications. It allows developers to create reusable UI components and manage the view layer of web applications efficiently.
Que 2. What is a component in ReactJS?
Answer:
A component in ReactJS is a reusable piece of code that represents part of the UI. Components can be either class-based or functional and help break down the UI into smaller, manageable parts.
Que 3. What is JSX in React?
Answer:
JSX stands for JavaScript XML. It allows developers to write HTML-like syntax in JavaScript files, making it easier to describe the UI structure directly within JavaScript code.
Example:
const element = <h1>Hello, World!</h1>;
Que 4. What are props in React?
Answer:
Props (short for properties) are read-only inputs passed from a parent component to a child component. Props help make components dynamic and reusable by supplying them with data.
Que 5. What is state in React?
Answer:
State is a built-in object that allows components to track and manage changing data. Unlike props, state is local to the component and can change over time using the useState
hook or this.setState()
.
Que 6. What are default props in React and how do you define them?
Answer:
Default props are fallback values for props that are not explicitly passed to a component. In class components, they can be set using Component.defaultProps
, while in functional components, they can be defined by assigning default values in the function parameter.
Que 7. How do you create a functional component in ReactJS?
Answer:
A functional component is a JavaScript function that returns JSX.
Example:
function Welcome() {
return <h1>Hello, React!</h1>;
}
Que 8. What is the virtual DOM?
Answer:
The virtual DOM is a lightweight copy of the real DOM. React updates the virtual DOM first, compares it with the previous version, and then efficiently updates only the changed parts in the actual DOM.
Que 9. How do synthetic events differ from native events in React?
Answer:
Synthetic events are wrappers around native events in React that provide a consistent API across browsers. They improve performance with event delegation but behave slightly differently than native events.
Que 10. What are custom hooks in React and when would you use them?
Answer:
Custom hooks are user-defined functions that encapsulate reusable logic using React hooks. They are used when you want to share stateful logic, like handling forms or fetching data, across multiple components without duplicating code.
Que 11. What is conditional rendering in React?
Answer:
Conditional rendering means displaying content based on conditions using operators like if, ternary operator, or logical AND (&&) within JSX.
Example:
{isLoggedIn ? <Dashboard /> : <Login />}
Que 12. What are the rules of hooks in React?
Answer:
Hooks must always be called at the top level of a functional component or custom hook. They cannot be used inside loops, conditions, or nested functions. Additionally, all hook names must begin with the prefix use
.
Que 13. How do you pass props to a component?
Answer:
Props are passed using attributes in JSX.
Example:
<Greeting message="Hello User!" />
Que 14. What are fragments in React?
Answer:
Fragments let you group multiple elements without adding extra nodes to the DOM.
Example:
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
Que 15. What are keys in React lists?
Answer:
Keys are unique identifiers used when rendering lists in React. They help React identify which items have changed or been removed.
Example:
{items.map(item => <li key={item.id}>{item.name}</li>)}
Que 16. What is prop drilling in React?
Answer:
Prop drilling is the process of passing props through multiple levels of components, even when intermediate components don’t need them, just to reach a child component.
Que 17. How do you validate form inputs in React?
Answer:
Form validation in React can be done by managing input values in state and applying conditions before submission. For complex validation, libraries like Formik or React Hook Form can be used.
Que 18. What is a pure component?
Answer:
A pure component is a component that renders the same output for the same state and props. React provides React.PureComponent to prevent unnecessary re-renders.
Que 19. What are the limitations of class components compared to functional components?
Answer:
Class components require more boilerplate, are harder to test, and don’t support hooks directly. Functional components are simpler, encourage cleaner code, and fully leverage hooks for state and lifecycle management.
Que 20. How do you handle file uploads in React forms?
Answer:
File uploads can be managed using <input type="file" />
. The selected file is accessed via event.target.files
and uploaded using APIs like fetch
or axios
with FormData
.

Also Check: Java interview Questions and Answers
Que. 21 What is the difference between state and props in React?
Answer:
State and props are both plain JavaScript objects used to manage data in React components, but they serve different purposes. State is internal to a component and managed within it, allowing the component to change its data over time, typically in response to user actions or events. Props (short for properties) are passed to a component from its parent and are read-only, meaning the component cannot modify them; they are used for communication between components.
State is mutable and can be updated using the setState
method in class components or hooks like useState
in functional components, triggering a re-render. Props are immutable and help make components reusable and configurable.
Example:
import React, { useState } from 'react';
function Child(props) {
return <p>Hello, {props.name}!</p>; // Props are read-only
}
function Parent() {
const [count, setCount] = useState(0); // State is mutable
return (
<div>
<Child name="User" />
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
</div>
);
}
Use state for dynamic data like form inputs, and props for static or passed-down data.
Que. 22 Explain the useState hook with an example code snippet.
Answer:
The useState
hook is a built-in React hook that allows functional components to manage local state. It returns an array with two elements: the current state value and a function to update it. Calling the update function triggers a re-render with the new state.
It simplifies state management compared to class components’ this.state
and this.setState
. Initial state can be a value or a function for lazy computation.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initial state is 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
This creates a counter that increments on button click. For complex state, use objects or arrays, but update immutably to avoid bugs.
Que. 23 How does the useEffect hook work? Provide a code example.
Answer:
The useEffect
hook runs side effects in functional components, such as data fetching, subscriptions, or DOM manipulations. It takes a callback function and an optional dependency array. Without dependencies, it runs after every render; with an empty array, it runs once on mount; with dependencies, it runs when they change.
It can return a cleanup function for unmounting, like clearing intervals.
Example:
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => setSeconds(seconds + 1), 1000);
return () => clearInterval(interval); // Cleanup
}, []); // Empty array: runs once on mount
return <p>Seconds: {seconds}</p>;
}
This creates a timer that increments every second. Use it for effects that need synchronization with state or props.
Que. 24 What are controlled and uncontrolled components in React?
Answer:
Controlled components have their form data managed by React state, where the value is set via props and updated via event handlers. This ensures single source of truth and enables validation or dynamic updates.
Uncontrolled components manage their own state internally using DOM refs, without React controlling the value. They are simpler for one-off forms but harder to validate.
Controlled example:
import React, { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState('');
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
Uncontrolled: Use ref
to access input.value
on submit. Prefer controlled for most cases to leverage React’s reactivity.
Que. 25 How do you handle forms in React? Provide a basic example.
Answer:
Forms in React are handled using controlled components for state management and event handlers for updates. On submit, prevent default behavior and process data. Use useState
for individual fields or libraries like Formik for complex forms.
Example:
import React, { useState } from 'react';
function SimpleForm() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
}
This captures input and alerts on submit. For multiple fields, use an object state.
Que. 26 What is the significance of React’s reconciliation process?
Answer:
Reconciliation is React’s process of updating the DOM by comparing the virtual DOM with the previous version. It determines the minimal number of changes needed, improving performance by avoiding unnecessary DOM updates.
Que. 27 What are React fibers and why were they introduced?
Answer:
React Fiber is the new reconciliation engine introduced in React 16. It improves rendering by breaking work into smaller units, enabling features like async rendering and smoother user experience.
Que. 28 What happens if keys are not used properly in React lists?
Answer:
If keys are missing or not unique, React may reuse or misplace DOM elements, leading to incorrect rendering, poor performance, and unexpected UI behavior.
Que. 29 How can you pass data from a child to a parent component?
Answer:
Data can be passed from child to parent using callback functions. The parent passes a function as a prop, and the child calls that function with data as an argument.
Que. 30 What is the Context API and when to use it?
Answer:
Context API provides a way to share data across the component tree without prop drilling. It creates a Provider component that supplies value, and Consumers (or useContext
hook) access it.
Use it for global data like themes, user auth, or locale, avoiding deep prop passing.
Example:
import React, { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
}
function Child() {
const theme = useContext(ThemeContext);
return <p>Theme: {theme}</p>;
}
It’s built-in; for complex state, combine with useReducer
.
Que. 31 Explain React Router and how to set up basic routing.
Answer:
React Router is a library for client-side routing in single-page apps, handling URL changes without full page reloads. It uses components like BrowserRouter
, Routes
, Route
, and Link
.
Setup:
Install: npm install react-router-dom
Example:
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<nav><Link to="/">Home</Link> | <Link to="/about">About</Link></nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
This enables navigation between views. Use useParams
for dynamic routes.
Que. 32 What are higher-order components (HOCs) in React?
Answer:
HOCs are functions that take a component and return an enhanced version, adding reusable logic like authentication or logging without modifying the original.
Example:
function withLogger(WrappedComponent) {
return function(props) {
console.log('Rendering', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const Enhanced = withLogger(MyComponent);
Use for cross-cutting concerns. Alternatives: Hooks or render props for simpler cases.
Que. 33 How do you optimize performance in a React application?
Answer:
Optimize by minimizing re-renders: Use React.memo
for pure components, useMemo
for expensive computations, useCallback
for stable functions.
Code-split with lazy
and Suspense
for faster loads. Avoid unnecessary state updates. Profile with React DevTools to identify bottlenecks.
Example with useMemo
:
const expensiveValue = useMemo(() => computeExpensive(data), [data]);
This prevents recomputation on every render unless data
changes.
Que. 34 What is memoization in React? Provide an example with useMemo.
Answer:
Memoization caches results of expensive functions, recomputing only on input changes. In React, useMemo
memoizes values.
Example:
import React, { useMemo } from 'react';
function Component({ list }) {
const sortedList = useMemo(() => list.sort((a, b) => a - b), [list]);
return <ul>{sortedList.map(item => <li key={item}>{item}</li>)}</ul>;
}
This sorts only when list
changes, improving performance for large arrays.
Que. 35 How do you handle events in React?
Answer:
Events in React use camelCase handlers like onClick
, passing functions that receive synthetic events (cross-browser wrappers).
Example:
function Button() {
const handleClick = (event) => {
event.preventDefault();
console.log('Clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
Bind this
in classes or use arrows. Events bubble; use event.stopPropagation()
to stop.
Que. 36 What are portals in React and when should you use them?
Answer:
Portals allow rendering children into a DOM node outside the parent hierarchy. They are useful for modals, tooltips, and dropdowns where the element needs to escape the container’s styling or stacking context.
Que. 37 Explain lifecycle methods in React class components.
Answer:
Lifecycle methods are hooks into component phases: Mounting (constructor
, render
, componentDidMount
), Updating (shouldComponentUpdate
, render
, componentDidUpdate
), Unmounting (componentWillUnmount
).
Example: componentDidMount
for API calls, componentWillUnmount
for cleanup.
Functional equivalents: useEffect
. Class methods are legacy but useful for understanding older code.
Que. 38 How do you fetch data in React components?
Answer:
Fetch data using useEffect
with async functions or libraries like Axios. Handle loading, error states.
Example:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(setData)
.catch(console.error);
}, []);
return data ? <p>{data.title}</p> : <p>Loading...</p>;
}
Use async/await
inside useEffect
with IIFE for cleanliness.
Que. 39 What is the difference between Context API and Redux?
Answer:
The Context API is built into React and best for lightweight state sharing. Redux is an external library suited for large applications needing predictable state management, middleware, and debugging tools.
Que. 40 What is basic testing in React using Jest? Provide a simple test example.
Answer:
Jest is a testing framework for React, used with React Testing Library for component tests. Write unit tests for rendering, events.
Install: npm install --save-dev jest @testing-library/react
Example test:
import { render, screen } from '@testing-library/react';
import Greeting from './Greeting';
test('renders greeting', () => {
render(<Greeting name="World" />);
expect(screen.getByText('Hello, World!')).toBeInTheDocument();
});
Run with npm test
. Focuses on user-visible behavior, not implementation.
Also Check: React interview questions for Freshers
React.JS Interview Questions and Answers for Experienced
Que 41. What is React.memo and when should you use it?
Answer:React.memo
is a higher-order component that prevents unnecessary re-renders by memoizing the rendered output of functional components. Use it when your component renders the same output with the same props to improve performance.
Example:
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
Que 42. Explain useCallback and its purpose.
Answer:useCallback
is a React hook that memoizes a function, preventing it from being recreated on every render unless its dependencies change. This helps optimize performance, especially when passing functions to child components.
Example:
const memoizedCallback = useCallback(() => {
doSomething();
}, [dependency]);
Que 43. What is the difference between useEffect and useLayoutEffect?
Answer:
useEffect
runs after the DOM has been painted.useLayoutEffect
runs synchronously after DOM mutations but before painting.
UseuseLayoutEffect
when you need to read layout from the DOM and synchronously re-render.
Que 44. How do you handle performance optimization in large React applications?
Answer:
- Use
React.memo
,useMemo
, anduseCallback
. - Use lazy loading with
React.lazy()
andSuspense
. - Avoid unnecessary re-renders.
- Split code and load components on demand.
- Optimize state management.
Que 45. What are React hooks rules when using Context API?
Answer:
When using Context with hooks, useContext
must follow React’s rules of hooks: it can only be called inside functional components or custom hooks, not inside loops, conditions, or nested functions.
Que 46. What is the purpose of useReducer in React?
Answer:useReducer
is a React hook used for managing complex state logic. It’s similar to Redux reducer but localized within a component.
Example:
const [state, dispatch] = useReducer(reducer, initialState);
Que 47. How do you implement lazy loading in React?
Answer:
Use React.lazy()
and Suspense
for component lazy loading.
Example:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
Que 48. What is server-side rendering (SSR) in React?
Answer:
SSR means rendering React components on the server and sending the fully rendered HTML to the client. Tools like Next.js are used for SSR, improving SEO and initial page load time.
Que 49. What are Higher-Order Components (HOC)?
Answer:
An HOC is a function that takes a component and returns a new component with additional features or props. Used for code reuse and logic abstraction.
Example:
function withLogger(Component) {
return function(props) {
console.log('Component rendered');
return <Component {...props} />;
}
}
Que 50. What is the difference between useMemo and React.memo?
Answer:useMemo
memoizes values within a component to avoid recalculations, while React.memo
is a higher-order component that memoizes the entire component to prevent unnecessary re-renders.
Que 51. Explain React Portals.
Answer:
React Portals let you render children into a DOM node outside the parent component’s DOM hierarchy. Useful for modals, tooltips, and overlays.
Example:
ReactDOM.createPortal(child, document.getElementById('modal-root'));
Que 52. How do you manage global state in React?
Answer:
Tool/Method | Purpose |
---|---|
Context API | Built-in React method for sharing state across components |
Redux / Redux Toolkit | Centralized state management with middleware support |
Zustand | Lightweight and minimal global state management |
Recoil | State management with React-like atoms and selectors |
Jotai | Primitive and scalable state management |
Selection Criteria | Choose based on app complexity and performance needs |
Que 53. What is Concurrent Mode in React?
Answer:
Concurrent Mode is an experimental feature that allows React to interrupt rendering, prioritize tasks, and improve responsiveness by rendering multiple UI versions simultaneously.
Que 54. Explain error boundaries in React.
Answer:
Error boundaries are React components that catch JavaScript errors in child components and display fallback UIs instead of breaking the app.
Example:
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
// Handle error
}
render() {
return this.props.children;
}
}
Que 55. How do you debug performance issues in React applications?
Answer:
- Use React DevTools Profiler
- Analyze render timings and component re-renders
- Use browser developer tools for network and memory monitoring
- Optimize unnecessary renders using memoization techniques

Also Check: ExpressJS Interview Questions and Answers
Que 56. What is prop drilling and how do you avoid it?
Answer:
Prop drilling involves passing props through multiple nested components. It can be avoided using Context API, Redux, or other global state management solutions.
Que 57. How do you handle API calls in React?
Answer:
- Use
useEffect
for fetching data on component mount - Use
fetch()
or libraries like Axios - Handle loading, success, and error states for better UX
- Use libraries like React Query for advanced data fetching and caching
Que 58. How do you manage form state in React?
Answer:
- Use controlled components with local state using
useState
- Use libraries like Formik or React Hook Form for complex forms
- Validate input using custom logic or libraries like Yup
Que 59. What’s the difference between Controlled and Uncontrolled components?
Answer:
- Controlled components: Form data handled by React state.
- Uncontrolled components: Form data handled by DOM itself using refs.
Que 60. How do you implement SSR with React?
Answer:
- Use frameworks like Next.js for built-in SSR support
- On the server, render React components to HTML using
ReactDOMServer.renderToString()
- Send rendered HTML to the browser and hydrate using client-side React
Que. 61 How would you optimize a React application’s performance when dealing with large lists or complex renders?
Answer:
For experienced developers, optimizing React performance involves identifying bottlenecks using tools like React Profiler or Chrome DevTools. Key strategies include memoization with React.memo
for pure components to prevent unnecessary re-renders, and useMemo
/useCallback
for expensive computations or stable callbacks. Implement virtualization with libraries like react-window
or react-virtualized
for large lists, rendering only visible items (e.g., 10-20 out of 1000+). Use code splitting with React.lazy
and Suspense
for dynamic imports to reduce initial bundle size. Avoid inline functions in render props to prevent child re-renders. Finally, batch updates with unstable_batchedUpdates
or ensure state updates are minimal.
Example with virtualization:
import { FixedSizeList as List } from 'react-window';
function LargeList({ items }) {
return (
<List height={400} itemCount={items.length} itemSize={35} width={300}>
{({ index, style }) => <div style={style}>{items[index]}</div>}
</List>
);
}
This renders efficiently, common in dashboards or feeds.
Que. 62 Explain the differences between Redux and Context API for state management, and when to choose one over the other.
Answer:
Redux is a global state management library with a single store, actions, reducers, and middleware for complex logic like async operations (e.g., Redux Thunk or Saga). It enforces unidirectional data flow and is scalable for large apps with debugging tools like Redux DevTools. Context API is built-in React for sharing state without prop drilling, using Providers and Consumers/useContext
, but lacks built-in middleware or immutability enforcement.
Choose Context API for medium-scale apps with simple global state (e.g., themes, user prefs) to avoid boilerplate. Use Redux for enterprise apps needing traceability, async handling, or plugins. For 2-5 years experience, hybrid approaches (Context + useReducer) mimic Redux for lighter apps, reducing bundle size by 50-70KB.
Example with Context:
const ThemeContext = createContext('light');
<ThemeContext.Provider value="dark"><Child /></ThemeContext.Provider>
Que. 63 How do you implement error boundaries in React, and what are their limitations?
Answer:
Error boundaries catch JavaScript errors in child component trees during rendering, lifecycle methods, or constructors, using static getDerivedStateFromError
for fallback UI and componentDidCatch
for logging. They are class components only; for hooks, use libraries like react-error-boundary
.
Limitations: Don’t catch event handlers, async code (e.g., setTimeout), SSR errors, or errors in the boundary itself. Place them strategically around risky components.
Example:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
return this.state.hasError ? <h1>Something went wrong.</h1> : this.props.children;
}
}
// Usage: <ErrorBoundary><BuggyComponent /></ErrorBoundary>
This prevents app crashes, essential for production stability.
Que. 64 Describe how to handle authentication in a React app with protected routes using React Router.
Answer:
For authentication, store tokens in localStorage or HttpOnly cookies (for security). Use Context or Redux for auth state. With React Router v6, create protected routes via a wrapper component checking auth, redirecting to login if unauthorized.
Advantages: Centralized auth logic, easy integration with JWT or OAuth.
Example with Router v6:
import { Outlet, Navigate } from 'react-router-dom';
function ProtectedRoute({ isAuth }) {
return isAuth ? <Outlet /> : <Navigate to="/login" />;
}
// In App: <Routes><Route element={<ProtectedRoute isAuth={auth} />}><Route path="/dashboard" element={<Dashboard />} /></Route></Routes>
For experienced devs, add role-based access and refresh tokens with interceptors (e.g., Axios).
Que. 65 What is the useReducer hook, and how does it compare to useState for complex state logic?
Answer:useReducer
manages complex state with a reducer function (like Redux), taking state and action, returning new state. It’s ideal for interdependent state or multiple transitions.
Compared to useState
, it’s better for logic-heavy states (e.g., forms with validation) as it centralizes updates, improving readability. useState
suits simple values.
Example:
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
default: return state;
}
}
const [state, dispatch] = useReducer(reducer, initialState);
// Usage: <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
This scales for apps with 5+ state variables.
Que. 66 How would you implement server-side rendering (SSR) in a React app using Next.js?
Answer:
Next.js enables SSR with getServerSideProps
or getStaticProps
for data fetching. Pages are pre-rendered on the server, improving SEO and initial load.
Steps: Create pages in /pages
, export async functions for props. For dynamic data, use getServerSideProps
; for static, getStaticProps
with revalidation.
Advantages: Better SEO, faster TTFB, accessibility.
Example:
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
function Page({ data }) {
return <div>{data.title}</div>;
}
For experienced, discuss hydration mismatches and API routes.
Que. 67 Explain concurrent mode in React and how it improves user experience.
Answer:
Concurrent mode (introduced in React 18) allows interrupting rendering for urgent updates, using features like startTransition
for non-urgent tasks and Suspense for async boundaries. It breaks work into chunks, prioritizing interactions.
Advantages: Smoother UI (no blocking renders), better for large apps with heavy computations. Enables transitions for deferred updates.
Example:
import { startTransition } from 'react';
startTransition(() => setInputValue(debouncedValue)); // Non-urgent search update
Limits: Experimental in older versions; requires root changes with createRoot
.
Que. 68 How do you test React components using Jest and React Testing Library?
Answer:
Jest runs tests; React Testing Library (RTL) focuses on user interactions. Write unit/integration tests querying by role/text, simulating events.
For experienced, cover async (act), mocks (jest.fn), snapshots.
Example:
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('increments counter', () => {
render(<Counter />);
fireEvent.click(screen.getByText('Increment'));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
This ensures behavior testing over implementation.
Que. 69 What are portals in React, and provide a use case with code.
Answer:
Portals render children into a DOM node outside the parent hierarchy, useful for modals, tooltips avoiding overflow issues.
Use ReactDOM.createPortal(child, container)
.
Example for modal:
import ReactDOM from 'react-dom';
function Modal({ children }) {
return ReactDOM.createPortal(children, document.getElementById('modal-root'));
}
// Usage: <Modal><div>Modal Content</div></Modal>
Advantages: Maintains event bubbling while escaping CSS constraints.
Que. 70 How would you implement lazy loading for images or components in React to improve initial load time?
Answer:
Lazy loading defers offscreen resources. For images, use loading="lazy"
attribute. For components, React.lazy
with Suspense.
Example for component:
const LazyComponent = React.lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
For images: <img src="image.jpg" loading="lazy" alt="desc" />
. Reduces TTI by 20-30% in large apps; combine with Intersection Observer for custom logic.
Que. 71 Describe render props pattern and when to use it over HOCs.
Answer:
Render props pass a function as prop that returns React elements, sharing code between components.
Example:
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
// ... track mouse
return render(position);
}
// Usage: <MouseTracker render={pos => <p>X: {pos.x}, Y: {pos.y}</p>} />
Use over HOCs for more flexibility (no wrapper components), especially with multiple consumers. HOCs suit simple enhancements; render props for dynamic rendering.
Que. 72 How do you handle global state with Redux Toolkit, including slices and async thunks?
Answer:
Redux Toolkit simplifies Redux with createSlice
for reducers/actions, configureStore
for setup, and createAsyncThunk
for async.
Example:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const fetchData = createAsyncThunk('data/fetch', async () => {
const res = await fetch('/api');
return res.json();
});
const dataSlice = createSlice({
name: 'data',
initialState: { items: [], status: 'idle' },
extraReducers: (builder) => {
builder.addCase(fetchData.pending, (state) => { state.status = 'loading'; });
builder.addCase(fetchData.fulfilled, (state, action) => { state.items = action.payload; state.status = 'succeeded'; });
},
});
Advantages: Less boilerplate, built-in immutability. For experienced, integrates with RTK Query for API caching.
Que. 73 What is the Suspense component, and how does it work with data fetching?
Answer:
Suspense pauses rendering until async operations (e.g., lazy loading, data fetch) resolve, showing fallback.
With React 18, use with use
hook or libraries like React Query.
Example:
<Suspense fallback={<div>Loading...</div>}>
<LazyLoadedComponent />
</Suspense>
For fetching: Wrap fetch in promise-throwing component. Advantages: Cleaner code, better UX with loading states without manual flags.
Que. 74 How would you secure a React application against common vulnerabilities like XSS or CSRF?
Answer:
For XSS, React escapes output by default; avoid dangerouslySetInnerHTML
or sanitize inputs (e.g., DOMPurify). For CSRF, use tokens in headers for API calls (e.g., Axios interceptors). Store JWT in HttpOnly cookies, not localStorage. Use HTTPS, validate inputs, and libraries like react-helmet
for CSP headers.
Example sanitizer:
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />
Regular audits with tools like OWASP ZAP. Critical for apps handling user data.
Que. 75 Explain the useCallback hook and its role in preventing unnecessary re-renders.
Answer:useCallback
memoizes functions, returning the same reference unless dependencies change, preventing child re-renders from new function instances.
Example:
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
// Pass to child: <Child onClick={memoizedCallback} />
Use with React.memo
on children. Advantages: Optimizes performance in lists or callbacks; avoid overusing to prevent memory leaks.
Que. 76 How do you implement internationalization (i18n) in a React app?
Answer:
Use libraries like react-i18next
or react-intl
. Load translations from JSON files, wrap app in provider, use hooks for strings.
Example with i18next:
import { useTranslation } from 'react-i18next';
function Component() {
const { t } = useTranslation();
return <p>{t('welcome')}</p>;
}
// Setup: i18n.init({ resources: { en: { translation: { welcome: 'Hello' } } } });
Advantages: Dynamic language switching, pluralization, formatting. For experienced, server-side i18n with Next.js.
Que. 77 What are compound components in React, and provide an example.
Answer:
Compound components share implicit state via context, allowing flexible composition (e.g., Select with Options).
Example:
const TabsContext = createContext();
function Tabs({ children, activeTab }) {
return <TabsContext.Provider value={activeTab}>{children}</TabsContext.Provider>;
}
function Tab({ id, children }) {
const active = useContext(TabsContext);
return <div className={active === id ? 'active' : ''}>{children}</div>;
}
// Usage: <Tabs activeTab="1"><Tab id="1">Tab1</Tab><Tab id="2">Tab2</Tab></Tabs>
Advantages: Expressive API without prop explosion, seen in libraries like Reach UI.
Que. 78 How would you debug a React application that’s experiencing memory leaks?
Answer:
Use Chrome DevTools Memory tab for heap snapshots, comparing before/after actions to find retained objects. Check for unclosed subscriptions in useEffect
cleanup. Tools like React DevTools highlight frequent re-renders.
Common causes: Global variables, event listeners without removal, large state objects.
Example cleanup:
useEffect(() => {
const handleResize = () => {};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
For experienced, profile with why-did-you-render
library.
Que. 79 Describe how to use React Query for data fetching and caching.
Answer:
React Query manages server state with queries/mutations, providing caching, refetching, and optimistic updates.
Install: npm i @tanstack/react-query
Example:
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
return <QueryClientProvider client={queryClient}><Component /></QueryClientProvider>;
}
function Component() {
const { data, isLoading } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
if (isLoading) return <div>Loading...</div>;
return <ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>;
}
Advantages: Automatic caching (stale-while-revalidate), background updates, reduces boilerplate vs manual fetch.
Que. 80 What is the role of service workers in Progressive Web Apps (PWAs) built with React?
Answer:
Service workers are scripts running in background for offline support, caching, and push notifications in PWAs. In React, use create-react-app
(built-in) or workbox
for custom.
Register: In index.js
, navigator.serviceWorker.register('/sw.js')
.
Advantages: Offline functionality (cache assets), faster loads, background sync. For experienced, implement precaching for routes.
Example sw.js snippet:
self.addEventListener('fetch', event => {
event.respondWith(caches.match(event.request).then(response => response || fetch(event.request)));
});
Enhances user experience in unreliable networks.

Also Check: React JS Interview Questions for Experienced
React JS Interview Questions for Senior Developer
Que. 81 How do you implement accessibility (a11y) features in a React application?
Answer:
Follow ARIA standards: Use semantic HTML (<nav>
, <button>
), add aria-label
for non-text elements, manage focus with useRef
. Test with screen readers (NVDA) and tools like Lighthouse or axe.
Example:
<button aria-label="Close modal" onClick={close}>X</button>
For forms: Associate labels with htmlFor
. Advantages: Inclusive design, legal compliance (ADA), better SEO. Experienced devs integrate ESLint-plugin-jsx-a11y.
Que. 82 Explain the useImperativeHandle hook and its use case.
Answer:useImperativeHandle
customizes ref values exposed by forwarding refs, limiting parent access to child methods.
Example:
const Child = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus() }));
return <input ref={inputRef} />;
});
// Parent: const childRef = useRef(); <Child ref={childRef} />; childRef.current.focus();
Use case: Expose specific APIs in libraries, enhancing encapsulation.
Que. 83 How would you migrate a class-based React app to functional components with hooks?
Answer:
Replace this.state
with useState
, lifecycle methods with useEffect
(e.g., componentDidMount
as useEffect(callback, [])
). Convert HOCs to hooks. Refactor step-by-step, testing each component.
Challenges: Handling shouldComponentUpdate
with React.memo
. Advantages: Conciser code, better performance. For large apps, use codemods like react-codemod
.
Que. 84 What are the differences between useLayoutEffect and useEffect?
Answer:
Both run after render; useEffect
async after paint, useLayoutEffect
sync before paint, blocking UI.
Use useLayoutEffect
for DOM measurements (e.g., positioning). Example: Measure element size post-render.
useLayoutEffect(() => {
const rect = ref.current.getBoundingClientRect();
setWidth(rect.width);
}, [dependencies]);
Avoid for non-DOM effects to prevent jank.
Que. 85 How do you implement code splitting in a React app without Next.js?
Answer:
Use React.lazy
and Suspense
for dynamic imports, splitting bundles.
Example:
const Lazy = React.lazy(() => import('./Component'));
<Suspense fallback={<Loader />}><Lazy /></Suspense>
Configure with Webpack (splitChunks). Advantages: Smaller initial bundles (20-50% reduction), faster loads. Analyze with webpack-bundle-analyzer.
Que. 86 Describe how to use React’s Profiler API for performance measurement.
Answer:
Profiler measures render times/phases. Wrap components with <Profiler>
.
Example:
<Profiler id="Panel" onRender={(id, phase, actualDuration) => console.log({id, phase, actualDuration})}>
<Panel />
</Profiler>
onRender
callback logs durations. Use in dev mode; integrate with tools for flame graphs. Helps identify slow components in complex UIs.
Que. 87 What is the role of middleware in Redux, and how to create a custom one?
Answer:
Middleware intercepts actions for side effects (logging, async). Chainable functions.
Custom example (logger):
const logger = store => next => action => {
console.log('dispatching', action);
return next(action);
};
// Apply: applyMiddleware(logger)
For async, use Thunk: dispatch => asyncAction
. Advantages: Extensible, reusable logic.
Que. 88 How would you handle real-time data in React, such as with WebSockets?
Answer:
Use libraries like Socket.io. Set up connection in useEffect
, update state on messages.
Example:
useEffect(() => {
const socket = io('https://server.com');
socket.on('update', data => setData(data));
return () => socket.disconnect();
}, []);
Advantages: Live updates (chats, stocks). For scale, combine with Redux for state sync.
Que. 89 Explain React’s batching behavior and how React 18 improved it.
Answer:
Batching groups state updates for one re-render. Pre-18, only in React events; 18 batches everywhere (promises, timeouts) with flushSync
for manual control.
Example: Multiple setState
in a promise batch into one render.
Improves performance in async code, reducing renders by 50% in event-heavy apps.
Que. 90 How do you implement drag-and-drop functionality in React?
Answer:
Use react-dnd
or native HTML5 API with events like onDragStart
, onDrop
.
Example with native:
function Draggable() {
return <div draggable onDragStart={e => e.dataTransfer.setData('text', id)}>Drag me</div>;
}
function Droppable({ onDrop }) {
const handleDrop = e => { e.preventDefault(); onDrop(e.dataTransfer.getData('text')); };
return <div onDrop={handleDrop} onDragOver={e => e.preventDefault()}>Drop here</div>;
}
For complex (sortable lists), react-beautiful-dnd
. Advantages: Intuitive UX for boards like Trello.
Scenario Based ReactJS Interview Questions and Answers
Que 91. A component is re-rendering unnecessarily on every update. How will you fix it?
Answer:
- Use
React.memo
to memoize functional components. - Use
useCallback
to memoize functions passed as props. - Use
useMemo
for expensive calculations. - Ensure keys are unique in lists to prevent unnecessary re-renders.
Que 92. How would you handle a slow API response affecting component load?
Answer:
- Show a loading spinner or skeleton loader using state.
- Use lazy loading for non-essential components.
- Implement caching using tools like React Query.
- Optimize API calls and paginate data if possible.
Que 93. A user form has many inputs and renders slowly. What’s your solution?
Answer:
- Use controlled components efficiently.
- Split the form into smaller, reusable components.
- Use
React.memo
for inputs that don’t depend on the entire form state. - Debounce or throttle input updates if applicable.
Que 94. How do you handle a requirement to display a modal from anywhere in your app?
Answer:
- Use React Portals to render the modal outside the component hierarchy.
- Manage modal visibility through Context API or global state (Redux).
- Keep modal components at a high level in your component tree for better control.
Que 95. In a real-time chat app, how would you update the UI on new messages without reloading the page?
Answer:
- Use WebSockets or polling APIs to listen for new messages.
- Update local state or global state when a new message arrives.
- Use efficient rendering strategies like virtualization for long chat histories.
Que 96. How would you handle API failures gracefully?
Answer:
- Implement error states using
useState
. - Show user-friendly error messages or retry options.
- Use try/catch blocks with async/await inside
useEffect
. - Optionally, use error boundaries for handling UI crashes.
Que 97. A list of 10,000 items needs to be displayed. How do you optimize rendering?
Answer:
- Implement windowing/virtualization using libraries like react-window or react-virtualized.
- Render only visible items to reduce DOM load.
- Use unique keys for list items.
- Memoize child components when possible.
Que 98. You need to share authentication status across unrelated components. What’s your approach?
Answer:
- Use the Context API to provide authentication status globally.
- Store the authentication token or state in Context or Redux.
- Optionally, persist auth data in localStorage or sessionStorage.
Que 99. A component’s useEffect keeps running repeatedly. How do you fix it?
Answer:
- Check the dependency array of
useEffect
for unnecessary dependencies. - Use proper memoization for functions and objects in dependencies using
useCallback
anduseMemo
. - If needed, move non-critical logic outside of
useEffect
.
Que 100. How would you preload data for a page before rendering?
Answer:
- Use server-side rendering (SSR) with Next.js for preloading data.
- Alternatively, fetch data in a parent component or using React Query before rendering child components.
- Use loading placeholders to improve user experience during data fetch.
ReactJS Interview Questions PDF
We have included all questions to PDF below, so you can prepare offline and access the questions anytime.
FAQs: ReactJS Interview Questions
What is the role of a React.JS Developer?
A React.JS Developer specializes in building interactive and dynamic user interfaces for web applications using the React library. Their responsibilities include developing reusable components, optimizing application performance, and collaborating with backend developers to integrate APIs and services.
What challenges do candidates face during a React JS interview?
React JS interviews often test a candidate’s practical coding skills, understanding of JavaScript fundamentals, component architecture, hooks, and state management. Handling real-world coding scenarios, performance optimization questions, and explaining project structures can be challenging for many candidates.
What are common job challenges for a ReactJS Developer?
In the role, developers frequently face challenges like optimizing large-scale applications, managing complex state across components, ensuring responsive design, and keeping up with frequent library updates. Collaborating effectively within cross-functional teams is also essential.
How important is backend knowledge for a React JS Developer?
While React JS focuses on frontend development, having basic backend knowledge can be beneficial. Understanding REST APIs, GraphQL, and basic authentication concepts helps developers integrate frontend applications more efficiently with backend services.
What is the average salary of a React JS Developer in the USA?
React JS Developers in the USA typically earn between $85,000 and $130,000 per year. Developers with advanced skills in TypeScript, Next.js, or full-stack capabilities can command salaries exceeding $140,000 annually, especially in major tech hubs.
Which top companies hire React JS Developers?
Top companies hiring React JS Developers include Facebook (Meta), Netflix, Airbnb, Amazon, Microsoft, Shopify, Uber, and many fast-growing startups. Demand is particularly high in companies prioritizing modern, responsive web applications with strong user experiences.
Why is interview preparation crucial for React JS roles?
Thorough interview preparation helps developers sharpen their coding abilities, understand React’s latest features, and effectively solve real-world UI problems. Practicing common patterns, hooks usage, and state management techniques can significantly improve performance in technical interviews.
Conclusion
Preparing for a ReactJS interview is essential whether you are a fresher or an experienced developer. Understanding both core React concepts and real-world scenarios will help you tackle technical discussions confidently.
On this page, We have covered commonly asked questions, scenario-based challenges, and advanced ReactJS topics like hooks, memoization, performance optimization, and state management using Context API and Redux. Good luck with your next ReactJS Developer interview.
Similar Interview Guides: