Open In App

React Interview Questions and Answers (2025) - Intermediate Level

Last Updated : 24 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

ReactJS is an open-source JavaScript library that is used for building user interfaces in a declarative and efficient way. It is a component-based front-end library responsible only for the view layer of an MVC (Model View Controller) architecture. React is used to create modular user interfaces and it promotes the development of reusable UI components that display dynamic data.

This article provides detailed explanations for intermediate-level React interview questions to help candidates thoroughly understand key concepts. These questions are designed for developers with 2–10 years of experience preparing for React job interview. Each answer includes comprehensive details, practical examples. Whether you're a fresher or an experienced professional, mastering these concepts will boost your confidence to ace technical interviews.

Before proceeding to learn ReactJS Interview Questions and Answers – Intermediate Level, you can first go through complete ReactJS Tutorial, and ReactJS Interview Questions and Answers – Beginner Level.

1. What is conditional rendering in React?

Conditional rendering in React refers to rendering different components or UI elements based on specific conditions. It allows developers to control what gets displayed in the UI dynamically, depending on the application’s state or props. This is similar to using if-else statements in JavaScript but implemented in a declarative way within JSX. Conditional rendering is commonly used for scenarios like showing a login or logout button based on user authentication status, displaying loading spinners, or toggling UI elements.

Example:

function UserStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <DisplayLoggedIn /> : <DisplayLoggedOut />}
</div>
);
}

function DisplayLoggedIn() {
return <h1>Welcome, User!</h1>;
}

function DisplayLoggedOut() {
return <h1>Please Log In</h1>;
}

In this example, if isLoggedIn is true, the DisplayLoggedIn component is rendered; otherwise, DisplayLoggedOut is shown. You can also use logical operators (&&, ||) or ternary operators for concise conditional rendering.

Key Points:

  • Use ternary operators (?:) for simple conditions within JSX.
  • Use && for rendering elements only when a condition is true (e.g., {isLoading && <Spinner />}).
  • Avoid complex logic in JSX; move it to a separate function for readability.
  • Conditional rendering enhances UI flexibility and user experience.

2. What is React Router?

React Router is a standard library for handling navigation and routing in React applications. It allows developers to create single-page applications (SPAs) with multiple views, enabling seamless navigation without full page reloads. React Router synchronizes the UI with the browser’s URL, ensuring the displayed content matches the current route. It’s essential for building dynamic, multi-page-like experiences in SPAs.

Installation:
To use React Router, install it via npm:

npm install react-router-dom

Example:

import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
}

Here, Link creates navigable links, Route maps URLs to components, and Switch ensures only the first matching route is rendered.

Key Points:

  • React Router enables client-side routing, improving performance.
  • It supports dynamic routing, nested routes, and route parameters.
  • Use react-router-dom for web applications (as opposed to react-router-native for mobile apps).

3. Explain the components of React Router.

React Router provides several core components to manage routing in a React application. These components work together to define routes, handle navigation, and render appropriate UI based on the URL.

Main Components:

  1. BrowserRouter (Router): The parent component that wraps the entire application to enable routing. It uses the HTML5 history API to keep the UI in sync with the URL.
    import { BrowserRouter as Router } from 'react-router-dom';
    function App() {
    return <Router>{/* Other components */}</Router>;
    }
  2. Switch: Renders the first Route or Redirect that matches the current URL. It prevents multiple routes from rendering simultaneously.
    <Switch>
    <Route path="/home" component={Home} />
    <Route path="/about" component={About} />
    </Switch>
  3. Route: Defines a mapping between a URL path and a component. It renders the specified component when the URL matches the path. The exact prop ensures precise matching.
    <Route exact path="/home" component={Home} />
  4. Link: Creates clickable links for navigation without reloading the page. It replaces traditional <a> tags to work with React Router.
    <Link to="/about">Go to About</Link>

Key Points:

  • Use BrowserRouter for web apps and HashRouter for static sites.
  • Switch ensures only one route renders at a time, improving performance.
  • Route supports dynamic parameters (e.g., /user/:id) and query strings.
  • Link enhances user experience by enabling smooth navigation.

4. Explain the lifecycle methods of components.

