FrontendDeveloper.in

React Interview Questions

  • Question 31

    What is reconciliation?

    Reconciliation is the process through which React updates the Browser DOM and makes React work faster. React use a diffing algorithm so that component updates are predictable and faster. React would first calculate the difference between the real DOM and the copy of DOM (Virtual DOM) when there's an update of components. React stores a copy of Browser DOM which is called Virtual DOM. When we make changes or add data, React creates a new Virtual DOM and compares it with the previous one. This comparison is done by Diffing Algorithm. Now React compares the Virtual DOM with Real DOM. It finds out the changed nodes and updates only the changed nodes in Real DOM leaving the rest nodes as it is. This process is called Reconciliation.

  • Question 32

    Does the lazy function support named exports?

    No, currently React.lazy function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and don’t pull unused components. Let's take a component file which exports multiple named components,

    // MoreComponents.js
    export const SomeComponent = /* ... */;
    export const UnusedComponent = /* ... */;
    

    and reexport MoreComponents.js components in an intermediate file IntermediateComponent.js

    // IntermediateComponent.js
    export { SomeComponent as default } from "./MoreComponents.js";
    

    Now you can import the module using lazy function as below,

    import React, { lazy } from "react";
    const SomeComponent = lazy(() => import("./IntermediateComponent.js"));
    
  • Question 33

    Why React uses `className` over `class` attribute?

    React uses className instead of class because of a JavaScript naming conflict with the class keyword.

    1. class is a reserved keyword in JavaScript In JavaScript, class is used to define ES6 classes:
    class Person {
    constructor(name) {
    this.name = name;
    }
    }
    

    If you try to use class as a variable or property name, it will throw a syntax error. Since JSX is just JavaScript with XML-like syntax, using class directly in JSX would break the parser.

    1. JSX Is JavaScript

    When you write JSX like this:

    It will be compiled to:

    React.createElement('div', { class: 'btn' }, 'Click');
    

    But class is invalid in this object literal context (since it clashes with the JS keyword), hence React instead uses className.

    which compiles to:

    React.createElement('div', { className: 'btn' }, 'Click');
    

    React then translates className to class in the final HTML DOM.

    1. Aligns with DOM APIs In vanilla JavaScript, you interact with element classes using:
    element.className = 'my-class';
    

    React follows this convention, staying consistent with the DOM API's property name rather than HTML’s attribute.

  • Question 34

    What are fragments?

    It's a common pattern or practice in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. You need to use either <Fragment> or a shorter syntax having empty tag (<></>).

    Below is the example of how to use fragment inside Story component.

    function Story({ title, description, date }) {
    return (
    <Fragment>
    <h2>{title}</h2>
    </Fragment>
    );
    }
    

    It is also possible to render list of fragments inside a loop with the mandatory key attribute supplied.

    function StoryBook() {
    return stories.map((story) => (
    <Fragment key={story.id}>
    <h2>{story.title}</h2>
    </Fragment>
    ));
    }
    

    Usually, you don't need to use <Fragment> until there is a need of key attribute. The usage of shorter syntax looks like below.

    function Story({ title, description, date }) {
    return (
    <>
    <h2>{title}</h2>
    </>
    );
    }
    
  • Question 35

    Why fragments are better than container divs?

    Below are the list of reasons to prefer fragments over container DOM elements,

    1. Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
    2. Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
    3. The DOM Inspector is less cluttered.
  • Question 36

    What are portals in React?

    A Portal is a React feature that enables rendering children into a DOM node that exists outside the parent component's DOM hierarchy, while still preserving the React component hierarchy. Portals help avoid CSS stacking issues—for example, elements with position: fixed may not behave as expected inside a parent with transform. Portals solve this by rendering content (like modals or tooltips) outside such constrained DOM contexts.

    ReactDOM.createPortal(child, container);
    
    • child: Any valid React node (e.g., JSX, string, fragment).
    • container: A real DOM node (e.g., document.getElementById('modal-root')).

    Even though the content renders elsewhere in the DOM, it still behaves like a normal child in React. It has access to context, state, and event handling.

    Example:- Modal:

    function Modal({ children }) {
    return ReactDOM.createPortal(
    document.body)
    );
    }
    

    The above code will render the modal content into the body element in the HTML, not inside the component's usual location.

  • Question 37

    What are stateless components?

    If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.

  • Question 38

    What are stateful components?

    If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are either function components with hooks or class components.

    Let's take an example of function stateful component which update the state based on click event,

    import React, {useState} from 'react';
    
    const App = (props) => {
    const [count, setCount] = useState(0);
    handleIncrement() {
    setCount(count+1);
    }
    
    return (
    <>
    <button onClick={handleIncrement}>Increment</button>
    <span>Counter: {count}</span>
    </>
    )
    }
    

    See Class

    The equivalent class stateful component with a state that gets initialized in the constructor.

    class App extends Component {
    constructor(props) {
    super(props);
    this.state = { count: 0 };
    }
    
    handleIncrement() {
    setState({ count: this.state.count + 1 });
    }
    
    render() {
    <>
    <button onClick={() => this.handleIncrement}>Increment</button>
    <span>Count: {count}</span>
    </>;
    }
    }
    
  • Question 39

    How to apply validation on props in React?

    When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact. The mandatory props are defined with isRequired.

    The set of predefined prop types:

    1. PropTypes.number
    2. PropTypes.string
    3. PropTypes.array
    4. PropTypes.object
    5. PropTypes.func
    6. PropTypes.node
    7. PropTypes.element
    8. PropTypes.bool
    9. PropTypes.symbol
    10. PropTypes.any

    We can define propTypes for User component as below:

    import React from "react";
    import PropTypes from "prop-types";
    
    class User extends React.Component {
    static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired,
    };
    
    render() {
    return (
    <>
    <h1>{`Welcome, ${this.props.name}`}</h1>
    <h2>{`Age, ${this.props.age}`}</h2>
    </>
    );
    }
    }
    

    Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.

    The Equivalent Functional Component

    import React from "react";
    import PropTypes from "prop-types";
    
    function User({ name, age }) {
    return (
    <>
    <h1>{`Welcome, ${name}`}</h1>
    <h2>{`Age, ${age}`}</h2>
    </>
    );
    }
    
    User.propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired,
    };
    
  • Question 40

    What are the advantages of React?

    Below are the list of main advantages of React,

    1. Increases the application's performance with Virtual DOM.
    2. JSX makes code easy to read and write.
    3. It renders both on client and server side (SSR).
    4. Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
    5. Easy to write unit and integration tests with tools such as Jest.
  • Question 41

    What are the limitations of React?

    Apart from the advantages, there are few limitations of React too,

    1. React is just a view library, not a full framework.
    2. There is a learning curve for beginners who are new to web development.
    3. Integrating React into a traditional MVC framework requires some additional configuration.
    4. The code complexity increases with inline templating and JSX.
    5. Too many smaller components leading to over engineering or boilerplate.
  • Question 42

    What are the recommended ways for static type checking?

    Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.

  • Question 43

    What is the use of `react-dom` package?

    The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:

    1. render()
    2. hydrate()
    3. unmountComponentAtNode()
    4. findDOMNode()
    5. createPortal()
  • Question 44

    What is ReactDOMServer?

    The ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:

    1. renderToString()
    2. renderToStaticMarkup()

    For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString to render your root component to a string, which you then send as response.

    // using Express
    import { renderToString } from "react-dom/server";
    import MyPage from "./MyPage";
    
    app.get("/", (req, res) => {
    res.write(
    "<!DOCTYPE html><html><head><title>My Page</title></head><body>"
    );
    res.write('<div id="content">');
    res.write(renderToString(<MyPage />));
    res.write("</div></body></html>");
    res.end();
    });
    
  • Question 45

    How to use innerHTML in React?

    The dangerouslySetInnerHTML attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.

    In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

    function createMarkup() {
    return { __html: "First &middot; Second" };
    }
    
    function MyComponent() {
    return <div dangerouslySetInnerHTML={createMarkup()} />;
    }
    
Get LinkedIn Premium at Rs 399