geekskai Logogeekskai
ToolsBlogPricing
Sign in
Sign in
ToolsBlogSign in
Sunday, January 11, 2026|44.48Mins Read

Core React Interview Questions & Answers 2026

Authors
  • avatar
    Name
    Geeks Kai
    Twitter
    @KaiGeeks
Discuss on Twitter • View on GitHub

Tags

ReactReact-JS-Interview-QuestionsReact.js-Interview-QuestionsJavaScript-Interview-QuestionsReact-Interview-QuestionsFrontend-Interview

Previous Article

React Arrays & Lists Interview Questions 2026

Next Article

Beyond the Microscope: How Pathology Labs Embrace AI Adoption
← Back to the blog
geekskai Logo
geekskai

Public tools for developers and creators, plus optional Geekskai Audio Toolkit plans. Built with care.

Popular Tools

SoundCloud DownloaderSoundCloud to MP3SoundCloud to WAVSoundCloud PlaylistSoundCloud Artwork
View All Tools

Resources

BlogAbout MePricingTagsProjectsPrivacy PolicyTerms of ServiceRefund Policy

Connect With Us

mailMail
githubGitHub
twitterTwitter
linkedinLinkedin
© 2026 geekskai • All rights reserved
React interview questions and answers cover core topics like JSX, components, props, and state.
Core React interview questions: JSX, components, props, state, and Virtual DOM.

📖 Introduction

Prepare for React interviews by explaining component behavior and checking it with a small example. This guide retains 77 core questions, including JSX, props, state, rendering, events, and composition.

The current guidance targets React 19. Historical APIs are identified where they affect an answer. Most code blocks are component excerpts that need the application's normal entry point; snippets with additional prerequisites say so.

Start with state and props, rendering, or current React DOM APIs. For effects and asynchronous behavior, continue with the Hooks questions.

Core React