In React, component lifecycle methods are special methods that allow developers to hook into specific phases of a component’s life, such as creation, updating, and removal. These methods are primarily used in class-based components and are divided into four phases:

  1. Initialization: The component is created with initial props and state, typically in the constructor.
    class MyComponent extends React.Component {
    constructor(props) {
    super(props);
    this.state = { count: 0 };
    }
    }
  2. Mounting: The component is rendered to the DOM for the first time. Key methods include componentWillMount (deprecated) and componentDidMount.
  3. Updating: The component re-renders due to changes in props or state. Methods like shouldComponentUpdate and componentDidUpdate are used here.
  4. Unmounting: The component is removed from the DOM, using componentWillUnmount for cleanup tasks.

Example:

class MyComponent extends React.Component {
componentDidMount() {
console.log('Component mounted!');
}
componentDidUpdate() {
console.log('Component updated!');
}
componentWillUnmount() {
console.log('Component will unmount!');
}
render() {
return <div>Hello, World!</div>;
}
}

Key Points:

  • Lifecycle methods are less common with functional components, where hooks like useEffect replace them.
  • Use lifecycle methods for tasks like data fetching, subscriptions, or cleanup.
  • Avoid deprecated methods like componentWillMount in modern React.

5. Explain the methods used in the mounting phase of components.

The mounting phase occurs when a component is initialized and added to the DOM. During this phase, React calls specific lifecycle methods to allow developers to perform setup tasks. The two primary methods in this phase are:

  1. componentWillMount() (Deprecated): Called just before the component is mounted to the DOM. It was used for setup tasks but is now replaced by componentDidMount or hooks due to potential issues in server-side rendering.
  2. componentDidMount(): Called immediately after the component is mounted to the DOM. It’s ideal for tasks like fetching data, setting up event listeners, or initializing third-party libraries.

Example:

class MyComponent extends React.Component {
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return <div>Data: {this.state.data}</div>;
}
}

Key Points:

  • Use componentDidMount for side effects like API calls or DOM manipulation.
  • Avoid using componentWillMount in new code; use componentDidMount or useEffect instead.
  • Mounting methods run only once during a component’s lifecycle.

6. What is the this.setState function in React?

The setState method in React is used to update a component’s state object, triggering a re-render to reflect the updated state in the UI. It’s a core feature of class-based components, ensuring that state changes are predictable and efficient. Unlike directly modifying this.state, setState notifies React to update the component and its children.

Example:

class Counter extends React.Component {
state = { count: 0 };
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

Key Points:

  • setState is asynchronous, so don’t rely on immediate state updates. Use a callback if needed:
    this.setState({ count: this.state.count + 1 }, () => console.log('State updated'));
  • You can pass a function to setState for updates based on the previous state:
    this.setState(prevState => ({ count: prevState.count + 1 }));
  • setState merges the provided object with the current state, preserving unmentioned properties.

7. What is the use of ref in React?

Refs in React provide a way to directly access DOM elements or React components created in the render method. They are useful for tasks like focusing an input, triggering animations, or integrating with third-party libraries. Refs are created using React.createRef() or the useRef hook in functional components.

Example (Class Component):

class InputField extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
focusInput = () => {
this.inputRef.current.focus();
};
render() {
return (
<div>
<input ref={this.inputRef} />
<button onClick={this.focusInput}>Focus Input</button>
</div>
);
}
}

Example (Functional Component):

import { useRef } from 'react';
function InputField() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}

Key Points:

  • Use refs sparingly; prefer props and state for most interactions.
  • Refs can store mutable values that persist across renders (via useRef).
  • Avoid using refs for tasks that can be handled declaratively with React’s state or props.

8. What are hooks in React?

Hooks are functions introduced in React 16.8 that allow functional components to use state, lifecycle methods, and other React features without writing class components. Hooks simplify code, improve reusability, and align with React’s functional programming paradigm. They don’t violate React’s core concepts but provide a cleaner API for state, context, refs, and more.

Common Hooks:

  • useState: Manages state in functional components.
  • useEffect: Handles side effects like data fetching or subscriptions.
  • useContext: Accesses context for global state.
  • useRef: Creates references to DOM elements or persistent values.

Example:

import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

Key Points:

  • Hooks can only be used in functional components or custom hooks.
  • They must be called at the top level of a component (not inside loops or conditions).
  • Custom hooks allow reusable logic across components.

9. Explain the useState hook in React?

The useState hook allows functional components to manage state. It returns a state variable and a function to update it, enabling dynamic UI updates. Each call to useState creates a single state variable, stored in React’s internal state management, and triggers a re-render when updated.

Syntax:

