React JS Interview Questions
Prepare for your React interview with the most asked questions for freshers and experienced developers. Covers hooks, lifecycle, performance optimization, and real-world scenarios.
Interview Questions for Freshers
1. What is React, and what are its main features?
React is an open-source JavaScript library developed by Meta for building user interfaces, especially single-page applications. It allows developers to create reusable UI components and efficiently update the UI using a virtual DOM. React follows a component-based architecture and uses declarative programming, making applications easier to manage and scale.
Main Features of React:
Component-Based Architecture: UI is divided into reusable, independent components.
Virtual DOM: React uses a virtual representation of the DOM to improve performance by updating only the necessary parts of the real DOM.
JSX (JavaScript XML): Allows writing HTML-like syntax inside JavaScript.
Unidirectional Data Flow: Data flows from parent to child components, making state management predictable.
Hooks: Functions like
useStateanduseEffectallow using state and lifecycle features in functional components.
1import React, { useState } from "react";
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <div>
8 <p>Count: {count}</p>
9 <button onClick={() => setCount(count + 1)}>
10 Increment
11 </button>
12 </div>
13 );
14}
15export default Counter;2. What is JSX and how does it work?
JSX (JavaScript XML) is a syntax extension for JavaScript used in React that allows us to write HTML-like code inside JavaScript. It makes UI code more readable and easier to write. JSX is not understood directly by browsers; it is transpiled by tools like Babel into regular JavaScript using React.createElement() before execution.
Example
1function App() {
2 return (
3 <div>
4 <h1>Welcome</h1>
5 <p>This is JSX</p>
6 </div>
7 );
8}3. What is the difference between functional and class components in React?
Functional components are just JavaScript functions that return JSX, while class components are ES6 classes that extend React.Component and have a render() method to return JSX.
Functional components were previously used for state and lifecycle, but with the introduction of React Hooks such as useState and useEffect, class components are no longer needed for state and lifecycle. Currently, functional components are used because they are cleaner and easier to maintain.
4. What are props in React?
Props (short for properties) are inputs passed from a parent component to a child component in React. They are used to send data and make components reusable and dynamic. Props are read-only, meaning a child component cannot modify the props it receives. React follows a unidirectional data flow, so props always flow from parent to child.
Example
Parent Component
1function App() {
2 return <User name="John" age={22} />;
3}Child Component
1function User(props) {
2 return (
3 <div>
4 <h1>Name: {props.name}</h1>
5 <p>Age: {props.age}</p>
6 </div>
7 );
8}5. Explain React state and props.
In React, props and state are used to manage data in components.
Props are read-only data passed from a parent component to a child component. They help make components reusable and follow unidirectional data flow.
State, on the other hand, is managed within the component itself and can change over time. When state updates, React re-renders the component to reflect the changes in the UI.
Example
1import React, { useState } from "react";
2
3// Child Component
4function User(props) {
5 return <h1>Hello {props.name}, Count: {props.count}</h1>;
6}
7
8// Parent Component
9function App() {
10 const [count, setCount] = useState(0);
11
12 return (
13 <div>
14 <User name="John" count={count} />
15 <button onClick={() => setCount(count + 1)}>
16 Increment
17 </button>
18 </div>
19 );
20}6. What are stateless components?
Stateless components are React components that do not manage or hold their own state. They simply receive data through props and render UI based on that data. They are usually functional components and are also called presentational components because they focus only on displaying information without handling logic or state changes.
Example
1function Greeting(props) {
2 return <h1>Hello {props.name}</h1>;
3}
4
5export default Greeting;7. What are React Fragments?
React Fragments are a feature in React that allow grouping multiple elements without adding an extra node to the DOM. Normally, React components must return a single parent element, but fragments let us return multiple elements without creating unnecessary wrapper <div>elements. This keeps the DOM clean and improves performance.<> </> is the shorthand for React.Fragment.
Example
1import React from "react";
2
3function App() {
4 return (
5 <>
6 <h1>Hello</h1>
7 <p>Welcome</p>
8 </>
9 );
10}8. What is the purpose of the key in React?
The key prop in React is used to uniquely identify elements in a list. It helps React efficiently update, add, or remove items by identifying which elements have changed during reconciliation. Keys improve performance by allowing React to reuse existing DOM elements instead of re-rendering the entire list.
Example
1function List() {
2 const users = ["John", "Doe", "Rahul"];
3
4 return (
5 <ul>
6 {users.map((user, index) => (
7 <li key={index}>{user}</li>
8 ))}
9 </ul>
10 );
11}9. What does re-rendering mean in React?
In React, re-rendering refers to the process of updating the user interface (UI) in response to changes in the component's state or props. When the state or props of a component change, React re-renders the component to reflect the updated data in the UI.
This involves:
Recalculating the JSX returned by the component
Comparing the new JSX with the previous one (using the Virtual DOM)
Updating the real DOM with only the differences (efficient rendering)
Re-rendering ensures that the UI stays in sync with the component's state and props.
10. What is the difference Between React Node, React Element, and React Component?
In React, a React Element is a plain JavaScript object that describes what should appear on the screen. A React Component is a function or class that returns React elements and defines reusable UI logic. A React Node is anything that React can render, including React elements, strings, numbers, arrays, fragments, or null. In simple terms, components create elements, and nodes are the renderable values React accepts.
Example
React Element
1const element = <h1>Hello John</h1>;React Component
1function Greeting() {
2 return <h1>Hello John</h1>;
3}React Node
1function App() {
2 return (
3 <div>
4 <Greeting /> {/* React Element */}
5 Hello {/* String (React Node) */}
6 {10} {/* Number (React Node) */}
7 </div>
8 );
9}11. What are higher-order components in React?
A Higher-Order Component (HOC) is a function in React that takes a component as an argument and returns a new enhanced component. HOCs are used to reuse component logic, such as authentication, logging, or data fetching, without modifying the original component. They follow the pattern:
Component → Function → Enhanced Component
Example
1function withLogger(WrappedComponent) {
2 return function EnhancedComponent(props) {
3 console.log("Component rendered");
4 return <WrappedComponent {...props} />;
5 };
6}12. What is prop drilling ?
Prop drilling in React occurs when data is passed from a parent component to child components that are deeply nested through intermediate components that don’t necessarily need the data. This is problematic because it makes the code difficult to maintain and understand since most of the components are just prop-drilling.
Example
1function App() {
2 const user = "John";
3 return <Parent user={user} />;
4}
5
6function Parent({ user }) {
7 return <Child user={user} />;
8}
9
10function Child({ user }) {
11 return <GrandChild user={user} />;
12}
13
14function GrandChild({ user }) {
15 return <h1>{user}</h1>;
16}
1713. What are the different phases of the component lifecycle?
The React component lifecycle consists of three main phases: Mounting, Updating, and Unmounting. These phases describe how a component is created, updated, and removed from the DOM. In class components, lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount are used. In functional components, these behaviors are handled using the useEffect hook.
Example
Mounting Phase
1useEffect(() => {
2 console.log("Component Mounted");
3}, []);Updating Phase
1useEffect(() => {
2 console.log("Component Updated");
3}, [dependency]);Unmounting Phase
1useEffect(() => {
2 return () => {
3 console.log("Component Unmounted");
4 };
5}, []);Interview Questions for Experienced
1. What is useState() in React?
useState()is a React Hook that allows functional components to manage state. It lets us add and update state variables inside a functional component. It returns an array with two values: the current state and a function to update that state. When the state updates, React re-renders the component.
2. What are React Hooks?
React Hooks are special functions introduced in React that allow functional components to use state and other React features like lifecycle methods. Before hooks, state and lifecycle features were only available in class components. Hooks make code cleaner and more reusable.
Example
useState Hook
1import React, { useState } from "react";
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <div>
8 <p>{count}</p>
9 <button onClick={() => setCount(count + 1)}>
10 Increment
11 </button>
12 </div>
13 );
14}3. What is useContext() in React?
useContext() is a React Hook that enables you to use data from a Context without having to pass props down through the entire component tree. It is used to consume values from the React Context API. It helps in preventing prop drilling.
When Should You Use It?
When there are multiple components that require access to the same data.
When you want to avoid prop drilling.
For global-like data such as: Theme, Authenticated user, Language settings, App configuration
4. What are the rules that must be followed while using React Hooks?
While using React Hooks, there are two main rules that must be followed.
First, Hooks must only be called at the top level of a React functional component or inside a custom Hook, not inside loops, conditions, or nested functions.
Second, Hooks must only be called from React functional components or custom Hooks, not from regular JavaScript functions.
These rules ensure that React maintains the correct order of Hook calls across renders.
Example
Incorrect Usage (Inside Condition)
1function Example() {
2 if (true) {
3 const [count, setCount] = useState(0); // Not allowed
4 }
5}Correct Usage (Top Level)
1import React, { useState } from "react";
2
3function Example() {
4 const [count, setCount] = useState(0); // Top level
5
6 return (
7 <button onClick={() => setCount(count + 1)}>
8 {count}
9 </button>
10 );
11}5. What is the use of useEffect React Hooks?
useEffect is a React Hook used to handle side effects in functional components. Side effects include operations like API calls, subscriptions, timers, DOM manipulation, or updating the document title. It runs after the component renders and can be controlled using a dependency array to determine when it should re-run.
Example
Run on Every Render
1import React, { useEffect } from "react";
2
3function Example() {
4 useEffect(() => {
5 console.log("Component rendered");
6 });
7
8 return <h1>Hello</h1>;
9}Run Only Once (On Mount)
1useEffect(() => {
2 console.log("Component mounted");
3}, []);Run When Dependency Changes
1useEffect(() => {
2 console.log("Count changed:", count);
3}, [count]);6. What is the useRef hook in React and when should it be used?
useRefis a React Hook that is used to create a reference that is preserved across the re-rendering of the component. It is primarily used to access the DOM element directly or to store values that do not cause re-renders when they are updated. Unlike state, when a ref is updated, it does not cause the component to re-render. It is often used for DOM manipulation, focusing an input element, storing previous values, or handling timers.
Example
Accessing DOM Element
1import React, { useRef } from "react";
2
3function InputFocus() {
4 const inputRef = useRef();
5
6 const handleClick = () => {
7 inputRef.current.focus();
8 };
9
10 return (
11 <>
12 <input ref={inputRef} type="text" />
13 <button onClick={handleClick}>Focus Input</button>
14 </>
15 );
16}7. What are the differences between controlled and uncontrolled components?
The main difference between controlled and uncontrolled components in React is how form data is handled.
In controlled components, form data is managed by React state, and the component re-renders whenever the input changes.
In uncontrolled components, form data is handled by the DOM itself, and React accesses the value using refs when needed.
Example
Controlled Component
1import React, { useState } from "react";
2
3function ControlledForm() {
4 const [name, setName] = useState("");
5
6 return (
7 <input
8 type="text"
9 value={name}
10 onChange={(e) => setName(e.target.value)}
11 />
12 );
13}Uncontrolled Component
1import React, { useRef } from "react";
2
3function UncontrolledForm() {
4 const inputRef = useRef();
5
6 const handleSubmit = () => {
7 console.log(inputRef.current.value);
8 };
9
10 return (
11 <>
12 <input type="text" ref={inputRef} />
13 <button onClick={handleSubmit}>Submit</button>
14 </>
15 );
16}8. How would you lift the state up in a React application, and why is it necessary?
Lifting the state up in React means moving the state from the child components to their highest-level ancestor. This technique is employed to share the state among components that are not necessarily parent and child. Lifting the state up helps you overcome the issue of prop drilling.
Example
1// Lifting state up
2const Parent = () => {
3 const [counter, setCounter] = useState(0);
4
5 return (
6 <div>
7 <Child1 counter={counter} />
8 <Child2 setCounter={setCounter} />
9 </div>
10 );
11};
12
13const Child1 = ({ counter }) => <h1>{counter}</h1>;
14
15const Child2 = ({ setCounter }) => (
16 <button onClick={() => setCounter((prev) => prev + 1)}>Increment</button>
17);9. What is a React Router?
React Router is a standard routing library for React that helps us navigate between various components of a single-page application (SPA) without reloading the page. It helps us define routes, handle URLs, and display particular components depending on the current URL. React Router functions by keeping the UI in sync with the browser URL.
Example
1import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
2
3function Home() {
4 return <h1>Home Page</h1>;
5}
6
7function About() {
8 return <h1>About Page</h1>;
9}
10
11function App() {
12 return (
13 <BrowserRouter>
14 <nav>
15 <Link to="/">Home</Link>
16 <Link to="/about">About</Link>
17 </nav>
18
19 <Routes>
20 <Route path="/" element={<Home />} />
21 <Route path="/about" element={<About />} />
22 </Routes>
23 </BrowserRouter>
24 );
25}10. What is the differences between BrowserRouter and HashRouter ?
The key difference between BrowserRouter and HashRouter in React is the manner in which they handle URLs.
BrowserRouter relies on the HTML5 History API to create URLs without a hash (#/about), while HashRouter uses the URL hash (#/about) to handle routing. BrowserRouter needs proper server configuration, but HashRouter does not.
BrowserRouter
Uses History API (pushState, replaceState)
Clean URLs
Requires server to handle route fallback
BrowserRouter Example
1import { BrowserRouter, Routes, Route } from "react-router-dom";
2
3function App() {
4 return (
5 <BrowserRouter>
6 <Routes>
7 <Route path="/" element={<Home />} />
8 <Route path="/about" element={<About />} />
9 </Routes>
10 </BrowserRouter>
11 );
12}HashRouter
Uses hash portion of URL
Does not require server configuration
Works well for static hosting
HashRouter Example
1import { HashRouter, Routes, Route } from "react-router-dom";
2
3function App() {
4 return (
5 <HashRouter>
6 <Routes>
7 <Route path="/" element={<Home />} />
8 <Route path="/about" element={<About />} />
9 </Routes>
10 </HashRouter>
11 );
12}11. What are Custom Hooks?
Custom Hooks are reusable functions in JavaScript and React that begin with the word use and enable us to refactor and reuse stateful logic in multiple components. Custom Hooks can also utilize other React Hooks such as useState and useEffect. Custom Hooks are used to prevent code duplication and keep the components clean.
Example
Custom Hook
1import { useState } from "react";
2
3function useCounter(initialValue) {
4 const [count, setCount] = useState(initialValue);
5
6 const increment = () => setCount(count + 1);
7
8 return { count, increment };
9}Using Custom Hook in Component
1function Counter() {
2 const { count, increment } = useCounter(0);
3
4 return (
5 <>
6 <p>{count}</p>
7 <button onClick={increment}>Increment</button>
8 </>
9 );
10}12. What is the useReducer ?
useReducer is a React Hook that is used for managing complex state logic in functional components. It is almost identical to Redux in that it relies on a reducer function that accepts the current state and an action, and then returns a new state. It is usually used in place of useState when the new state depends on the previous state or when there are multiple state values that need to be managed.
Example
1import { useReducer } from "react";
2
3const initialState = { count: 0 };
4
5function reducer(state, action) {
6 switch (action.type) {
7 case "increment":
8 return { count: state.count + 1 };
9 case "decrement":
10 return { count: state.count - 1 };
11 default:
12 throw new Error();
13 }
14}
15
16function Counter() {
17 const [state, dispatch] = useReducer(reducer, initialState);
18
19 return (
20 <>
21 <p>{state.count}</p>
22 <button onClick={() => dispatch({ type: "increment" })}>
23 Increment
24 </button>
25 <button onClick={() => dispatch({ type: "decrement" })}>
26 Decrement
27 </button>
28 </>
29 );
30}13. When should we use useReducer ?
You can use useReducer when your component has complex state logic, when you have multiple related state values, or when the state update is dependent on the previous state. This is helpful when your state transitions become complex and harder to manage with useState.
When the state logic is complex (multiple conditions).
When multiple state variables are related.
When updates depend on previous state.
When building forms or managing large state objects.
When you want Redux-like behavior inside a component.
Example
1//Instead of multiple useState calls
2const [count, setCount] = useState(0);
3const [error, setError] = useState(null);
4const [loading, setLoading] = useState(false);
5
6//You can manage everything in one reducer:
7const initialState = {
8 count: 0,
9 error: null,
10 loading: false
11};14. Explain one-way data flow of React
In React, the one-way flow of data means that data flows in only one direction, from parent components to child components via props. The child components cannot change the data they receive directly; rather, they send notifications back to the parent component through callback functions. The one-way flow of data ensures that applications are more predictable and easier to maintain.
Example
1import React, { useState } from "react";
2
3function Child({ count, increment }) {
4 return <button onClick={increment}>Count: {count}</button>;
5}
6
7function Parent() {
8 const [count, setCount] = useState(0);
9
10 return (
11 <Child
12 count={count}
13 increment={() => setCount(count + 1)}
14 />
15 );
16}15. What is the difference between re-render and re-mount in React?
Re-rendering occurs when a component is updated based on changes in the state or props, but the same component instance is still present in the DOM. React only updates the required parts of the UI.
Re-mounting occurs when a component is removed entirely from the DOM and then mounted again as a new component instance. In this scenario, all the lifecycle methods are executed again from the start, and the state of the component is reset.
Example
Re-render (State Change)
1function Counter() {
2 const [count, setCount] = React.useState(0);
3
4 return (
5 <>
6 <p>{count}</p>
7 <button onClick={() => setCount(count + 1)}>
8 Increment
9 </button>
10 </>
11 );
12}Re-mount (Key Change)
1function App() {
2 const [toggle, setToggle] = React.useState(false);
3
4 return (
5 <>
6 <button onClick={() => setToggle(!toggle)}>
7 Toggle
8 </button>
9 {toggle ? <Counter key="A" /> : <Counter key="B" />}
10 </>
11 );
12}16. What are common causes of the "Too many re-renders" error?
The “Too many re-renders” error in React happens when a component is updating its state within the rendering phase, thus creating an infinite loop of rendering. This is most likely happening when setState (or a state update function) is called directly within the component body or when a function that updates the state is invoked immediately rather than being passed as a callback.
Common Causes
Calling setState Directly in Component Body
1function App() {
2 const [count, setCount] = React.useState(0);
3
4 setCount(1); // Causes infinite re-render
5
6 return <h1>{count}</h1>;
7}Immediately Calling Function in JSX
1<button onClick={setCount(count + 1)}>Increment</button>useEffect Without Proper Dependency Array
1useEffect(() => {
2 setCount(count + 1); // Runs every render
3});Advanced Interview Questions
1. Explain the concept of the Virtual DOM in React.
The Virtual DOM is a light copy of the actual DOM that is kept by React. When there is a change in the state or props of a component, React updates the Virtual DOM and not the actual DOM. It then compares the updated Virtual DOM with the previous one through a process called reconciliation and updates the actual DOM accordingly. This makes the code more efficient and reduces direct DOM manipulation.
2. How does virtual DOM in React work? What are its benefits and downsides?
The Virtual DOM in React is a lightweight JavaScript representation of the real DOM. When a component's state or props change, React does not immediately update the real DOM. Instead, it creates a new Virtual DOM tree, compares it with the previous Virtual DOM using a diffing algorithm (reconciliation), identifies the minimal set of changes, and then updates only those specific parts in the real DOM. This process improves performance by reducing expensive direct DOM manipulations.
How Virtual DOM Works (Step-by-Step)
1. Initial Render
React creates a Virtual DOM tree.
It renders it to the real DOM.
2. State or Props Update
A new Virtual DOM tree is created.
3. Reconciliation (Diffing Algorithm)
React compares the old and new Virtual DOM.
It identifies what changed.
4. Efficient Update
React updates only the changed nodes in the real DOM.
The rest of the DOM remains untouched.
3. What is reconciliation?
Reconciliation is the mechanism by which React optimizes the updating of the DOM when there are changes in the state or props of a component. React compares the new Virtual DOM with the previous Virtual DOM using a diffing algorithm and makes changes only to the parts that are different in the actual DOM.
4. How does React's diffing algorithm work internally?
The diffing algorithm in React compares the new Virtual DOM with the previous one whenever there is a change in the state or props. It also updates only the parts that have changed. It assumes that if elements are of different types, they need to be replaced completely, but if they are of the same type, they can be updated by changing only the attributes that have changed. In the case of a list, React uses keys to efficiently identify elements that need to be updated.
5. Explain what React hydration is?
React hydration is the process where React attaches event listeners and makes a server-rendered HTML page interactive on the client side. When using Server-Side Rendering (SSR), the server sends fully rendered HTML to the browser. Hydration happens when React loads on the client and connects that static HTML with its virtual DOM so the page becomes fully functional without re-rendering everything.
6. What is React strict mode and what are its benefits?
React Strict Mode is a development-only feature that helps identify potential problems in a React application. It does not render any visible UI but activates additional checks and warnings for its child components. Strict Mode helps detect unsafe lifecycle methods, unexpected side effects, deprecated APIs, and other issues that could cause bugs in future React versions.
Example
1import React from "react";
2import ReactDOM from "react-dom/client";
3import App from "./App";
4
5const root = ReactDOM.createRoot(document.getElementById("root"));
6
7root.render(
8 <React.StrictMode>
9 <App />
10 </React.StrictMode>
11);7. What are Pure Components?
Pure Components in React are components that render only when their props or state change. They perform a shallow comparison of previous and current props and state to prevent unnecessary re-renders. This improves performance by avoiding re-rendering when data has not changed. In class components, React provides React.PureComponent, and in functional components, similar behavior can be achieved using React.memo().
Example
1import React from "react";
2
3const MyComponent = React.memo(function({ name }) {
4 console.log("Rendered");
5 return <h1>{name}</h1>;
6});
7
8export default MyComponent;8. What is React.memo()?
React.memo()function is a higher-order component that memoizes a functional component. It optimizes unnecessary re-renders of a component by performing a shallow comparison of the props. If the props are not changed, React skips the re-rendering of the component, which is useful for performance optimization.
Example
1import React from "react";
2
3const Child = React.memo(function Child({ name }) {
4 console.log("Child rendered");
5 return <h1>{name}</h1>;
6});
7
8function Parent() {
9 const [count, setCount] = React.useState(0);
10
11 return (
12 <>
13 <button onClick={() => setCount(count + 1)}>
14 Increment
15 </button>
16 <Child name="Vishal" />
17 </>
18 );
19}9. When should you not use React.memo()?
You should not use React.memo() if the component is simple or if it is cheap to render, as the overhead of memoization (prop comparison) could be higher than the benefit. It is also unnecessary if the component re-renders infrequently or if the props change every time, as memoization will not help in these scenarios anyway.
10. What is the useCallback hook in React and when should it be used?
useCallback is a React Hook that remembers a function so that it is not recreated every time the component re-renders. It helps improve performance, especially when passing functions as props to child components, so they don't re-render unnecessarily.
Example
1import React, { useState, useCallback } from "react";
2
3function Parent() {
4 const [count, setCount] = useState(0);
5
6 const handleClick = useCallback(() => {
7 console.log("Clicked");
8 }, []);
9
10 return <Child onClick={handleClick} />;
11}11. What is the useMemo hook in React and when should it be used?
useMemo is a React Hook that memoizes (remembers) the result of a calculation so that it does not run again unless its dependencies change. It is mainly used to optimize performance by avoiding expensive computations on every render.
It should be used:
When you have heavy or expensive calculations.
When a computed value depends on certain state/props.
When you want to prevent unnecessary recalculations during re-renders.
Example
1import React, { useState, useMemo } from "react";
2
3function App() {
4 const [count, setCount] = useState(0);
5
6 const result = useMemo(() => {
7 console.log("Calculating...");
8 return count * 2;
9 }, [count]);
10
11 return (
12 <>
13 <p>{result}</p>
14 <button onClick={() => setCount(count + 1)}>Increment</button>
15 </>
16 );
17}12. Why should we avoid using array indices as keys in React?
Using array indices as keys in React can lead to incorrect UI updates and performance issues, especially when the list changes dynamically (items are added, removed, or reordered). Since indices change when the array order changes, React may incorrectly reuse DOM elements, causing state and UI mismatches. Therefore, it is recommended to use stable and unique identifiers like IDs instead of array indices.
13. What is lazy loading in React and why is it used?
Lazy loading is a performance optimization technique in React where components are loaded only when they are needed instead of loading everything at once. It helps reduce the initial bundle size and improves application loading speed. React provides React.lazy() and Suspense to implement lazy loading for components.
Example
1import React, { Suspense } from "react";
2
3const LazyComponent = React.lazy(() => import("./MyComponent"));
4
5function App() {
6 return (
7 <Suspense fallback={<div>Loading...</div>}>
8 <LazyComponent />
9 </Suspense>
10 );
11}
12
13export default App;14. What is the difference between Shadow DOM and Virtual DOM?
The Shadow DOM is a web standard that encapsulates a part of the DOM, isolating it from the rest of the document. It's used for creating reusable, self-contained components without affecting the global styles or scripts.
The Virtual DOM is an in-memory representation of the actual DOM used to optimize rendering. It compares the current and previous states of the UI, updating only the necessary parts of the DOM, which improves performance.
15. What is code splitting in a React application?
Code splitting in React is a performance optimization technique where the application bundle is divided into smaller chunks that are loaded only when needed, instead of loading the entire app at once. This reduces the initial load time and improves performance, especially for large applications. It is commonly implemented using React.lazy() and Suspense or dynamic import().
Why Code Splitting is Needed
Reduces initial bundle size
Improves page load speed
Loads components only when required (on demand)
Better performance for large applications
16. How to optimize the performance of a react app?
React performance can be optimized by reducing unnecessary re-renders, splitting code into smaller chunks, memoizing components and calculations, optimizing state management, and using efficient rendering techniques like virtualization. The goal is to minimize DOM updates and avoid expensive computations during re-renders.
17. How do you decide between using React state, context, and external state managers?
The decision between React state, Context, and external state managers depends on how widely the data is used and how complex it is.
Use React state for local, component-specific data. Use Context when multiple components across the tree need shared data without prop drilling. Use external state managers like Redux or Zustand when the application is large, the state is complex, or many components need synchronized global state with better performance control.
18. How would you handle long-running tasks or expensive computations in React applications without blocking the UI?
To avoid blocking the UI, use Web Workers, setTimeout, or requestIdleCallback for offloading heavy computations. Alternatively, break tasks into smaller parts and use React's Suspense or useMemo to only recompute when necessary.
Example using setTimeout for deferring computation:
1const [data, setData] = useState(null);
2
3useEffect(() => {
4 setTimeout(() => {
5 const result = computeExpensiveData();
6 setData(result);
7 }, 0);
8}, []);19. How does React Fiber architecture improve rendering performance ?
React Fiber optimizes rendering by making the reconciliation algorithm in React incremental and interruptible, rather than fully synchronous. This allows React to split rendering work into smaller chunks that can be paused, resumed, or deferred, allowing React to process high-priority work such as user input before other work. This makes applications more responsive and enables features such as concurrent rendering.
Key improvements in React Fiber:
Breaks rendering into small units of work
Supports prioritization of updates
Allows pausing and resuming rendering
Enables concurrent rendering
Improves UI responsiveness and smoothness
20. What is concurrent rendering ?
Concurrent Rendering is a feature of React that makes the rendering process interruptible and prioritizable, so that React can perform multiple updates concurrently. This means that instead of waiting for all the updates to be done before proceeding with the next task, React can pause the low-priority task of rendering and attend to the high-priority task of handling user input, for example.
21. How would you debug performance issues in a large React application ?
To solve a performance problem in a big React application, I would begin by determining if the issue is due to re-renders, computationally expensive code, large bundles, or slow network calls. I would use the React DevTools Profiler to determine which components are being re-rendered too often and how long it takes to render them. Next, I would look for unnecessary re-renders due to changing props, inline functions, or missing memoization. I would also monitor network calls, bundle size, and use browser performance tools to identify blocking scripts or memory problems.
Steps to Debug Performance Issues:
Use React DevTools Profiler to detect slow components
Check for unnecessary re-renders
Apply React.memo, useMemo, or useCallback where needed
Optimize large lists using virtualization
Analyze bundle size and remove unused dependencies
Monitor network requests and API delays
Use Lighthouse and Chrome Performance tab for deeper analysis
Related Articles
JavaScript Interview Questions
Prepare for your next tech interview with the most asked JavaScript interview questions and answers. It includes basic to advanced concepts, coding problems, and real-world scenarios for freshers and experienced developers.
BackendPython Interview Questions
Master your Python interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.