Examness

Web & Design

React Interview Questions

Components, hooks, state, rendering and performance.

346 questions

  1. 1.

    What is reconciliation in React?

    Beginner

    Reconciliation is the process React uses to determine how to efficiently update the real browser DOM when a component\'s state or props change. Instead of rebuilding the entire UI from scratch, React compares a new representation of the interface with the previous one and applies only the necessary changes.

    How the Process Works

    • Virtual DOM Creation: When an update is triggered, React creates a new Virtual DOM (a lightweight, in-memory copy of the UI).
    • Diffing: React uses a "diffing algorithm" to compare the new Virtual DOM tree with the old one.
    • Patching: Once the differences are identified, React calculates the minimal set of operations needed to update the actual DOM and applies them in a single batch to ensure high performance.

    Key Rules of the Diffing Algorithm

    To keep the reconciliation process fast (complexity), React follows two primary heuristic assumptions:

    • Elements of Different Types: If the root elements of a subtree have different types (e.g., changing a to a ), React will tear down the old tree, destroy its state, and build the new one from scratch.
    • Elements of the Same Type: If elements are of the same type, React keeps the underlying DOM node and only updates the changed attributes or properties.
    • Keys for Lists: For lists of elements, React uses the key prop to track which items have moved, been added, or removed, preventing unnecessary re-renders of stable items.

    Evolution: React Fiber

    Since React 16, the core reconciliation engine has been reimplemented as React Fiber. This modern architecture allows React to break rendering work into small units and pause, resume, or prioritize them, making complex UIs much more responsive by not blocking the main thread

    ↥ back to top

  2. 2.

    What are the drawbacks of MVW pattern?

    Beginner

    MVW stands for Model-View-Whatever

    • MVC - Model-View-Controller
    • MVP - Model-View-Presenter
    • MVVM - Model-View-ViewModel
    • MVW / MV* / MVx - Model-View-Whatever
    • HMVC - Hierarchical Model-View-Controller
    • MMV - Multiuse Model View
    • MVA - Model-View-Adapter

    In React.js, the MVW (Model-View-Whatever) pattern—which typically encompasses variations like MVC (Model-View-Controller) or MVVM (Model-View-ViewModel)—is often considered a "mismatch" for React\'s core philosophy.

    Drawbacks as applications scale:

    • Uncontrolled state changes — As the number of models and controllers grows, they start communicating with each other through service layers, each modifying the other\'s state. It becomes increasingly difficult to track who changed what and when.
    • Nondeterministic UI state — Asynchronous network calls make the timing of model updates unpredictable. If a user interacts with the UI while an async callback is still in-flight, the resulting state can be inconsistent and hard to reason about.
    • Complex mutation tracking — Determining when state has actually changed adds another layer of complexity. You need additional tooling or conventions just to detect and respond to mutations reliably.
    • Poor fit for real-time/collaborative apps — Applications like Google Docs, where many data changes happen simultaneously from multiple sources, expose the fundamental weaknesses of MVW\'s bidirectional data flow.
    • No built-in undo/time-travel — Implementing undo/redo requires significant extra boilerplate because there is no single source of truth or immutable state history.

    React\'s unidirectional data flow (actions → reducer → state → UI) and Redux\'s single immutable state tree were specifically designed to solve these MVW problems — making state changes predictable, traceable, and replayable.

    ↥ back to top

  3. 3.

    What is route based code splitting?

    Beginner

    Route based code splitting is essential during the page transitions on the web, which takes some amount of time to load. Here is an example of how to setup route-based code splitting into the app using React Router with React.lazy.

    Key Benefits

    • Faster Initial Load: By shrinking the initial JavaScript payload, the time to first render is significantly reduced.
    • Reduced Bandwidth: Users only download the code for the parts of the site they actually visit.
    • Better Caching: When you update one page, only the chunk for that specific route needs to be re-downloaded by returning users, while others remain cached.
    • Improved Interactivity: Smaller bundles are parsed and executed faster by the browser, leading to a better Interaction to Next Paint (INP)

    Example:

    /**
     * Lazy Loading
     */
    import React, { Suspense, lazy } from "react";
    import { BrowserRouter, Routes, Route } from "react-router-dom";
    
    const Home = lazy(() => import("./Home"));
    const About = lazy(() => import("./About"));
    
    export default function App() {
      return (
        <BrowserRouter>
          <Suspense fallback={<div>Loading...</div>}>
            <Routes>
              <Route exact path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
            </Routes>
          </Suspense>
        </BrowserRouter>
      );
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  4. 4.

    What is the recommended ordering of methods in class component?

    Beginner
    • static methods
    • constructor()
    • getChildContext()
    • componentWillMount()
    • componentDidMount()
    • componentWillReceiveProps()
    • shouldComponentUpdate()
    • componentWillUpdate()
    • componentDidUpdate()
    • componentWillUnmount()
    • click handlers or event handlers like onClickSubmit() or onChangeDescription()
    • getter methods for render like getSelectReason() or getFooterContent()
    • optional render methods like renderNavigation() or renderProfilePicture()
    • render()

    This ordering helps maintain consistency and readability in your class components by grouping related methods together: lifecycle methods first, then event handlers, helper methods, and finally the render method at the bottom.

    ↥ back to top

  5. 5.

    What are default props?

    Beginner

    The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed.

    The defaultProps can be defined as a property on the component class itself to set the default props for the class. defaultProps is used for undefined props, not for null props.

    /**
     * Default Props
     */
    class MessageComponent extends React.Component {
       render() {
            return (
              <div>Hello, {this.props.value}.</div>
            )
        }
    }
    
    // Pass default Props
    MessageComponent.defaultProps = {
      value: 'World'  
    }

    For function components, you can use default values in destructuring:

    Example:

    function Greeting({ name = "Guest" }) {
      return <h1>Hello, {name}!</h1>;
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  6. 6.

    What is the benefit of component stack trace from error boundary?

    Beginner

    Component Stack Trace prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. It also display the filenames and line numbers in the component stack trace.

    Example:

    ↥ back to top

  7. 7.

    What are Pure Components in React?

    Beginner

    Pure Components in React are the components which do not re-renders when the value of state and props has been updated with the same values. Pure Components restricts the re-rendering ensuring the higher performance of the Component.

    Features of React Pure Components:

    • Prevents re-rendering of Component if props or state is the same
    • Takes care of shouldComponentUpdate() implicitly
    • State() and Props are Shallow Compared
    • Pure Components are more performant in certain cases

    Example:

    /**
     * React Pure Component
     */
    export default class App extends React.PureComponent {
      constructor() {
        super();
        this.state = {
          userArray: [1, 2, 3, 4, 5]
        };
        // Here we are creating the new Array Object during setState using "Spread" Operator
        setInterval(() => {
          this.setState({
            userArray: [...this.state.userArray, 6]
          });
        }, 1000);
      }
    
      render() {
        return <b>Array Length is: {this.state.userArray.length}</b>;
      }
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  8. 8.

    What is the purpose of render() function in React?

    Beginner

    In React, the render() function is a core lifecycle method used primarily in class components to define the visual structure of the user interface (UI). It acts as a "blueprint" that tells React what elements should appear on the screen based on the component\'s current data

    Key purposes:

    • Returns UI elements - Displays specified HTML/JSX inside a DOM element
    • Reads props and state - Accesses component data to determine what to render
    • Pure function - Cannot modify state or cause side effects (like HTTP requests)
    • Required method - Every class component must have a render() method

    Example:

    /**
     * render() function
     * 
     */
    class App extends React.Component {
      render() {
        return <h1>Render() Method Example</h1>;
      }
    }

    The render() method is called automatically whenever props or state change, causing React to update the DOM with the new output.

    Note:

    The modern React (v18+), functional components use return directly instead of a render() method, and the actual DOM rendering is done via `createRoot().render()`.

    &#9885; Try this example on CodeSandbox

    ↥ back to top

    # 4.2.1. REACT LIFECYCLE

  9. 9.

    What is JSX?

    Beginner

    JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code directly in JavaScript. It is used in React to describe what the UI should look like.

    JSX is not required for React, but it makes code more readable and easier to write. Under the hood, it\'s just syntactic sugar for React.createElement() calls.

    Key Points:

    • No DOM methods needed - Write HTML in JavaScript without createElement() or appendChild()
    • Compiles to JavaScript - JSX transforms into regular JavaScript objects
    • Type-safe - Most errors caught during compilation
    • Performance - Optimizations applied during compilation

    Example:

    // JSX syntax
    const hello = <h1 className="greet">Hello World</h1>
    
    // Compiles to:
    const hello = React.createElement("h1", {
      className: "greet"
    }, "Hello World")

    In a component:

    export default function App() {
      return (
        <div className="App">
          <h1>Hello World!</h1>
        </div>
      );
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  10. 10.

    What is the alternative of binding this in the constructor?

    Beginner

    Arrow Function creates and binds the function all at once. Inside render (and elsewhere), the function is already bound because the arrow function preserves the this binding.

    Example:

    class Button extends React.Component {
      // no binding
      handleClick = (e) => {
        console.log('clicked !');
      }
      render() {
        return <button onClick={this.handleClick}>Click Me</button>;
      }
    }

    ↥ back to top

    # 9. REACT LISTS

  11. 11.

    What is Apollo Client and how to use it with React?

    Beginner

    Apollo Client is the most popular GraphQL client for React. It handles data fetching, caching, and state management for GraphQL APIs.

    Setup:

    npm install @apollo/client graphql
    // index.jsx - Configure Apollo Client
    import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink } from '@apollo/client';
    import { setContext } from '@apollo/client/link/context';
    
    const httpLink = createHttpLink({ uri: 'https://api.example.com/graphql' });
    
    const authLink = setContext((_, { headers }) => {
      const token = sessionStorage.getItem('authToken');
      return {
        headers: { ...headers, authorization: token ? `Bearer ${token}` : '' },
      };
    });
    
    const client = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    });
    
    root.render(
      <ApolloProvider client={client}>
        <App />
      </ApolloProvider>
    );

    ↥ back to top

  12. 12.

    What is children props?

    Beginner

    The {this.props.children} is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component.

    Example:

    /**
     * React Children Props
     */
    function MyComponent(props) {
      return <div>{props.children}</div>;
    }
    
    // Usage:
    <MyComponent>
      <p>This is a child element.</p>
      <AnotherComponent />
    </MyComponent>

    Here, props.children will contain the and elements.

    Key points:

    • Enables component composition and nesting.
    • Can be a single element, multiple elements, or even text.
    • Used for flexible layouts and reusable wrappers.

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  13. 13.

    What are fragments?

    Beginner

    React Fragments are a way to group multiple elements without adding an extra node to the browser\'s DOM.

    Why use Fragments?

    • Avoid extra DOM nodes that can affect styling and layout
    • Cleaner DOM structure
    • Better performance (fewer nodes to render)
    • Satisfy React\'s requirement that components return a single element
    • Adding a inside elements like , , or can break the browser\'s layout rules.

    Example:

    // Long syntax
    import React, { Fragment } from 'react';
    
    function MyComponent() {
      return (
        <Fragment>
          <h1>Title</h1>
          <p>Description</p>
        </Fragment>
      );
    }
    
    // Short syntax (more common)
    function MyComponent() {
      return (
        <>
          <h1>Title</h1>
          <p>Description</p>
        </>
      );
    }

    ↥ back to top

  14. 14.

    What are React Hooks?

    Beginner

    React Hooks are in-built functions that let you "hook into" React features like state, lifecycle behavior, context, and more from function components (without writing class components).

    Rules of Hooks:

    • Call Hooks only at the top level
    • Hooks should not be called inside loops, conditions, or nested functions.
    • Hooks should be used inside React function components or custom Hooks

    Built-in Hooks:

    HooksDescription
    useState()To manage states. Returns a stateful value and an updater function to update it.
    useEffect()To manage side-effects like API calls, subscriptions, timers, mutations, and more.
    useContext()To return the current value for a context.
    useReducer()A useState alternative to help with complex state management.
    useCallback()It returns a memorized version of a callback to help a child component not re-render unnecessarily.
    useMemo()It returns a memoized value that helps in performance optimizations.
    useRef()It returns a ref object with a .current property. The ref object is mutable. It is mainly used to access a child component imperatively.
    useImperativeHandle()It customizes the instance value that is exposed to parent components when using ref.
    useLayoutEffect()It fires at the end of all DOM mutations. It\'s best to use useEffect as much as possible over this one as the useLayoutEffect fires synchronously.

    |useDebugValue() |Helps to display a label in React DevTools for custom hooks.

    Example:

    /**
     * useState() Hooks
     */
    import { useState } from "react";
    
    function App() {
      const [isButtonClicked, setIsButtonClicked] = useState(false);
    
      return (
        <button onClick={() => setIsButtonClicked(!isButtonClicked)}>
          {isButtonClicked ? "Clicked" : "Click Me, Please"}
        </button>
      );
    }
    
    export default App;

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  15. 15.

    What is the browser support for react applications?

    Beginner

    React applications are supported by all modern web browsers. Because React uses JavaScript ES5 features as its baseline, it can be extended to older browsers with the right configuration.

    Support for Internet Explorer 9, 10, and 11 requires polyfills. For a set of polyfills to support older browsers, use react-app-polyfill.

    Browser Configuration:

    The browserslist configuration in package.json controls which browsers are supported by determining what JavaScript transformations are applied:

    Example:

    // package.json
    
    "browserslist": {
      "production": [
        ">0.2%",          // Browsers with >0.2% market share
        "not dead",       // Still maintained browsers
        "not op_mini all" // Exclude Opera Mini
      ],
      "development": [
        "last 1 chrome version",
        "last 1 firefox version",
        "last 1 safari version"
      ]
    }

    ↥ back to top

  16. 16.

    What is React.js?

    Beginner

    React is a JavaScript library created for building fast and interactive user interfaces for web and mobile applications. It is an open-source, component-based, front-end library responsible only for the application view layer.

    The main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. It uses virtual DOM (JavaScript object), which improves the performance of the app. The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS on the client and server-side as well as with other frameworks. It uses component and data patterns that improve readability and helps to maintain larger apps.

    Reference:

    • https://reactjs.org/tutorial/tutorial.html

    ↥ back to top

  17. 17.

    What are the features of Vite?

    Beginner

    Vite is a modern build tool and development server with these key features:

    Core Features

    • Lightning-fast cold start using native ES modules
    • Instant Hot Module Replacement (HMR) that stays fast regardless of app size
    • No bundling during development

    Optimized Production Build

    • Uses Rollup for production bundling
    • Pre-configured and optimized out of the box
    • Code splitting and tree-shaking

    Rich Features

    • TypeScript support out of the box
    • JSX/TSX support
    • CSS pre-processors (Sass, Less, Stylus)
    • PostCSS support
    • Static asset handling
    • JSON importing

    ↥ back to top

  18. 18.

    What is Destructuring in React.js?

    Beginner

    Destructuring in React.js is a JavaScript ES6 feature that allows you to extract values from arrays or properties from objects into distinct variables. In React, it is widely used to make code cleaner and more readable.

    Key Uses in React:

    1. Props Destructuring:

    // Without destructuring
    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    // With destructuring
    function Welcome({ name, age }) {
      return <h1>Hello, {name}, you are {age} years old</h1>;
    }

    2. State Destructuring with Hooks:

    // Array destructuring with useState
    const [counter, setCounter] = React.useState(0);
    const [name, setName] = React.useState("John");
    
    // Object destructuring with useContext
    const { user, theme } = useContext(AppContext);

    3. Nested Object Destructuring:

    const user = {
      name: "Alice",
      address: {
        city: "New York",
        country: "USA"
      }
    };
    
    // Destructure nested properties
    const { name, address: { city } } = user;
    // name = "Alice", city = "New York"

    4. Class Component State:

    class App extends React.Component {
      render() {
        const { isLoggedIn, user } = this.state;
        return <div>{isLoggedIn ? user.name : "Guest"}</div>;
      }
    }

    ↥ back to top

  19. 19.

    What is State in React?

    Beginner

    In React, state is a built-in object that stores data or information about the component. State allows a component to keep track of changing information between renders. When the state of a component changes, React automatically re-renders the component to reflect the new state.

    Key Characteristics of State:

    • State is local to the component and controlled by the component itself.
    • State can be changed using the setState() method (in class components) or the useState() hook (in function components).
    • Changing state triggers a re-render of the component and its children.
    • State is used for dynamic data that can change over time, such as user input, toggles, counters, etc.

    Example:

    /**
     * React State
     */
    import { useState } from 'react';
    
    function Counter() {
      // Declares 'count' state variable and 'setCount' updater function
      const [count, setCount] = useState(0); 
    
      return <button onClick={() => setCount(count + 1)}>{count}</button>;
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  20. 20.

    What are functional components in react?

    Beginner

    A React functional component is a simple JavaScript function that accepts props and returns a React element. It also referred as stateless components as it simply accept data and display them in some form.

    After the introduction of React Hooks, writing functional components has become the ​standard way of writing React components in modern applications.

    Example:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    // Usage
    const element = <Welcome name="World!" />;

    With Hooks:

    import { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0); // State management via Hook
      
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top