import { useState } from 'react';
const [state, setState] = useState(initialValue);

Example:

import { useState } from 'react';
function TextInput() {
const [text, setText] = useState('');
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<p>You typed: {text}</p>
</div>
);
}

Key Points:

  • useState can store any data type (strings, numbers, objects, arrays).
  • Updates via setState are asynchronous; use a function for updates based on the previous state:
    setCount(prevCount => prevCount + 1);
  • Multiple useState calls can manage different state variables in a single component.

10. Explain the useEffect hook in React?

The useEffect hook handles side effects in functional components, such as data fetching, subscriptions, or DOM manipulation. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. useEffect runs after every render unless controlled by a dependency array.

Syntax:

import { useEffect } from 'react';
useEffect(() => {
// Side effect logic
return () => {
// Cleanup logic
};
}, [dependencies]);

Example:

import { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
return () => {
console.log('Cleanup');
};
}, []); // Empty array means run once on mount
return <div>{data ? data.name : 'Loading...'}</div>;
}

Key Points:

  • The optional dependency array controls when useEffect runs (e.g., [] for mount only, [value] for changes to value).
  • The cleanup function (returned from useEffect) runs before the next effect or on unmount.
  • Use multiple useEffect calls to separate unrelated side effects for clarity.

11. What is React Fragments?

React Fragments allow developers to group multiple elements without adding extra DOM nodes (like a <div>). They solve the issue of JSX requiring a single parent element while keeping the DOM clean. Introduced in React 16.2, Fragments improve performance and semantics by avoiding unnecessary wrapper elements.

Syntax:

<React.Fragment>
<h2>Child 1</h2>
<p>Child 2</p>
</React.Fragment>
// Shorthand syntax
<>
<h2>Child 1</h2>
<p>Child 2</p>
</>

Example:

function ListItems() {
return (
<>
<li>Item 1</li>
<li>Item 2</li>
</>
);
}

Key Points:

  • Use Fragments to avoid extra <div> tags in the DOM, improving performance.
  • The shorthand <></> is commonly used but doesn’t support keys or attributes.
  • Fragments are ideal for rendering lists or grouped elements cleanly.

12. What is a React Developer Tool?

React Developer Tools is a browser extension for Chrome and Firefox that aids in debugging React applications. It integrates with browser DevTools, allowing developers to inspect the component hierarchy, view props, state, hooks, and performance metrics. It’s invaluable for troubleshooting and optimizing React apps.

Features:

  • Inspect component trees and their props/state.
  • Debug hooks like useState and useEffect.
  • Profile performance to identify slow renders.

Installation:
Install from the Chrome Web Store or Firefox Add-ons. Once added, it appears as a “React” tab in DevTools.

Example Use Case:
When debugging, select a component in the React tab to view its props, state, and hooks. You can also edit state in real-time to test UI changes.

Key Points:

  • Essential for diagnosing rendering issues or state mismanagement.
  • Works with both development and production builds (though limited in production).
  • Use alongside browser DevTools for a complete debugging experience.

13. How to use styles in ReactJS?

Styling in React can be done in multiple ways, but CSS Modules are a popular approach for locally scoped styles. CSS Modules allow you to write CSS files with unique, auto-generated class names to avoid naming conflicts, improving modularity and maintainability.

Steps to Use CSS Modules:

  1. Create a CSS file named [ComponentName].module.css (e.g., App.module.css).
  2. Write CSS with standard class names.
  3. Import and use the styles in your component.

Example (App.module.css):

.container {
background-color: lightblue;
padding: 20px;
}

Example (App.js):

import styles from './App.module.css';
function App() {
return <div className={styles.container}>Styled Component</div>;
}

Key Points:

  • CSS Modules scope styles locally, preventing global conflicts.
  • Use camelCase for class names in JavaScript (e.g., styles.myClass).
  • Other styling options include inline CSS, styled-components, or CSS-in-JS libraries.

14. Explain styled-components in React.

Styled-components is a CSS-in-JS library that allows developers to write CSS within JavaScript, creating reusable, component-scoped styles. It eliminates the need for separate CSS files and provides dynamic styling based on props or state, enhancing developer experience and maintainability.

Installation:

npm install styled-components

Example:

import styled from 'styled-components';

const Button = styled.button`
background-color: ${props => (props.primary ? 'blue' : 'gray')};
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
`;

function App() {
return (
<div>
<Button>Normal Button</Button>
<Button primary>Primary Button</Button>
</div>
);
}