This section covers fundamental React JS interview questions about React basics, including JSX, components, props, state, and the Virtual DOM. These are essential concepts that every React developer should master.

  1. What is React?

    React is an open-source JavaScript library for building user interfaces from components. React DOM targets the browser; other renderers target other environments. A framework can add routing, data loading, and deployment conventions.

    The current API guidance here targets React 19. Identify the installed react and renderer versions when answering a version-dependent interview question. Class components and older APIs are discussed only where useful for maintaining existing code. See the React reference.

  2. What is the history behind React evolution?

    React began at Facebook and was open-sourced in 2013. Useful milestones for an interview include the Fiber architecture in React 16, Hooks in 16.8, concurrent rendering capabilities and broader batching in React 18, and API changes in React 19.

    Explain which milestone affects the code under discussion. XHP-inspired syntax and historical prototypes are background, not proof that React automatically prevents all injection problems or always renders faster. Consult the official React blog and the React 19 upgrade guide for versioned changes.

  3. What is JSX?

    JSX is a JavaScript syntax extension for describing UI. A build transform converts it to React element creation calls. The modern automatic transform can use the JSX runtime; it does not require every file to import a React namespace. The classic transform uses createElement.

    export default function Greeting() {
      return <h1 className="greeting">Hello</h1>
    }
    

    An equivalent explicit API example is:

    import { createElement } from "react"
    
    export default function Greeting() {
      return createElement("h1", { className: "greeting" }, "Hello")
    }
    

    See Writing markup with JSX.

  4. What is the difference between an Element and a Component?

    Element:

    • A React Element is a plain JavaScript object that describes what you want to see on the UI. It represents a DOM node or a component at a specific point in time.

    • Elements are immutable: once created, you cannot change their properties. Instead, you create new elements to reflect updates.

    • Elements can be nested within other elements through their props.

    • Creating an element is a fast, lightweight operation—it does not create any actual DOM nodes or render anything to the screen directly.

      Example (without JSX):

      const element = React.createElement("button", { id: "login-btn" }, "Login")
      

      Equivalent JSX syntax:

      <button id="login-btn">Login</button>
      

      The object returned by React.createElement:

      {
        type: 'button',
        props: {
          id: 'login-btn',
          children: 'Login'
        }
      }
      

      Elements are then passed to the React DOM renderer (e.g., createRoot(...).render()), which translates them to actual DOM nodes.


    Component:

    • A Component is a function or class that returns an element (or a tree of elements) to describe part of the UI. Components can accept inputs (called props) and manage their own state (in case of class or function components with hooks).

    • Components allow you to split the UI into independent, reusable pieces, each isolated and composable.

    • You can define a component using a function or a class:

      Example (Function Component with JSX):

      const Button = ({ handleLogin }) => (
        <button id="login-btn" onClick={handleLogin}>
          Login
        </button>
      )
      

      With the classic JSX transform, this can be expressed with React.createElement calls:

      const Button = ({ handleLogin }) =>
        React.createElement("button", { id: "login-btn", onClick: handleLogin }, "Login")
      

    In summary:

    • Elements are the smallest building blocks in React—objects that describe what you want to see.
    • Components are functions or classes that return elements and encapsulate logic, structure, and behavior for parts of your UI.

    Think of elements as the instructions for creating UI, and components as reusable blueprints that combine logic and structure to generate those instructions.

  5. How to create components in React?

    Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.

    1. Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the one and only one parameter and return React elements to render the output:

      function Greeting({ message }) {
        return <h1>{`Hello, ${message}`}</h1>
      }
      
    2. Class Components: You can also use ES6 class to define a component. The above function component can be written as a class component:

      class Greeting extends React.Component {
        render() {
          return <h1>{`Hello, ${this.props.message}`}</h1>
        }
      }
      
  6. When to use a Class Component over a Function Component?

    Use function components for new code. Hooks provide state and effects; needing state is not a reason to choose a class. Existing class components remain relevant when maintaining an application that uses them.

    A built-in error boundary is implemented with a class lifecycle API, but an application can use a maintained boundary component from a library. Check the boundary's documented scope: it does not catch every event-handler or asynchronous error. See the Component error-boundary reference.

  7. What are Pure Components?

    Rendering purity means a component produces its result from the same inputs without changing pre-existing values during render. Memoization is a separate optimization.

    React memo can skip a parent-driven render when props compare equal. The default comparison uses Object.is for each prop; local state or consumed context can still cause a render. It is not a correctness guarantee. See memo.

    import { memo } from "react"
    
    export const EmployeeProfile = memo(function EmployeeProfile({ name, email }) {
      return <p>{name}: {email}</p>
    })
    

    A class PureComponent shallowly compares props and state. Mutating an object in place can defeat that comparison. Profile an actual interaction before adding memoization.

  8. What is state in React?

    State is component memory. A useState value may be a string, number, boolean, object, array, or another supported JavaScript value; it is not limited to an object. Treat objects and arrays stored in state as immutable snapshots.

    import { useState } from "react"
    
    export default function Message() {
      const [message, setMessage] = useState("Welcome")
      return <button onClick={() => setMessage("Hello")}>{message}</button>
    }
    

    A setter requests a later render. It does not change the variable captured by the current event handler. See State as a snapshot.

  9. What are props in React?

    Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation similar to HTML-tag attributes. Here, the data is passed down from a parent component to a child component.

    The primary purpose of props in React is to provide following component functionality:

    1. Pass custom data to your component.
    2. Trigger state changes.
    3. Use via this.props.reactProp inside component's render() method.

    For example, let us create an element with reactProp property:

    <Element reactProp={"1"} />
    

    This reactProp (or whatever you came up with) attribute name then becomes a property attached to React's native props object which originally already exists on all components created using React library.

    props.reactProp
    

    For example, the usage of props in function component looks like below:

    import React from "react"
    import ReactDOM from "react-dom"
    
    const ChildComponent = (props) => {
      return (
        <div>
          <p>{props.name}</p>
          <p>{props.age}</p>
          <p>{props.gender}</p>
        </div>
      )
    }
    
    const ParentComponent = () => {
      return (
        <div>
          <ChildComponent name="John" age="30" gender="male" />
          <ChildComponent name="Mary" age="25" gender="female" />
        </div>
      )
    }
    

The properties from props object can be accessed directly using destructing feature from ES6 (ECMAScript 2015). It is also possible to fallback to default value when the prop value is not specified. The above child component can be simplified like below.

const ChildComponent = ({ name, age, gender = "male" }) => {
  return (
    <div>
      <p>{name}</p>
      <p>{age}</p>
      <p>{gender}</p>
    </div>
  )
}

Note: The default value won't be used if you pass null or 0 value. i.e, default value is only used if the prop value is missed or undefined value has been passed.

See Class
The Props accessed in Class Based Component as below
import React from "react"
import ReactDOM from "react-dom"

class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        <p>{this.props.name}</p>
        <p>{this.props.age}</p>
        <p>{this.props.gender}</p>
      </div>
    )
  }
}

