FrontendDeveloper.in

React Interview Questions

  • Question 16

    What are synthetic events in React?

    SyntheticEvent is a cross-browser wrapper around the browser's native event. Its API is same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. The native events can be accessed directly from synthetic events using nativeEvent attribute.

    Let's take an example of BookStore title search component with the ability to get all native event properties

    function BookStore() {
    function handleTitleChange(e) {
    console.log("The new title is:", e.target.value);
    console.log('Synthetic event:', e); // React SyntheticEvent
    console.log('Native event:', e.nativeEvent); // Browser native event
    e.stopPropagation();
    e.preventDefault();
    }
    
    return <input name="title" onChange={handleTitleChange} />;
    }
    

    List of common synthetic events are:

    • onClick
    • onChange
    • onSubmit
    • onKeyDown, onKeyUp
    • onFocus, onBlur
    • onMouseEnter, onMouseLeave
    • onTouchStart, onTouchEnd
  • Question 17

    What are inline conditional expressions?

    You can use either if statements or ternary expressions which are available in JS(and JSX in React) to conditionally execute or render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&. It is helpful to render elements conditionally within a single line and commonly used for concise logic, especially in JSX rendering.

    <h1>Hello!</h1>;
    {
    messages.length > 0 && !isLogin ? (
    <h2>You have {messages.length} unread messages.</h2>
    ) : (
    <h2>You don't have unread messages.</h2>
    );
    }
    
  • Question 18

    What is "key" prop and what is the benefit of using it in arrays of elements?

    A key is a special attribute you should include when mapping over arrays to render data. Key prop helps React identify which items have changed, are added, or are removed.

    Keys should be unique among its siblings. Most often we use ID from our data as key:

    const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
    

    When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:

    const todoItems = todos.map((todo, index) => (
    <li key={index}>{todo.text}</li>
    ));
    

    Benefits of key:

    • Enables React to efficiently update and re-render components.
    • Prevents unnecessary re-renders by reusing components when possible.
    • Helps maintain internal state of list items correctly.

    Note:

    1. Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
    2. If you extract list item as separate component then apply keys on list component instead of li tag.
    3. There will be a warning message in the console if the key prop is not present on list items.
    4. The key attribute accepts either string or number and internally convert it as string type.
    5. Don't generate the key on the fly something like key={Math.random()}. Because the keys will never match up between re-renders and DOM created everytime.
  • Question 19

    What is Virtual DOM?

    The Virtual DOM (VDOM) is a lightweight, in-memory representation of Real DOM used by libraries like React to optimize UI rendering. The representation of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.

  • Question 20

    How Virtual DOM works?

    The Virtual DOM works in five simple steps.

    1. Initial Render When a UI component renders for the first time, it returns JSX. React uses this structure to create a Virtual DOM tree, which is a lightweight copy of the actual DOM. This Virtual DOM is then used to build and render the Real DOM in the browser.

    2. State or Props Change When the component's state or props change, React creates a new Virtual DOM reflecting the updated UI. However, it doesn't immediately update the Real DOM; instead, it works in memory to prepare for an efficient update.

    vdom

    3. Diffing Algorithm React then compares the new Virtual DOM with the previous one using a process called diffing. It determines what has changed between the two versions and identifies the minimal set of updates needed.

    vdom2

    4. Reconciliation Based on the diffing results, React decides which parts of the Real DOM should be updated. It avoids re-rendering the entire DOM and instead updates only the elements that actually changed.

    vdom3

    5. Efficient DOM Updates This entire process—working with the Virtual DOM, diffing, and selective updating—makes the UI rendering much faster and more efficient than manipulating the Real DOM directly.

  • Question 21

    What is the difference between Shadow DOM and Virtual DOM?

    The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.

    The key differences in a table format shown below:

    FeatureShadow DOMVirtual DOM
    PurposeEncapsulation for Web ComponentsEfficient UI rendering
    Managed byBrowserJS frameworks (e.g., React)
    DOM TypePart of real DOM (scoped)In-memory representation
    EncapsulationYesNo
    Use CaseWeb Components, scoped stylingUI diffing and minimal DOM updates
  • Question 22

    What is React Fiber?

    React Fiber is the new reconciliation engine in React, introduced in React 16. It’s a complete rewrite of React’s core algorithm(old stack-based algorithm) for rendering and updating the UI. Fiber enhances React’s ability to handle asynchronous rendering, prioritized updates(assign priority to different types of updates), and interruption(ability to pause, abort, or reuse work) of rendering work, enabling smoother and more responsive user interfaces.

  • Question 23

    What is the main goal of React Fiber?

    The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

    Its main goals are:

    • Incremental Rendering – Breaks work into chunks for smoother updates.
    • Interruptible Rendering – Pauses and resumes rendering to keep the UI responsive.
    • Prioritization – Handles high-priority updates (e.g. animations) before low-priority ones.
    • Concurrency Support – Enables working on multiple UI versions simultaneously.
    • Better Error Handling – Supports component-level error boundaries.
    • Suspense Support – Allows waiting for async data before rendering.
    • Improved DevTools – Enables better debugging and performance tracking.
  • Question 24

    What are controlled components?

    A controlled component is a React component that fully manages the form element's state(e.g, elements like <input>, <textarea>, or <select>)) using React's internal state mechanism. i.e, The component does not manage its own internal state — instead, React acts as the single source of truth for form data.

    The controlled components will be implemented using the below steps,

    1. Initialize the state using useState hooks in function components or inside constructor for class components.
    2. Set the value of the form element to the respective state variable.
    3. Create an event handler(onChange) to handle the user input changes through useState's updater function or setState from class component.
    4. Attach the above event handler to form element's change or click events

    Note: React re-renders the component every time the input value changes.

    For example, the name input field updates the username using handleChange event handler as below,

    import React, { useState } from "react";
    
    function UserProfile() {
    const [username, setUsername] = useState("");
    
    const handleChange = (e) => {
    setUsername(e.target.value);
    };
    
    return (
    <form>
    <label>
    Name:
    <input type="text" value={username} onChange={handleChange} />
    </label>
    </form>
    );
    }
    

    In these components, DOM does not hold the actual data instead React does.

    Benefits:

    • Easy to implement validation, conditional formatting, or live feedback.
    • Full control over form data.
    • Easier to test and debug because the data is centralized in the component’s state.
  • Question 25

    What are uncontrolled components?

    The Uncontrolled components are form elements (like <input>, <textarea>, or <select>) that manage their own state internally via the DOM, rather than through React state. You can query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

    The uncontrolled components will be implemented using the below steps,

    1. Create a ref using useRef react hook in function component or React.createRef() in class based component.
    2. Attach this ref to the form element.
    3. The form element value can be accessed directly through ref in event handlers or componentDidMount for class components

    In the below UserProfile component, the username input is accessed using ref.

    import React, { useRef } from "react";
    
    function UserProfile() {
    const usernameRef = useRef(null);
    
    const handleSubmit = (event) => {
    event.preventDefault();
    console.log("The submitted username is: " + usernameRef.current.value);
    };
    
    return (
    <form onSubmit={handleSubmit}>
    <label>
    Username:
    <input type="text" ref={usernameRef} />
    </label>
    <button type="submit">Submit</button>
    </form>
    );
    }
    

    Note: Here, DOM is in charge of the value. React only accesses the value when needed (via ref).

    Benefits:

    • Less boilerplate — no need for useState and onChange.
    • Useful for quick form setups or when integrating with non-React code.
    • Slightly better performance in very large forms (fewer re-renders).

    In most cases, it's recommend to use controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

    See Class

    class UserProfile extends React.Component {
    constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
    }
    
    handleSubmit(event) {
    alert("A name was submitted: " + this.input.current.value);
    event.preventDefault();
    }
    
    render() {
    return (
    <form onSubmit={this.handleSubmit}>
    <label>
    {"Name:"}
    <input type="text" ref={this.input} />
    </label>
    <input type="submit" value="Submit" />
    </form>
    );
    }
    }
    
  • Question 26

    What is the difference between createElement and cloneElement?

    Both React.createElement and React.cloneElement are used to work with React elements, but they serve different purposes.

    createElement:

    Creates a new React element from scratch. JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI. Syntax:

    React.createElement(type, props, ...children)
    

    Example:

    React.createElement('button', { className: 'btn' }, 'Click Me')
    

    cloneElement:

    The cloneElement method is used to clone an existing React element and optionally adds or overrides props.

    Syntax:

    React.cloneElement(element, newProps, ...children)
    

    Example:

    const button = <button className="btn">Click Me</button>;
    const cloned = React.cloneElement(button, { className: 'btn-primary' });
    // Result: <button className="btn-primary">Click Me</button>
    
  • Question 27

    What is Lifting State Up in React?

    When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.

  • Question 28

    What are Higher-Order Components?

    A higher-order component (HOC) is a function that takes a component and returns a new enhanced component with additional props, behavior, or data. It’s a design pattern based on React’s compositional nature, allowing you to reuse logic across multiple components without modifying their internals.

    We consider HOCs pure components because they don’t mutate or copy behavior from the original component—they simply wrap it, enhance it, and pass through the necessary props. The wrapped component remains decoupled and reusable.

    const EnhancedComponent = higherOrderComponent(WrappedComponent);
    

    Let's take an example of a withAuth higher-order component (HOC) in React. This HOC will check if a user is authenticated and either render the wrapped component if authenticated or redirect (or show a message) if not.

    withAuth HOC Example:

    import React from 'react';
    import { Navigate } from 'react-router-dom'; // For redirection (assuming React Router v6)
    
    const isAuthenticated = () => {
    // e.g., check for a valid token in localStorage or context
    return !!localStorage.getItem('authToken');
    };
    
    function withAuth(WrappedComponent) {
    return function AuthenticatedComponent(props) {
    if (!isAuthenticated()) {
    // User is NOT authenticated, redirect to login page
    return <Navigate to="/login" replace />;
    }
    
    // User is authenticated, render the wrapped component
    return <WrappedComponent {...props} />;
    };
    }
    
    export default withAuth;
    

    Usage

    import React from 'react';
    import withAuth from './withAuth';
    
    function Dashboard() {
    return <h1>Welcome to the Dashboard!</h1>;
    }
    
    // Wrap Dashboard with withAuth HOC
    export default withAuth(Dashboard);
    

    HOC can be used for many use cases:

    1. Code reuse, logic and bootstrap abstraction (e.g., fetching data, permissions, theming).
    2. Render hijacking (e.g., conditional rendering or layout changes).
    3. State abstraction and manipulation(e.g., handling form logic).
    4. Props manipulation(e.g., injecting additional props or filtering them).

    Some of the real-world examples of HOCs in react eco-system:

    1. connect() from react-redux
    2. withRouter() from React Router v5
    3. withTranslation() from react-i18next
    4. withApollo() from Apollo client
    5. withFormik from Formik library
    6. withTheme from styled components
  • Question 29

    What is children prop?

    The children prop is a special prop in React used to pass elements between the opening and closing tags of a component. It is commonly used in layout and wrapper componnents.

    A simple usage of children prop looks as below,

    function MyDiv({ children }){
    return (
    {children}
    );
    }
    
    export default function Greeting() {
    return (
    <MyDiv>
    <span>{"Hello"}</span>
    <span>{"World"}</span>
    </MyDiv>
    );
    }
    

    Here, everything inside <MyDiv>...</MyDiv> is passed as children to the custom div component.

    The children can be text, JSX elements, fragments, arrays and functions(for advance use case like render props).

    See Class

    const MyDiv = React.createClass({
    render: function () {
    return <div>{this.props.children}</div>;
    },
    });
    
    ReactDOM.render(
    <MyDiv>
    <span>{"Hello"}</span>
    <span>{"World"}</span>
    </MyDiv>,
    node
    );
    

    Note: There are several methods available in the legacy React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray.

  • Question 30

    How to write comments in React?

    The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.

    Single-line comments:

    {/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */}
    {`Welcome ${user}, let's play React`}
    

    Multi-line comments:

    {/* Multi-line comments for more than
     one line */}
    {`Welcome ${user}, let's play React`}
    

    You can use // and /* */ in JS logic, hooks, and functions.

Get LinkedIn Premium at Rs 399