Key Points:

  • Styles are scoped to components, avoiding global CSS conflicts.
  • Supports dynamic styling with props and theming.
  • Integrates well with TypeScript and modern React workflows.

15. What is prop drilling and its disadvantages?

Prop drilling occurs when data is passed from a parent component to deeply nested child components through props, even if intermediate components don’t need the data. While functional, this practice can lead to cumbersome and hard-to-maintain code.

Example:

function App() {
const user = { name: 'John' };
return <Parent user={user} />;
}
function Parent({ user }) {
return <Child user={user} />;
}
function Child({ user }) {
return <GrandChild user={user} />;
}
function GrandChild({ user }) {
return <div>{user.name}</div>;
}

Disadvantages:

  • Code Clutter: Intermediate components must pass props they don’t use, increasing complexity.
  • Maintenance Issues: Refactoring or adding new props requires changes across multiple components.
  • Readability: Long prop chains make code harder to follow.

Solutions:

  • Use Context API to share data globally.
  • Use state management libraries like Redux or Zustand for complex apps.

16. What are controlled and uncontrolled components in React?

Controlled and uncontrolled components refer to how form elements (like inputs) manage their data in React.

  • Controlled Components: The parent component manages the form element’s value via state. The input’s value is bound to a state variable, and changes are handled through event handlers.
  • Uncontrolled Components: The form element maintains its own internal state, and React accesses its value using refs.

Example (Controlled Component):

function ControlledInput() {
const [value, setValue] = useState('');
return (
<input
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}

Example (Uncontrolled Component):

function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = () => {
alert(inputRef.current.value);
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}

Key Points:

  • Controlled components are preferred for predictable data flow and validation.
  • Uncontrolled components are simpler for basic forms but harder to manage in complex scenarios.
  • Use controlled components for forms requiring real-time validation or synchronization.

17. What is the useRef hook in React?

The useRef hook creates a mutable reference that persists across renders in functional components. It’s commonly used to access DOM elements or store values that don’t trigger re-renders when updated. The useRef object has a .current property that holds the reference’s value.

Example:

import { useRef, useEffect } from 'react';
function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}

Key Points:

  • useRef doesn’t cause re-renders when .current changes.
  • Useful for accessing DOM nodes, storing previous values, or managing timers.
  • Unlike state, useRef values persist for the component’s entire lifecycle.

18. Explain the componentDidMount method in React.

Explanation:
The componentDidMount method is a lifecycle method in class-based components that runs immediately after a component is mounted to the DOM. It’s ideal for initializing tasks like fetching data, setting up subscriptions, or manipulating the DOM.

Example:

class DataFetcher extends React.Component {
state = { data: null };
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return <div>{this.state.data ? this.state.data.name : 'Loading...'}</div>;
}
}

Key Points:

  • Runs only once after the initial render.
  • Equivalent to useEffect with an empty dependency array in functional components.
  • Avoid setting state in a loop to prevent performance issues.

19. Difference between ES6 and ES5 syntax in React.

ES6 (ECMAScript 2015) introduced modern JavaScript features that simplify React development compared to ES5. These differences impact how components, imports, and functions are written.

Comparison Table:

FeatureES5ES6
Importing Reactvar React = require('react');import React from 'react';
Exporting Componentsmodule.exports = Component;export default Component;
Function Declarationvar sum = function(x, y) { return x + y; };const sum = (x, y) => x + y;
Class Componentsvar MyComponent = React.createClass({ ... });class MyComponent extends React.Component { ... }
State Initializationthis.state = { count: 0 }; (in constructor)state = { count: 0 }; (Class Fields)
Method Bindingthis.handleClick = this.handleClick.bind(this); (in constructor)No binding needed with arrow functions: handleClick = () => { ... };

Example (ES5):

var MyComponent = React.createClass({
getInitialState: function() {
return { count: 0 };
},
handleClick: function() {
this.setState({ count: this.state.count + 1 });
},
render: function() {
return <button onClick={this.handleClick.bind(this)}>{this.state.count}</button>;
}
});

Example (ES6):

import React from 'react';
class MyComponent extends React.Component {
state = { count: 0 };
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return <button onClick={this.handleClick}>{this.state.count}</button>;
}
}
export default MyComponent;