class ParentComponent extends React.Component {
  render() {
    return (
      <div>
        <ChildComponent name="John" age="30" gender="male" />
        <ChildComponent name="Mary" age="25" gender="female" />
      </div>
    )
  }
}
  1. What is the difference between state and props?

    Props are inputs supplied by the parent; local state is owned by the component that declares it. Both can contain values other than plain objects. Treat props and state as read-only snapshots during render.

    ConcernPropsState
    OwnerParent supplies the valueComponent declares the state
    ChangeParent passes another valueOwner calls a setter or dispatches an action
    MutationDo not mutate propsReplace object/array values instead of mutating them
    CommunicationMay include an event callbackOwner can pass the value and a callback to children

    Calling a callback prop can ask an owner to update state. Merely passing props does not itself perform an update.

  2. What is the difference between HTML and React event handling?

    React DOM event props use names such as onClick and take a function value. Pass a handler rather than calling it while rendering. Use preventDefault to cancel a default browser action; returning false from a React handler does not do that.

    export default function ExampleForm() {
      function handleSubmit(event) {
        event.preventDefault()
        console.log("Form submitted")
      }
      return <form onSubmit={handleSubmit}><button type="submit">Submit</button></form>
    }
    

    Native HTML inline handlers contain JavaScript text; native addEventListener also accepts functions. The distinction is the API being used, not a universal rule that HTML always requires parentheses.

  3. 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
  4. What are inline conditional expressions?

    Use an if statement for an early return, a ternary for two alternatives, or a boolean condition with && for an optional element. Avoid a bare numeric count on the left of && because zero can render as text.

    export default function Inbox({ unreadCount }) {
      if (unreadCount === 0) {
        return <p>No unread messages.</p>
      }
      return <p>You have {unreadCount} unread messages.</p>
    }
    

    See Conditional rendering.

  5. 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.
    • Preserves identity when matching sibling elements.
    • 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.
  6. 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.

  7. How Virtual DOM works?

    Think in terms of trigger, render, and commit. React calls components to calculate the desired UI, then commits changes to the host environment. A component render does not necessarily produce a DOM change.

    Reconciliation considers element type, position, and keys when matching the new tree to the previous one. It is a heuristic process, not a promise of a mathematically minimal edit sequence.

    The browser performs layout and painting after relevant DOM work. Using a virtual representation does not guarantee better performance than every direct-DOM implementation. See Render and commit.

  8. What is the difference between Shadow DOM and Virtual DOM?

    The Shadow DOM is a browser technology for DOM and style encapsulation in web components; it does not create a separate JavaScript variable scope. 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
  9. What is React Fiber?

    Fiber is React's internal reconciliation architecture, introduced with React 16. It represents units of rendering work and supports scheduling features used by modern React. It is not a new public API that an application should manipulate directly.

    For application behavior, explain public concepts such as rendering, committing, transitions, and Suspense rather than depending on a particular internal field or scheduling implementation.

  10. What is the main goal of React Fiber?

    Fiber made it possible to organize and schedule rendering work more flexibly than the older stack reconciler. Modern concurrent rendering can interrupt or abandon some rendering work before committing a result.

    This does not make JavaScript computations run on multiple CPU threads. A long synchronous function can still block the main thread. Use the public transition APIs for non-urgent React updates and a worker or other suitable architecture for CPU work that must leave the main thread.

  11. What are controlled components?

    A controlled input receives its current value from React state and reports changes through an event handler. React keeps the DOM input synchronized with that value.

    import { useState } from "react"
    
    export default function NameField() {
      const [name, setName] = useState("")
      return (
        <label>
          Name
          <input value={name} onChange={(event) => setName(event.target.value)} />
        </label>
      )
    }
    

    Initialize a controlled text value as a string. Do not switch the same input between controlled and uncontrolled behavior during its lifetime.

  12. 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.
    • Can avoid state-driven updates for each keystroke; measure the actual form before drawing a performance conclusion.

    Choose controlled inputs when React needs the value during editing; uncontrolled inputs can be suitable when reading the value on submission is sufficient. 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>
    );
  }
}
  1. 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. The classic JSX transform uses createElement; the modern automatic transform can use the JSX runtime. Both create React element descriptions. 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>
    
  2. 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.

  3. What are Higher-Order Components?

    A higher-order component is a function that accepts a component and returns another component. It can provide presentation or shared behavior without changing the original component. A HOC is not automatically a PureComponent or a performance optimization.

    export function withLoading(WrappedComponent) {
      return function LoadingBoundary({ isLoading, ...componentProps }) {
        if (isLoading) {
          return <p role="status">Loading...</p>
        }
        return <WrappedComponent {...componentProps} />
      }
    }
    

    This is a presentation pattern. An authentication wrapper that only checks whether localStorage contains a token cannot establish authorization; protected data and actions need enforcement at the authoritative service. Custom hooks and composition may be simpler for new shared logic.

  4. What is children prop?

    The children prop receives nested content passed between a component's tags. It can represent renderable values such as text, elements, and arrays. A function child must be invoked by a component designed for that render-prop contract; rendering the function directly is not ordinary renderable content.

    export function Panel({ children }) {
      return <section>{children}</section>
    }
    
    export default function Greeting() {
      return <Panel><p>Hello</p><p>World</p></Panel>
    }
    

    The legacy React.createClass API is not part of modern React. Prefer function components or a supported class declaration.

  5. Does the lazy function support named exports?

    The loader passed to lazy must resolve to an object whose default property is a component. A module can re-export a named component as its default, or the loader can map the named export to that shape.

    import { lazy, Suspense } from "react"
    
    const HelpPanel = lazy(() =>
      import("./HelpPanel.jsx").then((module) => ({ default: module.HelpPanel }))
    )
    
    export default function HelpPage() {
      return <Suspense fallback={<p>Loading...</p>}><HelpPanel /></Suspense>
    }
    

    This excerpt requires HelpPanel.jsx to export a named HelpPanel component. Declare lazy at module scope and verify the bundler's output instead of promising a particular tree-shaking result. See lazy.

  6. Why React uses className over class attribute?

    For built-in React DOM elements, use className to set the HTML class attribute. It follows React DOM's property naming convention.

    export default function Notice() {
      return <div className="notice">Saved</div>
    }
    

    The explanation is not that class is forbidden as an object property. Modern JavaScript permits an object such as { class: "notice" }. JSX syntax, JavaScript property syntax, and React DOM's prop API are separate concerns.

  7. 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.

    import { Fragment } from "react"
    
    function Story({ title, description, date }) {
      return (
        <Fragment>
          <h2>{title}</h2>
          <p>{description}</p>
          <p>{date}</p>
        </Fragment>
      )
    }
    

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

    import { Fragment } from "react"
    
    function StoryBook({ stories }) {
      return stories.map((story) => (
        <Fragment key={story.id}>
          <h2>{story.title}</h2>
          <p>{story.description}</p>
          <p>{story.date}</p>
        </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>
          <p>{description}</p>
          <p>{date}</p>
        </>
      )
    }
    
  8. Why fragments are better than container divs?

    A Fragment groups children without adding a wrapper DOM node. This helps when markup or layout requires direct children, such as table rows or items in a flex/grid container. It also keeps the inspected DOM simpler.

    It is not universally better than a div: use a real element when you need its semantics, styling, or layout box. Do not claim a meaningful performance gain without measuring the affected page.

  9. What are portals in React?

    A portal renders children into another DOM container while keeping them in the same React tree. Context and React event propagation follow that React tree. Portals can help escape an overflow or stacking context, but a modal also needs focus management and appropriate semantics.

    This client-side component expects an existing element with id modal-root:

    import { createPortal } from "react-dom"
    
    export default function ModalContent({ children }) {
      const container = document.getElementById("modal-root")
      if (!container) {
        return null
      }
      return createPortal(<div>{children}</div>, container)
    }
    

    This is a portal example, not a complete accessible modal implementation. See createPortal.

  10. What are stateless components?

    A stateless component does not own state relevant to its behavior. It can receive props and compose other components. A function component can be either stateless or stateful because Hooks provide state.

    Choose a function component for new code unless a specific supported class API or existing integration calls for a class. Function syntax alone does not establish that a component renders faster.

  11. 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"
    
    function App() {
      const [count, setCount] = useState(0)
    
      const 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() {
    this.setState({ count: this.state.count + 1 })
  }

  render() {
    return (
      <>
        <button onClick={() => this.handleIncrement()}>Increment</button>
        <span>Count: {this.state.count}</span>
      </>
    )
  }
}
  1. How to apply validation on props in React?

    For current React code, use TypeScript or another suitable static checker for component prop types. React 19 removed React's propTypes checks; an old propTypes assignment is not current runtime validation. See the React 19 upgrade guide.

    interface UserProps {
      name: string
      age: number
    }
    
    export default function User({ name, age }: UserProps) {
      return <p>{name}, age {age}</p>
    }
    

    Static types do not validate untrusted JSON at runtime. Check external input at the application's data boundary using a parser or validator appropriate to that contract.

  2. What are the advantages of React?

    React provides component composition, declarative rendering, and reusable stateful logic through Hooks. It can render through different host environments, and frameworks can add routing and server rendering.

    Those capabilities do not automatically make an application fast, accessible, secure, or easy to test. Judge those properties from the implementation and appropriate measurements.

  3. 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.
  4. What are the recommended ways for static type checking?

    TypeScript provides static checking for a React application and integrates with editor tooling. Flow is another static type system, with a different ecosystem and configuration. Choose the tool the project actually supports.

    PropTypes historically performed development-time runtime checks; it was never a static type checker. Current React 19 no longer runs those propTypes checks. Runtime validation of network responses remains a separate requirement from either static type system.

  5. What is the use of react-dom package?

    The react-dom package provides browser-specific integration. Modern application roots use createRoot or hydrateRoot from react-dom/client; portals use createPortal from react-dom. A root can be removed with root.unmount().

    ReactDOM.render, hydrate, unmountComponentAtNode, and findDOMNode are removed in React 19. Do not copy them into a new application. See the client APIs and upgrade guide.

  6. What is ReactDOMServer?

    react-dom/server exposes server-rendering APIs. For a small synchronous example, renderToString returns an HTML string; it does not stream or wait for suspended data. Frameworks often manage the server and client rendering path for you.

    The following is a complete Node ESM example after installing matching react and react-dom packages:

    // render-example.mjs
    import { createElement } from "react"
    import { renderToString } from "react-dom/server"
    
    const greeting = createElement("h1", null, "Hello")
    const markup = renderToString(greeting)
    console.log(markup)
    

    Run node render-example.mjs. It prints an h1 element as markup; it does not start an HTTP server or make the markup interactive. See renderToString.

  7. 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()} />;
    }
    
  8. How to use styles in React?

    React's style prop accepts an object with property names such as backgroundColor. A CSS class is often easier to maintain for reusable styling. The style prop is not a general XSS-prevention guarantee; review untrusted values and other injection surfaces separately.

    const NOTICE_STYLE = { color: "blue", backgroundColor: "white" }
    
    export default function Notice() {
      return <p style={NOTICE_STYLE}>Saved</p>
    }
    
  9. How events are different in React?

    Handling events in React elements has some syntactic differences:

    1. React event handlers are named using camelCase, rather than lowercase.
    2. With JSX you pass a function as the event handler, rather than a string.
  10. What is the impact of indexes as keys?

    Keys should be stable, predictable, and unique so that React can keep track of elements.

    In the below code snippet each element's key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do and creates confusing bugs in the application.

    {
      todos.map((todo, index) => <Todo {...todo} key={index} />);
    }
    

    If you use element data for unique key, assuming todo.id is unique to this list and stable, React can associate the row with the same identity across a reorder; this does not guarantee that its render function is skipped.

    {
      todos.map((todo) => <Todo {...todo} key={todo.id} />);
    }
    

    Note: If you don't specify key prop at all, React will use index as a key's value while iterating over an array of data.

  11. How do you conditionally render components?

    In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

    const MyComponent = ({ name, address }) => (
      <div>
        <h2>{name}</h2>
        {address && <p>{address}</p>}
      </div>
    );
    

    If you need an if-else condition then use ternary operator.

    const MyComponent = ({ name, address }) => (
      <div>
        <h2>{name}</h2>
        {address ? <p>{address}</p> : <p>{"Address is not available"}</p>}
      </div>
    );
    
  12. Why we need to be careful when spreading props on DOM elements?

    A wrapper can accidentally forward application-only props to a built-in DOM element. Consume those props explicitly and pass only the DOM attributes the wrapper intends to support. Destructuring one private prop does not prove every remaining prop is valid.

    export default function Notice({ isVisible, className, children }) {
      if (!isVisible) {
        return null
      }
      return <div className={className}>{children}</div>
    }
    
  13. How do you memoize a component?

    Use React memo when profiling shows that skipping parent-driven renders with unchanged props is useful. It is optional and must not be required for correctness. State and context updates can still render a memoized component.

    import { memo } from "react"
    
    export const Greeting = memo(function Greeting({ name }) {
      return <p>Hello, {name}</p>
    })
    

    A compiler-enabled application may receive automatic memoization. Confirm the project's actual compiler configuration rather than assuming it is enabled.

  14. How you implement Server Side Rendering or SSR?

    Generate HTML with a suitable server-rendering API or framework, then hydrate it on the client with the matching tree. Sending HTML alone does not attach event handlers.

    In a client entry point with an existing root element containing the server-rendered App markup:

    import { hydrateRoot } from "react-dom/client"
    import App from "./App.jsx"
    
    const rootElement = document.getElementById("root")
    if (!rootElement) {
      throw new Error("Missing root element")
    }
    hydrateRoot(rootElement, <App />)
    

    The server and first client render must agree. Review hydrateRoot for mismatches and error handling. This excerpt assumes the server pipeline and App module already exist.

  15. How to enable production mode in React?

    Use the production build command documented by the application's framework or build tool. In a Vite project this is normally the build script that runs vite build. Serve the resulting application with an appropriate deployment setup.

    Development checks and production optimization are build-tool concerns; manually copying an old Webpack DefinePlugin or minifier recipe is not a universal setup. A successful production build does not prove every runtime flow works.

  16. What is a switching component?

    A switching component chooses an implementation from an explicit mapping or switch statement. Handle unknown values intentionally.

    const PAGES = {
      home: () => <h1>Home</h1>,
      about: () => <h1>About</h1>,
    }
    
    export default function Page({ page }) {
      const SelectedPage = PAGES[page]
      if (!SelectedPage) {
        return <p>Page not found.</p>
      }
      return <SelectedPage />
    }
    

    Use a router when URL matching and navigation are the actual requirement. A propTypes declaration is not current React 19 runtime validation.

  17. What are the Pointer Events supported in React?

    Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don't correlate to having a mouse, like phones with touch surface or pens. We need to remember that these events will only work in browsers that support the Pointer Events specification.

    The following event types are now available in React DOM:

    1. onPointerDown
    2. onPointerMove
    3. onPointerUp
    4. onPointerCancel
    5. onGotPointerCapture
    6. onLostPointerCapture
    7. onPointerEnter
    8. onPointerLeave
    9. onPointerOver
    10. onPointerOut
  18. Why should component names start with capital letter?

    An uppercase JSX name is resolved as a component binding; a lowercase name is treated as a built-in or custom tag name. A lowercase custom-looking tag does not necessarily throw an exception, but it will not call a JavaScript function of the same name as a component.

    function Greeting() {
      return <p>Hello</p>
    }
    
    export default function App() {
      return <Greeting />
    }
    
  19. What is React proptype array with shape?

    The historical PropTypes pattern was arrayOf(shape(...)). React.PropTypes is no longer part of React, and React 19 does not run propTypes checks. For a current typed component, declare the array element type:

    interface TextStyle {
      color: string
      fontSize: number
    }
    
    interface StyleListProps {
      styles: TextStyle[]
    }
    
    export default function StyleList({ styles }: StyleListProps) {
      return <p>{styles.length} styles</p>
    }
    

    Validate external values separately before passing them to the component.

  20. How to conditionally apply class attributes?

    You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.

    <div className="btn-panel {this.props.visible ? 'show' : 'hidden'}">
    

    Instead you need to move curly braces outside (don't forget to include spaces between class names):

    <div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>
    

    Template strings will also work:

    <div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}>
    
  21. What is the difference between React and ReactDOM?

    react contains component, element, and Hook APIs. react-dom integrates React with the browser DOM; react-dom/client exposes root creation and hydration, while react-dom/server exposes server-rendering APIs. Other renderers target other host environments.

    Do not use ReactDOM.render as a current example: React 19 removed it.

  22. Why ReactDOM is separated from React?

    The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at some of the packages, react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

    To build more environments that React can render to, React team planned to split the main React package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native.

  23. How to use React label element?

    Use htmlFor on a React DOM label and match it to the input's id, or nest the input inside the label. This establishes an accessible label association. It is React DOM's prop convention, not a prohibition on using for as a modern JavaScript object property.

    export default function UsernameField() {
      return (
        <>
          <label htmlFor="username">Username</label>
          <input id="username" name="username" />
        </>
      )
    }
    
  24. How to pretty print JSON with React?

    Render JSON.stringify output as text inside a pre element. For a component excerpt:

    const EXAMPLE_USER = { name: "John", age: 42 }
    
    export default function UserPreview() {
      return <pre>{JSON.stringify(EXAMPLE_USER, null, 2)}</pre>
    }
    

    This preserves whitespace. Only display information the viewer is allowed to see; a debug preview can expose private fields. Use the application's existing root instead of adding a legacy React.render call.

  25. How to focus an input element on page load?

    A ref gives access to an input after it mounts. Focus it in an effect when moving focus is intentional; automatic focus can otherwise interrupt a reader or keyboard user.

    import { useEffect, useRef } from "react"
    
    export default function SearchField() {
      const inputRef = useRef(null)
      useEffect(() => {
        inputRef.current?.focus()
      }, [])
      return <label>Search<input ref={inputRef} /></label>
    }
    

    Render this component through the application's normal entry point. Refs can be null before mount and after unmount.

  26. How does React's automatic batching improve performance?

    Batching lets React process multiple queued state updates together. A setter does not synchronously change the current render's variables. Use updater functions when the next value depends on the queued previous value. Separate intentional user events are handled separately.

    import { useState } from "react"
    
    export default function Counter() {
      const [count, setCount] = useState(0)
      function incrementTwice() {
        setCount((previous) => previous + 1)
        setCount((previous) => previous + 1)
      }
      return <button onClick={incrementTwice}>{count}</button>
    }
    

    One click increases the displayed count by two. See Queueing state updates.

  27. What are React Portals, and what problems do they solve?

    Portals let content use a different physical DOM parent while retaining its React-tree relationship. This can help with an overlay clipped by an ancestor's overflow. See the portal example above.

    A portal alone does not implement a dialog's keyboard behavior, initial focus, focus restoration, or accessible name. Test those requirements separately when building a modal.

  28. What is React Strict Mode and what are its benefits?

    StrictMode enables additional development checks. Depending on where it is enabled, React can repeat rendering, effect setup/cleanup, and ref callbacks to expose missing cleanup or impure behavior. These checks are not production behavior and do not prove that all bugs have been found.

    import { StrictMode } from "react"
    import App from "./App.jsx"
    
    export default function Root() {
      return <StrictMode><App /></StrictMode>
    }
    

    Keep effects and ref callbacks correct when setup is followed by cleanup and another setup. See StrictMode.

  29. What is code splitting in a React application?

    Code splitting lets a build tool produce chunks that can be loaded when needed. A dynamic import with lazy and a Suspense fallback is one React pattern; a framework may provide route-based splitting.

    See the lazy-loading example and the lazy reference. Measure the actual initial transfer and the interaction that first loads a chunk rather than assuming more chunks are always faster.

  30. How would one optimize the performance of React contexts to reduce rerenders?

    First measure which consumers render during the interaction. Splitting contexts by concern can avoid broadcasting unrelated changes. Stabilizing an object value can help when its contents have not changed, but it cannot suppress updates that consumers actually need.

    The built-in useContext subscribes to the context value; it does not have a selector argument. A library can provide a separate selector API. Check that library's contract before using it. See useContext.

  31. Explain one-way data flow of React

    In React, one-way data flow means data moves from parent to child components through props.

    • Parent to child: The parent passes data to the child
    • State updates: To change data, the child calls a function passed down by the parent
    function Parent() {
      const [count, setCount] = React.useState(0);
      return <Child count={count} increment={() => setCount(count + 1)} />;
    }
    
    function Child({ count, increment }) {
      return <button onClick={increment}>Count: {count}</button>;
    }
    

    This ensures data flows in one direction, making the app more predictable.

  32. What are some pitfalls of using context in React?

    Consumers update when the nearest provider's value changes under React's comparison. A new object identity can broadcast a change even when its contents appear equivalent. memo does not block a consumed-context update.

    Avoid using context as a universal state container without considering ownership and update frequency. Context can still be appropriate for frequently changing values when its consumers and costs fit the application. Profile before choosing a different store.

  33. What are some React anti-patterns?

    Common defects include mutating state, making side effects during render, missing effect dependencies or cleanup, and using unstable keys for reorderable stateful rows.

    Inline event functions are not automatically an anti-pattern. Add memoization only when it addresses a measured problem. Similarly, small components or context are not inherently wrong; judge whether they clarify responsibilities and preserve correct behavior.

  34. How do you decide between using React state, context, and external state managers?

    Choosing between React state, context, and external state managers depends on your application's complexity. Use React state for local component state, context for global state shared across multiple components, and external managers like Redux or MobX for complex state management requiring advanced features like optimizing re-renders.

    Decision guide:

    • useState/useReducer: For component-local state
    • Context API: For simple global state (theme, user info, language)
    • Redux/Zustand: For complex state with frequent updates, time-travel debugging, middleware needs
  35. Explain what happens when setState is called in React?

    A state setter queues an update. React calculates a later render from queued updates, and the current handler keeps its existing state snapshot. A useState setter replaces that state value; class setState shallowly merges the supplied state object.

    If the next value depends on the previous queued value, use an updater function. Do not mutate an existing object or assume that reading the local variable immediately after a setter yields the next render's value.

  36. Explain prop drilling

    Prop drilling is when you pass data from a parent component to a deeply nested child component through props, even if intermediate components don't use it.

    function Grandparent() {
      const data = 'Hello from Grandparent';
      return <Parent data={data} />;
    }
    
    function Parent({ data }) {
      return <Child data={data} />;
    }
    
    function Child({ data }) {
      return <p>{data}</p>;
    }
    

    In this example, data is passed through multiple components, even though only the Child component uses it. Prop drilling is acceptable for small applications where the component hierarchy is shallow. When global state is needed to be accessed in deeper levels of the app, using context and/or external state managers might be better.

  37. Describe lazy loading in React

    Lazy loading in React is a technique where components are loaded only when they are needed, rather than at the initial page load. This helps reduce the initial load time and improve performance by splitting the code into smaller chunks.

    import React, { Suspense, lazy } from 'react';
    
    const LazyComponent = lazy(() => import('./LazyComponent'));
    
    function App() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyComponent />
        </Suspense>
      );
    }
    

    In this example, LazyComponent is loaded only when it's rendered, and while loading, a fallback UI (Loading...) is displayed.

  38. Discuss synthetic events in React

    React DOM events expose methods such as preventDefault and stopPropagation through a React event object, with nativeEvent for the underlying browser event. Modern React DOM no longer pools these event objects; event pooling is historical advice for React DOM 16 and earlier.

    The browser can still clear currentTarget outside the active handler. Capture a DOM reference or required primitive value before awaiting if later work needs it. Do not infer asynchronous event behavior solely from the absence of pooling.

  39. What is Concurrent Mode in React, and how does it improve rendering performance?

    Modern React uses concurrent rendering capabilities for features such as transitions. Some render work can be interrupted or abandoned before commit. This is not parallel execution of arbitrary application JavaScript on multiple CPU threads.

    There is no separate current “Concurrent Mode” switch to recommend for a new app. Use the framework's supported root and public APIs such as startTransition or useDeferredValue, then measure the interaction.

  40. How would you handle long-running tasks or expensive computations in React applications without blocking the UI?

    A worker can run suitable CPU work away from the main thread. Moving the same long computation into setTimeout only delays it; when the callback runs it still blocks the main thread. requestIdleCallback also runs callbacks on that thread.

    Chunking work can yield between chunks. useMemo can avoid some repeated calculations but cannot make one expensive calculation non-blocking. A transition changes the priority of React updates, not the thread on which an ordinary calculation runs. See the Web Workers guide.

  41. Explain the presentational vs container component pattern in React

    In React, the presentational vs container component pattern distinguishes between components that focus on appearance (presentational components) and those that manage logic and state (container components). Presentational components render HTML and CSS, while container components handle data and behavior. This separation leads to a cleaner and more organized codebase.

    Presentational components:

    • Focus on how things look
    • Receive data via props
    • Rarely have their own state
    • Are reusable and easy to test

    Container components:

    • Focus on how things work
    • Manage state and data fetching
    • Pass data to presentational components
    • Handle business logic
  42. What are render props in React?

    A render prop is a function prop that a component calls to produce part of its UI. It is useful when the caller needs control over presentation.

    export function ValuePresenter({ value, render }) {
      return <section>{render(value)}</section>
    }
    
    export default function Greeting() {
      return <ValuePresenter value="Hello" render={(message) => <p>{message}</p>} />
    }
    

    This demonstrates the pattern without an unrelated network request. Data fetching still needs a defined API, loading/error handling, and stale-request protection.

  43. Explain the composition pattern in React

    The composition pattern in React involves building components by combining smaller, reusable ones instead of using inheritance. This encourages creating complex UIs by passing components as children or props.

    function WelcomeDialog() {
      return (
        <Dialog>
          <h1>Welcome</h1>
          <p>Thank you for visiting our spacecraft!</p>
        </Dialog>
      );
    }
    
    function Dialog(props) {
      return <div className="dialog">{props.children}</div>;
    }
    

    Benefits:

    • More flexible than inheritance
    • Easier to understand and maintain
    • Promotes code reuse
    • Better separation of concerns
  44. How do you handle asynchronous data loading in React applications?

    Prefer a framework loader or a suitable request library when the project provides one. If fetching in an effect, check HTTP status, handle failure visibly, and prevent an obsolete response from updating the current view.

    This component excerpt expects an endpoint returning a JSON array of records with id and title. It does not provide that server:

    import { useEffect, useState } from "react"
    
    export default function RecordList({ url }) {
      const [records, setRecords] = useState([])
      const [status, setStatus] = useState("loading")
    
      useEffect(() => {
        let isCurrent = true
        const controller = new AbortController()
        setStatus("loading")
        setRecords([])
    
        async function loadRecords() {
          try {
            const response = await fetch(url, { signal: controller.signal })
            if (!response.ok) {
              throw new Error("Request failed: " + response.status)
            }
            const receivedRecords = await response.json()
            if (!Array.isArray(receivedRecords)) {
              throw new Error("Expected a record array")
            }
            if (isCurrent) {
              setRecords(receivedRecords)
              setStatus("ready")
            }
          } catch (error) {
            if (!isCurrent) {
              return
            }
            console.error("Record list request failed", error)
            setStatus("failed")
          }
        }
        loadRecords()
        return () => {
          isCurrent = false
          controller.abort()
        }
      }, [url])
    
      if (status === "loading") {
        return <p role="status">Loading...</p>
      }
      if (status === "failed") {
        return <p role="alert">Unable to load records.</p>
      }
      if (records.length === 0) {
        return <p>No records.</p>
      }
      return <ul>{records.map((record) => <li key={record.id}>{record.title}</li>)}</ul>
    }
    

    The array check is a minimal illustration; validate each record's fields at the real API boundary. Cleanup invalidates the previous request and asks the browser to abort it. See useEffect data fetching and the complete SWR/Vite workflow.

  45. What are some common pitfalls when doing data fetching in React?

    Check loading, failure, empty, and populated states separately. fetch can fulfill for an HTTP error response, so inspect response.ok before accepting JSON. An old request must not replace newer content after an input changes.

    Clean up subscriptions, invalidate obsolete requests, and define retry behavior. Do not label every late response a memory leak or silence an error into an empty list. Validate untrusted response fields before rendering them.


📚 Related React Interview Questions

Continue your React JS interview questions preparation with these related topics:

React Hooks Interview Questions

Comprehensive React Hooks interview questions covering useState, useEffect, useCallback, useMemo, useReducer, and custom...

React State Management Interview Questions

Master React State Management interview questions covering useState, Context API, Redux, and state optimization. Essenti...

React Rendering & Performance Interview Questions

Comprehensive React Rendering & Performance interview questions covering Virtual DOM, memoization, code splitting, and o...

📖

Complete React Interview Guide

Master all aspects of React development

This article is part of our comprehensive React JS interview questions series covering all aspects of React development. Explore all topics:

Arrays & Lists
Forms & Events
React Hooks
Internationalization
Libraries & Integration
Miscellaneous
React Redux
Rendering & Performance
React Router
State Management
React Testing