Key Points:

  • ES6 syntax is more concise and readable, especially with arrow functions and class fields.
  • ES5 requires manual binding of methods, while ES6 arrow functions eliminate this need.
  • Modern React projects use ES6+ for better developer experience and compatibility.

20. What are synthetic events in React?

Synthetic events are React’s cross-browser wrapper around native browser events. They normalize event properties and behavior to ensure consistency across different browsers. Synthetic events are used in event handlers (e.g., onClick, onChange) and provide a unified API for handling user interactions.

Example:

function Button() {
const handleClick = (event) => {
console.log(event.type); // 'click'
console.log(event.target); // DOM element
};
return <button onClick={handleClick}>Click Me</button>;
}

Key Points:

  • Synthetic events are pooled for performance, so their properties can’t be accessed asynchronously.
  • They support all standard browser events but are optimized for React’s rendering model.
  • Use event.preventDefault() to stop default browser behavior (e.g., form submission).

21. What is the Context API in React?

The Context API allows sharing global data (e.g., themes, user authentication) across a React component tree without prop drilling. It provides a Provider to supply data and a Consumer (or useContext hook) to access it in nested components.

Syntax:

const MyContext = React.createContext(defaultValue);

Example:

import { 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 <div>Current theme: {theme}</div>;
}

Key Points:

  • Use Context for global data like themes, locales, or auth states.
  • Avoid overuse; it can make components harder to test and reuse.
  • The useContext hook simplifies consuming context in functional components.

22. How can you optimize the performance of a React application?

Optimizing a React application improves rendering speed and user experience. Key techniques include minimizing re-renders, reducing bundle size, and efficient state management.

Techniques:

  1. Use React.memo: Prevents unnecessary re-renders of functional components when props don’t change.
    const MyComponent = React.memo(({ data }) => <div>{data}</div>);
  2. Lazy Loading and Code Splitting: Use React.lazy and Suspense to load components only when needed.
    const LazyComponent = React.lazy(() => import('./LazyComponent'));
    function App() {
    return (
    <Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
    </Suspense>
    );
    }
  3. Use useCallback and useMemo: Cache functions and values to avoid unnecessary recalculations.
    const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  4. Avoid Unnecessary Re-renders: Minimize state changes and use keys in lists to optimize rendering.
  5. Use Production Builds: Ensure the app is built with NODE_ENV=production to enable optimizations.

Key Points:

  • Profile performance with React Developer Tools to identify bottlenecks.
  • Optimize images and assets to reduce load times.
  • Consider server-side rendering (SSR) with Next.js for faster initial loads.

23. What is the purpose of the useCallback hook in React?

The useCallback hook returns a memoized version of a function that only changes if its dependencies change. It’s used to prevent unnecessary function recreations, which can cause child components to re-render unnecessarily when passed as props.

Syntax:

const memoizedCallback = useCallback(() => {
// Function logic
}, [dependencies]);

Example:

import { useState, useCallback } from 'react';
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <Child onClick={handleClick} />;
}
const Child = React.memo(({ onClick }) => {
console.log('Child rendered');
return <button onClick={onClick}>Click</button>;
});

Key Points:

  • Use useCallback for functions passed to memoized components.
  • Dependencies must include all variables used in the function.
  • Overusing useCallback can add complexity; use only when needed.

24. What are Higher-Order Components (HOCs) in React?

Higher-Order Components (HOCs) are functions that take a component and return a new component with enhanced functionality. HOCs are used for code reuse, adding features like authentication, logging, or data fetching to components.

Example:

function withAuth(Component) {
return function WrappedComponent(props) {
const isAuthenticated = checkAuth(); // Assume some auth logic
if (!isAuthenticated) {
return <Redirect to="/login" />;
}
return <Component {...props} />;
};
}
const ProtectedComponent = withAuth(MyComponent);

Key Points:

  • HOCs promote reusability but can increase complexity.
  • Alternatives include hooks or render props for similar functionality.
  • Use meaningful names for HOCs (e.g., withAuth, withData).

25. What is the purpose of the useReducer hook in React?

The useReducer hook manages complex state logic in functional components. It’s an alternative to useState for scenarios involving multiple state transitions or interdependent state updates, similar to Redux’s reducer pattern.

Syntax:

const [state, dispatch] = useReducer(reducer, initialState);

Example:

import { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}

Key Points:

  • Use useReducer for complex state logic with multiple actions.
  • Dispatch actions to update state predictably.
  • Can be combined with Context API for global state management.

26. What is a React Portal?

React Portals allow rendering a component’s children into a DOM node outside the parent component’s DOM hierarchy. They are useful for rendering modals, tooltips, or popovers that need to break out of their parent’s CSS or DOM constraints.

Syntax:

ReactDOM.createPortal(child, container);

Example:

import ReactDOM from 'react-dom';
function Modal() {
return ReactDOM.createPortal(
<div className="modal">Modal Content</div>,
document.getElementById('modal-root')
);
}

HTML:

<div id="root"></div>
<div id="modal-root"></div>

Key Points:

  • Portals don’t affect React’s component tree, only the DOM.
  • Useful for handling z-index or overflow issues in modals.
  • Ensure the target DOM node exists (e.g., modal-root).

27. Explain the "Virtual DOM" in React.

The Virtual DOM is an in-memory representation of the real DOM. React uses it to optimize updates by comparing the new Virtual DOM with the previous one (diffing) and applying only the necessary changes to the real DOM. This process, called reconciliation, improves performance by minimizing costly DOM operations.

How It Works:

  1. When state or props change, React creates a new Virtual DOM tree.
  2. React compares it with the previous tree to identify differences.
  3. Only the changed parts are updated in the real DOM.

Example:

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

When count updates, React updates only the <p> element’s text, not the entire DOM.

Key Points:

  • The Virtual DOM reduces direct DOM manipulation, improving performance.
  • Diffing is fast because it operates on lightweight JavaScript objects.
  • Frameworks like Next.js enhance Virtual DOM with SSR.

28. What are keys in React and why are they important?

Keys are unique identifiers used in React lists to help React efficiently update and reconcile elements. They ensure React can track which items have changed, been added, or removed, optimizing rendering performance.

Example:

function List() {
const items = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}

Key Points:

  • Use unique, stable keys (e.g., item IDs) instead of indices to avoid issues with list reordering.
  • Incorrect keys can lead to unexpected behavior or performance issues.
  • Keys are only needed for elements in arrays, not single components.

29. What is the difference between React.PureComponent and React.Component?

React.PureComponent is a base class like React.Component but includes an automatic shouldComponentUpdate implementation that performs a shallow comparison of props and state to prevent unnecessary re-renders.

Comparison:

FeatureReact.ComponentReact.PureComponent
Re-renderingRe-renders on every state/prop changeRe-renders only if props/state change (shallow)
PerformanceManual optimization neededAutomatic optimization via shallow comparison
Use CaseGeneral-purpose componentsPerformance-sensitive components

Example (PureComponent):

class MyPureComponent extends React.PureComponent {
render() {
console.log('Rendering');
return <div>{this.props.value}</div>;
}
}

Key Points:

  • Use PureComponent for components with simple props/state to avoid manual shouldComponentUpdate.
  • Shallow comparison may miss deep object changes; use immutable data or useMemo for complex cases.
  • Functional components with React.memo are the modern alternative.

30. What are the differences between Server-Side Rendering (SSR) and Client-Side Rendering (CSR) in React, and when would you use each?

Server-Side Rendering (SSR) and Client-Side Rendering (CSR) are two approaches to rendering React applications.

Comparison:

FeatureSSRCSR
Rendering LocationServer renders HTMLBrowser renders HTML after JS loads
Initial Load TimeFaster (HTML sent pre-rendered)Slower (waits for JS bundle)
SEOBetter (search engines see full HTML)Poor (search engines may miss dynamic content)
InteractivityDelayed until JS hydratesImmediate after JS loads
Use CaseSEO-heavy sites, static pagesInteractive SPAs, dashboards

Example (SSR with Next.js):

// pages/index.js
function HomePage({ data }) {
return <div>{data.title}</div>;
}
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}

When to Use:

  • SSR: Use for public-facing sites, blogs, or e-commerce platforms where SEO and fast initial loads are critical (e.g., with Next.js).
  • CSR: Use for private dashboards, SPAs, or apps where interactivity is prioritized over SEO.

Conclusion

Mastering these intermediate React concepts—hooks, routing, lifecycle methods, performance optimization, and more—prepares you to build efficient applications and excel in technical interviews. Practice these concepts with real-world projects, explore GeeksforGeeks React resources, and stay updated with React’s evolving ecosystem to secure your next React developer role in 2025.

ReactJS-interview-Questions-and-answers-Intermediate-Level
React Interview Questions and Answers (2025) - Intermediate Level

Next Article

Similar Reads