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

React Miscellaneous 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 Redux Interview Questions & Answers 2026

Next Article

React Libraries & Integration Interview Questions 2026
← 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 & Answers

📖 Introduction

Review 164 React interview questions that mix current APIs, application decisions, and historical library behavior. The current guidance targets React 19; version-specific questions identify the relevant older or newer API instead of treating all snippets as interchangeable.

For a focused path, start with Hooks rules, state updates, refs, or server components. Follow the linked core and Hooks guides when a topic needs a longer example.

Most snippets are component or API excerpts that need an application's normal entry point and the declared dependencies. They are not all complete applications, and historical questions are not installation recommendations.

Miscellaneous

  1. What are the main features of Reselect library?

    Reselect builds memoized selectors for derived values and lets selectors compose. Recalculation depends on the configured memoization and the identities of arguments and input-selector results. Mutating an input in place can make a selector return stale output. See Reselect's documentation.

  2. Give an example of Reselect usage?

    For an illustrative calculation, store integer cents and derive a subtotal. This avoids presenting floating-point decimal output as an exact financial total. Tax rounding still needs the application's actual rule.

    import { createSelector } from "reselect"
    
    const selectLines = (state) => state.shop.lines
    export const selectSubtotalCents = createSelector(
      [selectLines],
      (lines) => lines.reduce((subtotal, line) => subtotal + line.priceCents, 0)
    )
    
    const exampleState = { shop: { lines: [{ priceCents: 120 }, { priceCents: 95 }] } }
    console.log(selectSubtotalCents(exampleState)) // 215
    

    This needs the reselect package and an immutable state update strategy. It does not implement tax calculation or payment approval.

  3. Can Redux only be used with React?

    Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.

  4. Do you need to have a particular build tool to use Redux?

    Redux is independent of a particular UI build tool. The package format and supported runtime depend on the installed version. Redux 5 changed packaging and removed UMD builds, so an old script-tag recipe is not a current universal installation method. See the Redux migration guide.

  5. How Redux Form initialValues get updated from state?

    For a legacy Redux Form application, enableReinitialize controls whether changes to initialValues reinitialize the form. Review keepDirtyOnReinitialize and the intended treatment of unsaved edits before enabling it; reinitialization can replace entered values. The Redux Form 8.3 reference is version-specific, not a recommendation to add it to a new application.

  6. How React PropTypes allow different types for one prop?

    Historically PropTypes.oneOfType described a union. React 19 no longer runs propTypes checks, so use an appropriate static type such as string | number for current typed components and validate untrusted input separately. See the current prop-validation answer.

  7. Can I import an SVG file as react component?

    SVG import behavior belongs to the build tool. The ReactComponent named import was a Create React App convention, not a general React feature. In a plain Vite project, importing an SVG normally gives an asset URL:

    import logoUrl from "./logo.svg"
    
    export default function Logo() {
      return <img src={logoUrl} alt="Project logo" />
    }
    

    An SVG-to-component plugin needs its own documented configuration and import syntax. Review SVG contents before treating an untrusted file as executable markup.

  8. What is render hijacking in react?

    The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enable hijacking, but by using HOC you make your component behave differently.

  9. How to pass numbers to React component?

    We can pass numbers as props to React component using curly braces {} where as strings in double quotes "" or single quotes ''

    import React from "react"
    
    const ChildComponent = ({ name, age }) => {
      return (
        <>
          My Name is {name} and Age is {age}
        </>
      )
    }
    
    const ParentComponent = () => {
      return (
        <>
          <ChildComponent name="Chetan" age={30} />
        </>
      )
    }
    
    export default ParentComponent
    
  10. Do I need to keep all my state into Redux? Should I ever use react internal state?

    It is up to the developer's decision, i.e., it is developer's job to determine what kinds of state make up your application, and where each piece of state should live. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.

    Below are the rules of thumb to determine what kind of data should be put into Redux

    1. Do other parts of the application care about this data?
    2. Do you need to be able to create further derived data based on this original data?
    3. Is the same data being used to drive multiple components?
    4. Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
    5. Do you want to cache the data (i.e, use what's in state if it's already there instead of re-requesting it)?
  11. What is the purpose of registerServiceWorker in React?

    registerServiceWorker was a helper name in older application templates. React itself does not automatically create or register a service worker. Offline behavior requires an intentional registration, caching strategy, secure context, and update lifecycle.

    Follow the application's current PWA tooling and the service-worker API documentation. Test updates and stale-cache recovery; a service worker is not proof that every page or API works offline.

  12. What is React memo function?

    memo can skip a parent-driven render when props compare equal. Local state and consumed context can still trigger a render, and memoization must not be needed for correctness. See the memoization example.

  13. What is React lazy function?

    lazy loads a component from a promise resolving to a module with a default component export. Declare it outside the component and provide a Suspense fallback. Modern server rendering can support Suspense; the old claim that lazy is categorically unavailable with SSR is outdated. See lazy and the framework's rendering support.

  14. How to prevent unnecessary updates using setState?

    For a class setState updater, returning null can skip an unnecessary state update. Return the correctly named field when a change is needed:

    // Method excerpt inside a class component with an address state field.
    updateAddress = (user) => {
      this.setState((previous) => {
        if (previous.address === user.address) {
          return null
        }
        return { address: user.address }
      })
    }
    

    A useState setter is a different API: setting an Object.is-equal value can let React skip work. Do not mutate the existing state object.

  15. What are hooks?

    Hooks is a special JavaScript function that allows you use state and other React features without writing a class. This pattern has been introduced as a new feature in React 16.8 and helped to isolate the stateful logic from the components.

    Let's see an example of useState hook:

    import { useState } from "react"
    
    function Example() {
      // Declare a new state variable, which we'll call "count"
      const [count, setCount] = useState(0)
    
      return (
        <>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </>
      )
    }
    

    Note: Hooks can be used inside an existing function component without rewriting the component.

  16. What rules need to be followed for hooks?

    Call ordinary Hooks at the top level of a function component or custom Hook, before early returns. Do not call useState or useEffect from a conditional branch, a class, or an ordinary helper. The current use API has a documented exception for conditions and loops; it still has its own restrictions.

    See the Rules of Hooks and the focused Hooks questions. A custom Hook's use-prefixed name identifies its contract; renaming an arbitrary function does not make every use valid.

  17. How to ensure hooks followed the rules in your project?

    Use the current eslint-plugin-react-hooks configuration for the ESLint version and framework in the project. Enable the relevant recommended rules, including rules-of-hooks and exhaustive-deps. A legacy .eslintrc fragment is not interchangeable with a modern flat configuration.

    The plugin is a lint tool, not part of React's runtime Hook API or something limited to Create React App. Lint results complement tests and review; do not silence a dependency warning merely to force an effect to run once.

  18. What are the differences between Flux and Redux?

    Flux is an architectural pattern; Redux is a library with a defined store, dispatch, reducer, and subscription model. Redux does have dispatch, even though it does not use a separate Flux dispatcher object. Avoid claiming that every Flux implementation is mutable or that all React Redux applications use connect; modern React bindings also provide Hooks.

  19. What are the benefits of React Router V4?

    React Router v4 introduced a component-oriented routing model, but this is a historical-version question. Its APIs should not be copied as the setup for a current router. For current route matching, navigation, and lazy-loading patterns, use the version-scoped React Router questions and the installed router's documentation.

  20. Can you describe about componentDidCatch lifecycle method signature?

    The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters,

    1. error: - The error object which was thrown
    2. info: - An object with a componentStack key contains the information about which component threw the error.

    The method structure would be as follows

    componentDidCatch(error, info)
    
  21. In which scenarios do error boundaries not catch errors?

    A class error boundary does not generally catch event-handler errors, arbitrary later timer callbacks, or an error in the boundary itself. Framework server-error handling and server Suspense behavior are separate mechanisms. Check the Component error-boundary reference rather than treating a boundary as a universal try/catch.

  22. What is the proper placement for error boundaries?

    The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches,

    1. You can wrap top-level route components to display a generic error message for the entire application.
    2. You can also wrap individual components in an error boundary to protect them from crashing the rest of the application.
  23. What is the benefit of component stack trace from error boundary?

    componentDidCatch receives information including a componentStack, which helps identify the React component path involved in a failure. Source filenames and line details depend on the build and available source information. Keep private props and sensitive payloads out of reports. See the Component reference.

  24. What are default props?

    For a current function component, use a JavaScript parameter default. It applies when the prop is missing or undefined, while null remains null. React 19 removed defaultProps support for function components; supported class defaultProps is a separate case.

    export default function MyButton({ color = "red" }) {
      return <button type="button" data-color={color}>Continue</button>
    }
    

    This example stores a color label as an attribute; it does not recursively render MyButton inside itself.

  25. What is the purpose of displayName class property?

    The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component.

    For example, To ease debugging, choose a display name that communicates that it’s the result of a withSubscription HOC.

    function withSubscription(WrappedComponent) {
      class WithSubscription extends React.Component {
        /* ... */
      }
      WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`
      return WithSubscription
    }
    function getDisplayName(WrappedComponent) {
      return WrappedComponent.displayName || WrappedComponent.name || "Component"
    }
    
  26. What is the browser support for react applications?

    Browser support depends on the React version, build output, framework, and browser APIs used by the application. Do not apply an old IE9/polyfill claim to current React. Test the supported browser matrix and the production build; syntax transforms do not polyfill every runtime API.

  27. What is code-splitting?

    Code splitting creates separately loadable modules. A dynamic import returns a promise that needs a visible failure path.

    // message.js
    export const message = "Hello"
    
    // App.jsx
    import { useState } from "react"
    
    export default function App() {
      const [message, setMessage] = useState("Not loaded")
      async function handleLoad() {
        try {
          const loadedModule = await import("./message.js")
          setMessage(loadedModule.message)
        } catch (error) {
          console.error("Message module failed to load", error)
          setMessage("Unable to load the module.")
        }
      }
      return <><button onClick={handleLoad}>Load</button><p>{message}</p></>
    }
    

    The bundler determines the actual chunks. Inspect its output instead of assuming every dependency becomes a separate file.

  28. What are Keyed Fragments?

    Use the explicit Fragment component when a group in a list needs a key. The short <> syntax cannot take a key.

    import { Fragment } from "react"
    
    export default function Glossary({ entries }) {
      return <dl>{entries.map((entry) => (
        <Fragment key={entry.id}>
          <dt>{entry.term}</dt><dd>{entry.description}</dd>
        </Fragment>
      ))}</dl>
    }
    

    Other Fragment capabilities can depend on the React release channel; consult the installed version's reference rather than assuming event props work.

  29. Does React support all HTML attributes?

    React DOM supports documented HTML/SVG props, plus data-* and aria-* attributes. Naming and value requirements still matter: use className and htmlFor, and do not forward arbitrary application objects as DOM attributes. “Supports every attribute” is too broad to explain special boolean, URL, and event props. See the DOM component reference.

  30. When component props defaults to true?

    A JSX prop without an explicit value supplies boolean true. For a custom component, <Panel isExpanded /> is equivalent to <Panel isExpanded={true} />. Use a prop whose contract accepts a boolean. Native autoComplete is a string-valued setting, so it is a poor example of a shorthand boolean.

  31. What is NextJS and major features of it?

    Next.js is a React framework with routing, rendering, data-loading, and deployment conventions. Its App Router and Pages Router have different APIs. Do not describe every Next.js page as server-rendered by default or assume Webpack is the only current development build path. See the Next.js documentation for the selected version.

  32. How do you pass an event handler to a component?

    Pass a function prop and attach it to the child's event. This component is only a click-state demonstration; it does not download a file.

    import { useState } from "react"
    
    function ActionButton({ onClick }) {
      return <button type="button" onClick={onClick}>Continue</button>
    }
    
    export default function ClickDemo() {
      const [isClicked, setIsClicked] = useState(false)
      return <><ActionButton onClick={() => setIsClicked(true)} /><p>{isClicked ? "Clicked" : "Ready"}</p></>
    }
    
  33. How to prevent a function from being called multiple times?

    Debouncing waits for a pause; throttling limits frequency. They can reduce repeated UI work but do not establish that a consequential server operation happens only once. For a submission, handle the pending state and use the backend's duplicate-prevention or idempotency contract. Clean up scheduled callbacks when their owner changes or unmounts.

  34. How JSX prevents Injection Attacks?

    React escapes ordinary text children, so a string containing markup is displayed as text. That protection does not make arbitrary HTML, URLs, or third-party DOM operations safe. dangerouslySetInnerHTML deliberately bypasses ordinary text escaping and needs trusted or appropriately sanitized markup. Review injection boundaries separately.

  35. How do you update rendered elements?

    Update component state and let React render the next UI. A timer needs cleanup:

    import { useEffect, useState } from "react"
    
    export default function Clock() {
      const [time, setTime] = useState(() => new Date())
      useEffect(() => {
        const intervalId = setInterval(() => setTime(new Date()), 1000)
        return () => clearInterval(intervalId)
      }, [])
      return <p>{time.toLocaleTimeString()}</p>
    }
    

    Use the application's normal root. ReactDOM.render is removed in React 19. A server-rendered clock needs an agreed first-render value to avoid a hydration mismatch.

  36. How do you say that props are readonly?

    When you declare a component as a function or a class, it must never modify its own props.

    Let us take a below capital function,

    function capital(amount, interest) {
      return amount + interest
    }
    

    The above function is called “pure” because it does not attempt to change their inputs, and always return the same result for the same inputs. Hence, React has a single rule saying "All React components must act like pure functions with respect to their props."

  37. What are the conditions to safely use the index as a key?

    There are three conditions to make sure, it is safe use the index as a key.

  38. The list and items are static– they are not computed and do not change

  39. The items in the list have no ids

  40. The list is never reordered or filtered.

  41. Should keys be globally unique?

    The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays.

    For example, the below Book component uses two arrays with different arrays,

    function Book(props) {
      const index = (
        <ul>
          {props.pages.map((page) => (
            <li key={page.id}>{page.title}</li>
          ))}
        </ul>
      )
      const content = props.pages.map((page) => (
        <div key={page.id}>
          <h3>{page.title}</h3>
          <p>{page.content}</p>
          <p>{page.pageNumber}</p>
        </div>
      ))
      return (
        <div>
          {index}
          <hr />
          {content}
        </div>
      )
    }
    
  42. What is the popular choice for form handling?

    Formik is one form-management option for values, validation, touched state, and submission. Compare it with the project's existing form approach and actual requirements. Its existence does not establish that it is the universally most popular or fastest choice.

  43. What are the advantages of formik over redux form library?

    Formik generally keeps form state outside a Redux store, while Redux Form integrates it with Redux. Compare update frequency, validation, subscriptions, maintenance, and migration cost in the actual form. Old gzip-size numbers without versions and build conditions are not a reliable performance comparison. A migration also needs to preserve dirty values, errors, and submission behavior.

  44. Why are you not required to use inheritance?

    In React, it is recommended to use composition over inheritance to reuse code between components. Both Props and composition give you all the flexibility you need to customize a component’s look and behavior explicitly and safely. Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript module. Later components import it and use that function, object, or class, without extending it.

  45. Can I use web components in react application?

    React can render registered custom elements, and the exact property/event handling depends on the React version. Use the custom element's documented attributes, properties, events, and registration import. A vendor-specific example also needs the package and API version it assumes. Do not treat a JSX tag alone as installation or a complete integration.

  46. What is dynamic import?

    A dynamic import loads a module asynchronously and returns a promise. It can become a code-splitting boundary under a compatible bundler. Handle a rejected load and verify the actual output. See the complete two-file example rather than relying on an undefined module or an unhandled promise.

  47. What are loadable components?

    Loadable Components is a separate library for loading components and coordinating with a bundler or server setup. Whether it fits depends on the application's framework and existing build integration. Modern React supports Suspense in supported server-rendering paths; do not assume every SSR application needs this library. Code splitting alone does not guarantee a faster page.

  48. What is suspense component?

    Suspense displays a fallback when a supported child suspends, such as a lazy-loaded component or data supplied through a compatible framework/resource. A fetch started in an ordinary effect does not automatically activate Suspense. Do not create a fresh uncached promise during each render and expect a reliable loading workflow.

    Use the lazy-loading example or the framework's documented data integration. A rejected operation needs the appropriate error handling as well as a loading fallback.

  49. What is route based code splitting?

    Routes can form useful loading boundaries, but navigation can leave layouts and other controls interactive. Use the installed router's lazy-loading integration and choose fallback placement deliberately. React Router v5's Switch and component props are historical; current APIs differ. See the router guide.

  50. What is the purpose of default value in context?

    The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.

    Below code snippet provides default theme value as Luna.

    const MyContext = React.createContext(defaultValue)
    
  51. What is diffing algorithm?

    React reconciliation uses heuristics to associate elements between renders, including their type, position, and keys. Do not present it as an algorithm guaranteed to find the mathematically smallest DOM edit sequence. Explain the observable identity and state-preservation behavior before discussing internal complexity.

  52. What are the rules covered by diffing algorithm?

    Different element types at the same position can replace a subtree and reset its state. Matching type, position, and keys can preserve identity. A DOM node may be reused while its properties change.

    Do not describe every update through unsafe legacy class lifecycles. For current behavior and examples, see preserving and resetting state.

  53. When do you need to use refs?

    There are few use cases to go for refs,

  54. Managing focus, text selection, or media playback.

  55. Triggering imperative animations.

  56. Integrating with third-party DOM libraries.

  57. Must prop be named as render for render props?

    The prop may have any agreed name, including children. Its contract is that the component calls the function to obtain renderable content. Document or statically type that contract; React 19 propTypes checks cannot enforce it. See the render-prop example.

  58. What are the problems of using render props with pure components?

    A newly created function has a new identity, so it can defeat a shallow-prop memoization comparison. That is relevant only when skipping that render matters. A new callback is not automatically a defect. Measure the interaction and stabilize the function only when the comparison or effect contract needs it.

  59. What is windowing technique?

    Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created. If your application renders long lists of data then this technique is recommended. Both react-window and react-virtualized are popular windowing libraries which provides several reusable components for displaying lists, grids, and tabular data.

  60. How do you print falsy values in JSX?

    React renders neither boolean true nor false as visible text, and null/undefined also render no content. Zero is different: it can appear as text. To display a debug representation deliberately, render String(value), while taking care not to expose private information.

  61. What is the typical use case of portals?

    Portals are useful for overlays that need another DOM parent, such as content clipped by an ancestor. They preserve the React-tree relationship. They do not guarantee topmost stacking, correct positioning, or accessible dialog behavior. Test focus and keyboard interaction separately.

  62. How do you set default value for uncontrolled component?

    Use defaultValue for an uncontrolled text input's initial value and defaultChecked for an uncontrolled checkbox/radio. Later prop changes do not turn the initial value into a controlled update.

    export default function NameForm() {
      return <form><label>Name<input name="name" defaultValue="John" /></label></form>
    }
    

    Use a controlled value and an onChange handler when React must own the editing state.

  63. What is your favorite React stack?

    A useful interview answer explains the task and tradeoffs. Choose routing, forms, state, requests, styling, and build tooling from the project's needs and maintenance constraints. An old boilerplate repository is not evidence of the current most popular stack or a reason to add Redux, sagas, and every other dependency to a small application.

  64. What is the difference between Real DOM and Virtual DOM?

    The browser DOM is the actual document API. React's element representation describes desired UI and reconciliation decides what to commit. Both computation and DOM work have costs; a virtual representation is not automatically faster and does use memory. Measure the complete interaction rather than comparing them with a blanket “slow versus fast” table.

  65. How to add Bootstrap to a react application?

    Bootstrap can be added to your React app in a three possible ways,

  66. Using the Bootstrap CDN: This is the easiest way to add bootstrap. Add both bootstrap CSS and JS resources in a head tag.

  67. Bootstrap as Dependency: If you are using a build tool or a module bundler such as Webpack, then this is the preferred option for adding Bootstrap to your React application

    npm install bootstrap
    
  68. React Bootstrap Package: In this case, you can add Bootstrap to our React app is by using a package that has rebuilt Bootstrap components to work particularly as React components. Below packages are popular in this category,

    1. react-bootstrap
    2. reactstrap
  69. Can you list down top websites or applications using react as front end framework?

    There is no fixed, independently established “top ten” in this guide. A company's historic use of React does not prove that its entire current site uses React. For an interview, discuss a verifiable project or the component architecture itself and cite a current engineering source if naming a company.

  70. Is it recommended to use CSS In JS technique in React?

    React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate *.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries. But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option.

  71. Do I need to rewrite all my class components with hooks?

    Existing class components can coexist with function components. Do not rewrite a working class solely to use Hooks. Prefer function components for new code, and plan a migration when a concrete maintenance or integration need justifies it. Current support is documented by the Component reference; future roadmap promises require a current source.

  72. What is useEffect hook? How to fetch data with React Hooks?

    useEffect synchronizes a component with an external system. It is not a one-to-one replacement for three class lifecycles, and an empty dependency array does not guarantee exactly one setup in every development or mounting scenario.

    For network loading, check status and data shape, show distinct loading/error/empty states, and invalidate obsolete responses. See the complete effect-fetching example and the SWR/Vite workflow.

  73. Is Hooks cover all use cases for classes?

    Most new component logic can use Hooks. Some class APIs, including a class error boundary's lifecycle contract, have no direct built-in function-component equivalent. A library can expose a component abstraction around such behavior. Do not promise that a missing equivalent will be added soon without a current roadmap source.

  74. What is the stable release for hooks support?

    Hooks first shipped as stable React functionality in React 16.8. That is a historical release milestone, not a recommended version for a new project. Use current matching React and renderer versions and check the API required by the example.

  75. Why do we use array destructuring (square brackets notation) in useState?

    When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.

    For example, the array index access would look as follows:

    var userStateVariable = useState("userProfile") // Returns an array pair
    var user = userStateVariable[0] // Access first item
    var setUser = userStateVariable[1] // Access second item
    

    Whereas with array destructuring the variables can be accessed as follows:

    const [user, setUser] = useState("userProfile")
    
  76. What are the sources used for introducing hooks?

    The archived Hooks introduction explains motivations such as reusing stateful logic, separating concerns, and avoiding difficulties with classes. Treat it as historical context; use current react.dev documentation for today's API rules rather than attributing precise design origins to an unsourced list.

  77. How do you access imperative API of web components?

    Web Components often expose an imperative API to implement its functions. You will need to use a ref to interact with the DOM node directly if you want to access imperative API of a web component. But if you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.

  78. What is formik?

    Formik manages form values, validation, and submission state. See the form-library discussion above and the Formik documentation. It is a choice to evaluate, not a prerequisite for React forms.

  79. What are typical middleware choices for handling asynchronous calls in Redux?

    Use Redux's current side-effect guidance for the task. Redux Toolkit includes thunk support, and RTK Query handles many server-data caching workflows. Listener middleware can suit reactions to actions or state changes. Sagas and other libraries have their own tradeoffs; do not add one solely because an old list calls it popular.

  80. Do browsers understand JSX code?

    Browsers do not execute JSX directly. A compiler or build transform converts it to JavaScript. Babel is one option; current toolchains can use other transforms. The automatic JSX runtime also differs from the classic createElement transform, so check the actual build configuration.

  81. Describe about data flow in react?

    React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding.

  82. What is MobX?

    MobX manages observable state and derived reactions. Its React integration documents observer bindings, including mobx-react-lite for function components. Use the binding and configuration supported by the installed version rather than assuming one package name fits every application.

  83. What are the differences between Redux and MobX?

    Redux uses a store/reducer/action model with immutable update semantics; Redux Toolkit can express updates through Immer drafts. MobX tracks observable values and reactions. Both can be used in substantial applications. Neither a “small versus large app” label nor an unsupported performance ranking is enough to choose between them. Compare state ownership, subscriptions, debugging, team familiarity, and measured behavior.

  84. Should I learn ES6 before learning ReactJS?

    Learn the JavaScript used by the code you will maintain: modules, functions, closures, arrays, objects, destructuring, and promises. You can learn React alongside those topics, but copying JSX without understanding its JavaScript makes debugging harder. Older examples that contrast ES5 and ES6 are background; choose the application's current toolchain and browser targets.

  85. What is Concurrent Rendering?

    Modern React can interrupt or abandon some render work before commit. This is not parallel execution of arbitrary JavaScript. The old unstable_ConcurrentMode and unstable_createRoot snippets are not current setup APIs. Use the framework's supported root and public transition APIs. See the concurrent-rendering answer.

  86. What is the difference between async mode and concurrent mode?

    “Async Mode” and “Concurrent Mode” appeared in historical discussions. Current guidance describes concurrent rendering capabilities and public APIs such as transitions. Do not recommend either old experimental name as a switch to enable in a new application.

  87. Can I use javascript urls in react16.9?

    This heading refers to React 16.9's historical behavior. It is not permission to use javascript: URLs in current code. React 19 blocks these URLs. Validate navigation destinations against the application's allowed URL contract, and never rely on a warning as protection. See the React 19 upgrade guide.

  88. What is the purpose of eslint plugin for hooks?

    The current Hooks lint plugin checks where Hooks are called and whether dependencies are complete, along with additional React rules. The use-prefixed naming convention helps analysis but does not guarantee correct logic. See the plugin setup answer and its current reference.

  89. What is the difference between Imperative and Declarative in React?

    Declarative UI describes the output for state; an imperative approach specifies steps that mutate the current UI. React still uses imperative browser operations internally. A small declarative example is:

    import { useState } from "react"
    
    export default function LikeButton() {
      const [isLiked, setIsLiked] = useState(false)
      return <button aria-pressed={isLiked} onClick={() => setIsLiked((previous) => !previous)}>
        {isLiked ? "Liked" : "Like"}
      </button>
    }
    

    Use an uppercase component binding for a custom component; a lowercase blueLike tag would not call a similarly named function.

  90. What are the benefits of using TypeScript with ReactJS?

    TypeScript can check prop and state contracts, improve editor feedback, and detect certain mistakes before execution. It does not validate an untrusted API response at runtime or polyfill browser APIs. The build target, runtime validation, and tests remain separate concerns.

  91. How do you make sure that user remains authenticated on page refresh while using Context API State Management?

    Context stores client UI state; it cannot establish that a session is valid after reload. On startup, use the application's authorized session mechanism to ask the authoritative service for the current user. Represent pending, authenticated, unauthenticated, and failed checks separately.

    A failed session request is not a successful login, and finding a token string in browser storage is not authorization. Prevent stale responses from restoring a user after logout. Enforce access on the backend as well as deciding which UI to display. This answer does not assume a particular token-storage or authentication-provider contract.

  92. What are the benefits of new JSX transform?

    The automatic JSX transform can compile JSX without a React namespace import in each file. React and the runtime packages still need to be installed, and Hooks still need their own imports. Bundle effects depend on the build; it is not a guaranteed size reduction for every application.

  93. How is the new JSX transform different from old transform??

    The classic transform emits createElement calls and commonly needs a React binding in scope. The automatic transform imports helpers from the JSX runtime instead. This removes the need for a namespace import solely for JSX; it does not remove the React dependency. Import useState or other Hooks explicitly when using them.

  94. What are React Server components?

    React Server Components execute in an environment separate from the client component bundle. They may run at build time or during a request. They are different from ordinary SSR, which produces initial HTML for a component tree.

    Server Components are stable in React 19, while the lower-level framework/bundler integration APIs have different versioning constraints. Use a supported framework integration. Client interactions, state, and effects still need an appropriate client boundary.

  95. What is prop drilling?

    Prop Drilling is the process by which you pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around.

  96. What is the difference between useState and useRef hook?

  97. useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes. Essentially, useRef is like a “box” that can hold a mutable value in its (.current) property.

  98. useState allows us to update the state inside components. While useRef allows referencing DOM elements and tracking values.

  99. What is a wrapper component?

    A wrapper in React is a component that wraps or surrounds another component or group of components. It can be used for a variety of purposes such as adding additional functionality, styling, or layout to the wrapped components.

    For example, consider a simple component that displays a message:

    const Message = ({ text }) => {
      return <p>{text}</p>
    }
    

    We can create a wrapper component that will add a border to the message component:

    const MessageWrapper = (props) => {
      return (
        <div style={{ border: "1px solid black" }}>
          <Message {...props} />
        </div>
      )
    }
    

    Now we can use the MessageWrapper component instead of the Message component and the message will be displayed with a border:

    <MessageWrapper text="Hello World" />
    

    Wrapper component can also accept its own props and pass them down to the wrapped component, for example, we can create a wrapper component that will add a title to the message component:

    const MessageWrapperWithTitle = ({ title, ...props }) => {
      return (
        <div>
          <h3>{title}</h3>
          <Message {...props} />
        </div>
      )
    }
    

    Now we can use the MessageWrapperWithTitle component and pass title props:

    <MessageWrapperWithTitle title="My Message" text="Hello World" />
    

    This way, the wrapper component can add additional functionality, styling, or layout to the wrapped component while keeping the wrapped component simple and reusable.

  100. What are the differences between useEffect and useLayoutEffect hooks?

    useLayoutEffect runs before the browser repaints and can block that paint; useEffect is normally the choice when a layout measurement is not required. useEffect is not guaranteed to run after paint in every interaction, and it does not have a special error-swallowing mechanism absent from useLayoutEffect.

    Keep layout work small, include correct dependencies and cleanup, and follow the layout-effect reference. Neither Hook provides a universal guarantee against visual flicker or application errors.

  101. What are the differences between Functional and Class Components?

    Both function and class components accept props and can own state. Function components use Hooks; classes use supported class APIs and this.props/this.state. Class state is an object and class setState shallowly merges updates; a useState value can have other types and its setter replaces the value.

    Prefer functions for new code while preserving existing behavior during a class migration. See when a class is useful.

  102. What is strict mode in React?

    StrictMode wraps a tree or subtree to enable additional development checks without adding a DOM wrapper. Its placement affects which checks apply. Inspect the framework/project configuration rather than assuming every app enables it in the same way. See the core StrictMode example.

  103. What is the benefit of strict mode?

    StrictMode adds development checks, including repeated work that can expose impure rendering, missing effect cleanup, and ref-callback problems. It does not prove an application is bug-free. Some APIs previously warned about, such as findDOMNode, are removed in React 19 rather than merely current warnings. See StrictMode.

  104. Why does strict mode render twice in React?

    Repeated development rendering helps expose side effects in render. Effect setup/cleanup and ref callbacks can also receive additional checks depending on StrictMode placement. Event handlers are not simply all called twice.

    Fix missing cleanup or impurity instead of removing StrictMode to hide the symptom. Render logs alone are not a production performance measurement.

  105. What are the rules of JSX?

    A return statement needs one JavaScript expression. Adjacent JSX tags can be grouped in a Fragment, an element, or an appropriate array. Close tags explicitly and use React DOM prop conventions, while retaining lowercase aria-* and data-* attributes. A wrapper DOM element is not always required.

  106. What is the reason behind multiple JSX tags to be wrapped?

    Two adjacent JSX elements are not one JavaScript expression. A Fragment groups them without adding a DOM wrapper; an array is another possible returned value with the usual key requirements for a list. The rule is not that components can only return a single plain object.

  107. How do you prevent mutating array variables?

    Treat props and existing state arrays as read-only snapshots. map, filter, slice, and spread can create a new array, but they are shallow: mutating an object inside the copy can still mutate the original object. Copy each changed level or use a correctly scoped Immer producer.

  108. What are capture phase events?

    Capture handlers run on the path toward the target before bubbling handlers. A target's stopPropagation in the bubbling phase does not undo capture handlers that already ran. Propagation can still be stopped earlier, so capture is not a guarantee of observing every possible event. Keep analytics collection consistent with the application's actual consent and data rules.

  109. How does React updates screen in an application?

    React processes a trigger, renders components to calculate output, and commits relevant changes to the host environment. An application root calls createRoot(...).render(...), not a component instance's render method. A component render does not guarantee a DOM mutation. See the render/commit explanation.

  110. How does React batch multiple state updates?

    React can batch queued state updates. When the next value depends on queued previous values, use updater functions; do not infer a fixed render count from console output under development checks. See the two-update counter.

  111. Is it possible to prevent automatic batching?

flushSync can force relevant updates to reach the DOM synchronously for unusual integration needs. It can hurt performance and is not a normal solution for reading the next state value. Use queued updater functions for dependent state updates. See the flushSync reference before using it at an integration boundary.

  1. What is React hydration?

Hydration attaches React to matching HTML produced ahead of the client render, whether generated at request time or during a build. It is not a ranking guarantee. The server and initial client tree must agree. See the hydrateRoot example and test mismatches and event behavior separately.

  1. How do you update objects inside state?

Create a new object through the setter and retain the unchanged fields. This complete component excerpt updates a name:

import { useState } from "react"

export default function Profile() {
  const [profile, setProfile] = useState({ firstName: "John", lastName: "Abraham" })
  function handleFirstNameChange(event) {
    const firstName = event.target.value
    setProfile((previous) => ({ ...previous, firstName }))
  }
  return <>
    <label>First name<input value={profile.firstName} onChange={handleFirstNameChange} /></label>
    <p>{profile.firstName} {profile.lastName}</p>
  </>
}

Changing an object property without the setter does not request the intended React update.

  1. How do you update nested objects inside state?

Copy every changed level of a nested object and use the queued previous state when the update depends on it. An illustrative setter excerpt is:

setProfile((previous) => ({
  ...previous,
  address: { ...previous.address, country: "Germany" },
}))

This assumes an existing setProfile setter and address object. Flatten state when it simplifies the domain; copying the top level alone does not copy the nested object.

  1. How do you update arrays inside state?

Pass an event function that calls the setter with a new array. Merely constructing an array or calling push is not a state update.

import { useState } from "react"

export default function TodoDemo() {
  const [todos, setTodos] = useState([])
  function handleAdd() {
    const newTodo = { id: crypto.randomUUID(), title: "New todo" }
    setTodos((previous) => [...previous, newTodo])
  }
  return <>
    <button onClick={handleAdd}>Add</button>
    <ul>{todos.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
  </>
}

The identifier is generated for a newly added record during the event, not regenerated for every row during rendering.

  1. How do you use immer library for state updates?

Immer allows mutation-like syntax only on a draft within its producer. With use-immer installed, call useImmer inside a function component or custom Hook, just like other Hooks. It does not make it safe to mutate arbitrary existing props or state.

import { useImmer } from "use-immer"

export default function Location() {
  const [profile, updateProfile] = useImmer({ address: { country: "Singapore" } })
  function moveToGermany() {
    updateProfile((draft) => {
      draft.address.country = "Germany"
    })
  }
  return <button onClick={moveToGermany}>{profile.address.country}</button>
}
  1. What are the benefits of preventing the direct state mutations?

Immutable updates preserve earlier snapshots, make changes observable through identity comparisons, and avoid changing another consumer's view unexpectedly. They also make tests and debugging easier to reason about. Immutability is not a promise of better performance in every case; choose a representation that keeps updates understandable.

  1. What are the preferred and non-preferred array operations for updating the state?

Use non-mutating operations on existing state: map for replacements, filter for removals, and spread/concat for additions. For sort or reverse, copy first. These are shallow copies, so also copy changed nested objects. Mutation-like methods belong only on a local copy or an Immer draft inside its producer.

  1. What will happen by defining nested function components?

Defining a component inside another component's render creates a new component function identity on each parent render. React can treat it as a different type and reset its state. Declare component types at module scope and pass changing values as props. An ordinary helper that returns markup is a different contract from a component rendered as a JSX type.

  1. Can I use keys for non-list items?

Yes. A key can intentionally distinguish a non-list component and reset its state when the identity changes. For example, keying an editor by a document ID can start a fresh editor for another document. Use a stable domain identity and decide whether reset is intended; a random key on every render discards state repeatedly. See state preservation.

  1. What are the guidelines to be followed for writing reducers?

A reducer must calculate the next state from its inputs without external side effects or mutation of existing state. Model actions around meaningful interactions, such as resetting a form, rather than depending on an accidental order of field updates. In Redux Toolkit an Immer draft permits mutation-like syntax inside its supported reducer contract; that is different from mutating an ordinary existing object.

  1. How does ReactJS work behind the scenes?

Separate React's internal architecture from its public behavior. Components calculate output during render; reconciliation associates identities; a commit applies relevant host changes. Fiber supports scheduling, but its fields and internal phases are not application APIs.

React does interact with the real DOM, and not every render becomes a commit. Effects also have different timing contracts. Use the core rendering questions for public examples rather than relying on a simplified internal diagram as a guarantee.

  1. How is useReducer Different from useState?

useState and useReducer both manage local component state. Either can hold complex values. useReducer separates transitions into an explicit reducer/action model, which can help when related changes need a single tested transition. Neither Hook automatically shares state across component instances or reduces renders merely by being chosen.

  1. What is useContext? What are the steps to follow for useContext?

Create a context with an explicit default, provide a value above the consumer, and read it with useContext. This complete component excerpt demonstrates a theme:

import { createContext, useContext } from "react"

const ThemeContext = createContext("light")
function ThemeLabel() {
  const theme = useContext(ThemeContext)
  return <p>Theme: {theme}</p>
}

export default function ThemeDemo() {
  return <ThemeContext.Provider value="dark"><ThemeLabel /></ThemeContext.Provider>
}

The default applies when no matching provider exists above the consumer. A provider explicitly supplying undefined is a different case.

  1. What are the use cases of useContext hook?

Context can share a theme, locale, current-user UI state, or a shared interaction state through a subtree. Ownership still belongs to a provider or another store. Sharing an authenticated-looking user object does not authorize access to protected data; the service must enforce it. Split unrelated values when their consumers and update patterns justify it.

  1. When to use client and server components?

In the Next.js App Router, use a Client Component boundary for interactive state, event handlers, and browser APIs. Keep server-only credentials and backend access on the server. A Client Component can still contribute server-rendered initial HTML, so “client” does not mean “never runs during server rendering.”

Follow the current server/client component guide. Data loading can exist on either side depending on the framework's design; do not make the boundary from a blanket “all fetches belong here” rule.

  1. What are the differences between page router and app router in nextjs?

The Pages Router uses pages-based route files and APIs such as getServerSideProps/getStaticProps. The App Router uses app route segments, layouts, and React Server Component boundaries. It provides dedicated loading, error, and metadata conventions.

Pages Router components can be server-rendered; labeling them all as browser-only Client Components is misleading. Choose the actual router and Next.js version before discussing data caching, streaming, or server mutation APIs. See the Next.js documentation.

  1. Can you describe the useMemo() Hook?

useMemo caches a calculation result until React needs to recompute it, normally when a dependency changes. It is an optimization, not a semantic guarantee that a function runs only once. Include every reactive input.

import { useMemo, useState } from "react"

export default function UserSearch({ users }) {
  const [query, setQuery] = useState("")
  const visibleUsers = useMemo(() => {
    const normalizedQuery = query.toLowerCase()
    return users.filter((user) => user.name.toLowerCase().includes(normalizedQuery))
  }, [users, query])
  return <>
    <label>Search users<input value={query} onChange={(event) => setQuery(event.target.value)} /></label>
    <ul>{visibleUsers.map((user) => <li key={user.id}>{user.name}</li>)}</ul>
  </>
}

This excerpt expects a users array with id/name fields. Both users and query are dependencies. Measure whether caching helps for the actual list. See useMemo.

  1. Can Hooks be used in class components?

    No, Hooks cannot be used inside class components. They are specially designed for function components. This is because hooks depend on the sequence in which they are called during a component’s render, something that's only guaranteed in functional components. However, both class and function components can coexist in the same application.

  2. What is an updater function? Should an updater function be used in all cases?

An updater function is a form of setState where you pass a function instead of a direct value. This function receives the previous state as an argument and returns the next state.

The updater function expression looks like below,

setCount((prevCount) => prevCount + 1) // Safe and predictable

Here, prevCount => prevCount + 1 is the updater function.

In the React community, there's often a recommendation to use updater functions when updating state that depends on its previous value. This helps prevent unexpected behaviors that can arise from working with outdated or "stale" state.

While using an updater function is a good habit, it's not always necessary. In most cases, React batches updates and ensures that the state is up-to-date at the beginning of the event handler, so you typically don’t run into stale state issues during a single synchronous event. However, if you’re doing multiple updates to the same state variable within a single handler, using the updater form ensures that each update correctly uses the latest state value, rather than a potentially outdated one.

Example: Multiple Updates in One Handler

function handleCount() {
  setCounter((a) => a + 1)
  setCounter((a) => a + 1)
  setCounter((a) => a + 1)
}

In this example, a => a + 1 is an updater function. React queues these updater functions and applies them sequentially, each using the most recent state value. As a result, the counter will correctly increment by 3.

In many cases, such as setting state based on user input or assigning static values, you don’t need the updater function:

setName("Sudheer")
  1. Can useState take a function as an initial value?

A useState initializer function calculates the initial stored value without repeating the calculation on every ordinary render. It must be pure. Development checks can call it more than once, and remounting creates a new state instance, so “runs exactly once forever” is incorrect. To store a function as a value, return that function from an initializer rather than accidentally invoking it as the initializer.

  1. What types of values can useState hold?

useState can hold primitives, objects, arrays, functions, null, or undefined. For objects/arrays, use immutable updates. To store a function, use an initializer or updater that returns the function; passing a function directly is interpreted as an initializer or updater. React compares values with Object.is when deciding whether an equal update can be skipped.

  1. What happens if you call useState conditionally?

Calling useState conditionally violates Hook ordering, even if a small example appears to work while the condition stays unchanged. When order changes, React can misassociate state or report a Hook-order error. Use the linter and move the condition inside behavior after declaring the Hook. The current use API has its own different rules.

  1. Is useState Synchronous or Asynchronous?

useState returns the current render's value and a setter during render. The setter queues another update; it does not return a promise or modify the variable in the existing handler. Describe this as a state snapshot and queued rendering rather than an ordinary asynchronous assignment that can be awaited.

  1. Can you explain how useState works internally?

Conceptually, React associates Hook state and update queues with a particular component identity and Hook call order. On another render, queued updates contribute to the state returned for that render.

A global array-and-index demonstration omits component instances, scheduling, bailouts, and many other concerns. Do not present such a toy as React's actual implementation. For application code, rely on the state snapshot contract, not internal storage details.

  1. What is useReducer? Why do you use useReducer?

useReducer takes a reducer, an initial argument, and an optional initializer. Without an initializer, the argument supplies the initial state; with one, React calls the initializer to produce it. dispatch queues an action, and the pure reducer returns the next state. It can help organize related transitions without making the state global.

  1. How does useReducer works? Explain with an example

The useReducer hooks works similarly to Redux, where:

  • You define a reducer function to handle state transitions.
  • You dispatch actions to update the state.

Counter Example with Increment, Decrement, and Reset:

  1. Reducer function:

Define a counter reducer function that takes the current state and an action object with a type, and returns a new state based on that type.

function counterReducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 }
    case "decrement":
      return { count: state.count - 1 }
    case "reset":
      return { count: 0 }
    default:
      return state
  }
}
  1. Using useReducer: Invoke useReducer with above reducer function along with initial state. Thereafter, you can attach dispatch actions for respective button handlers.
import React, { useReducer } from "react"

function Counter() {
  const initialState = { count: 0 }
  const [state, dispatch] = useReducer(counterReducer, initialState)

  return (
    <div style={{ textAlign: "center" }}>
      <h2>Count: {state.count}</h2>
      <button onClick={() => dispatch({ type: "increment" })}>Increment</button>
      <button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  )
}

export default Counter

Once the new state has been returned, React re-renders the component with the updated state.count.

  1. Can you combine useReducer with useContext?

Yes, it's common to combine useReducer with useContext to build a lightweight state management system similar to Redux:

const AppContext = React.createContext()

function AppProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState)
  return <AppContext.Provider value={{ state, dispatch }}>{children}</AppContext.Provider>
}
  1. Can you dispatch multiple actions in a row with useReducer?

Yes, you can dispatch multiple actions in a row using useReducer but not directly in one call. You'd have to call dispatch multiple times or create a composite action in your reducer that performs multiple updates based on the action type.

Example: Dispatching Multiple Actions You can define a custom function with dispatching actions one by one.

function handleMultipleActions(dispatch) {
  dispatch({ type: "increment" })
  dispatch({ type: "increment" })
  dispatch({ type: "reset" })
}

After that, you need to invoke it through event handler

<button onClick={() => handleMultipleActions(dispatch)}>Run Multiple Actions</button>

Note: You can also define a custom action type If you want multiple state changes to be handled in one reducer call.

case 'increment_twice':
  return { count: state.count + 2 };

Then dispatch

dispatch({ type: "increment_twice" })
  1. How does useContext works? Explain with an example

Context can share a simulated current-user value across a subtree. The example below only updates local UI state: it does not authenticate credentials, restore a server session, or authorize protected data.

The context-sharing demonstration has:

  • Login and Logout buttons
  • An AuthContext provider to share local state
  • Components that can read and update that simulated state

1. Create the Auth Context:

You can define AuthProvider which holds and provides user, login(), and logout() via context.

// AuthContext.js
import React, { createContext, useContext, useState } from "react"

const AuthContext = createContext()

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null)

  const login = (username) => setUser({ name: username })
  const logout = () => setUser(null)

  return <AuthContext.Provider value={{ user, login, logout }}>{children}</AuthContext.Provider>
}

// Custom hook for cleaner usage
export const useAuth = () => useContext(AuthContext)

2. Wrap Your App with the Provider:

Wrap the above created provider in main App.js file

// App.js
import React from "react"
import { AuthProvider } from "./AuthContext"
import HomePage from "./HomePage"
import Dashboard from "./Dashboard"

function App() {
  return (
    <AuthProvider>
      <HomePage />
      <Dashboard />
    </AuthProvider>
  )
}

export default App

3. Home page with login: Read or access user and login details through custom useAuth hook and use it inside home page.

// HomePage.js
import React from "react"
import { useAuth } from "./AuthContext"

function HomePage() {
  const { user, login } = useAuth()

  return (
    <div>
      <h1>Home</h1>
      {user ? (
        <p>Welcome back, {user.name}!</p>
      ) : (
        <button onClick={() => login("Alice")}>Login</button>
      )}
    </div>
  )
}

export default HomePage

4. Dashboard with logout: Read or access user and logout details from useAuth custom hook and use it inside dashboard page.

// Dashboard.js
import React from "react"
import { useAuth } from "./AuthContext"

function Dashboard() {
  const { user, logout } = useAuth()

  if (!user) {
    return <p>Please login to view the dashboard.</p>
  }

  return (
    <div>
      <h2>Dashboard</h2>
      <p>Logged in as: {user.name}</p>
      <button onClick={logout}>Logout</button>
    </div>
  )
}

export default Dashboard
  1. Can You Use Multiple Contexts in One Component?

Yes, it is possible. You can use multiple contexts inside the same component by calling useContext multiple times, once for each context.

It can be achieved with below steps,

  • Create multiple contexts using createContext().
  • Wrap your component tree with multiple <Provider>s.
  • Call useContext() separately for each context in the same component.

Example: Using ThemeContext and UserContext Together

import React, { createContext, useContext } from "react"

// Step 1: Create two contexts
const ThemeContext = createContext()
const UserContext = createContext()

function Dashboard() {
  // Step 2: Use both contexts
  const theme = useContext(ThemeContext)
  const user = useContext(UserContext)

  return (
    <div style={{ background: theme === "dark" ? "#333" : "#fff" }}>
      <h1>Welcome, {user.name}</h1>
      <p>Current theme: {theme}</p>
    </div>
  )
}

// Step 3: Provide both contexts
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <UserContext.Provider value={{ name: "Sudheer" }}>
        <Dashboard />
      </UserContext.Provider>
    </ThemeContext.Provider>
  )
}

export default App
  1. What's a common pitfall when using useContext with objects?

A provider object with a new identity can broadcast an update to useContext consumers even when only one field matters to each consumer. Splitting unrelated contexts can help. Memoizing the object can avoid identity changes caused by unrelated provider renders, but when theme changes in an object containing both user and theme, that object still changes and its consumers still update. Built-in useContext does not provide a selector argument.

  1. What would the context value be for no matching provider?

With no matching provider, useContext returns the default supplied to createContext. A provider whose value is undefined still supplies undefined; it does not activate the default. Choose an explicit default or a missing-provider error contract appropriate to the application.

  1. How do reactive dependencies in the useEffect dependency array affect its execution behavior?

Dependencies are the reactive values used by an effect's setup. React compares them with Object.is. With no array, setup runs after relevant commits; with listed values it reruns when one changes. An empty array does not guarantee one setup across remounts or development checks. Include the real dependencies instead of choosing an array to force an intended schedule.

  1. When and how often does React invoke the setup and cleanup functions inside a useEffect hook?

Setup runs for a committed mount and when the dependency comparison requires another synchronization. Cleanup runs before the next setup for changed dependencies and on unmount. Development StrictMode can add a setup/cleanup check. A render that is abandoned does not mean an effect setup ran. See effect lifecycle.

  1. What happens if you return a Promise from useEffect??

An effect setup must return undefined or a cleanup function, not a promise. An async setup returns a promise and cannot supply the expected cleanup contract; it can produce warnings or cleanup errors. Start asynchronous work inside a synchronous setup and handle its failure and cancellation. Use the complete fetching example instead of copying an unhandled fetch.

  1. Can you have multiple useEffect hooks in a single component?

Yes, multiple useEffect hooks are allowed and recommended when you want to separate concerns.

useEffect(() => {
  // Handles API fetch
}, [])

useEffect(() => {
  // Handles event listeners
}, [])

Each effect runs independently and helps make code modular and easier to debug.

  1. How to prevent infinite loops with useEffect?

An infinite synchronization loop requires an effect to update state in a way that changes a dependency again. Merely listing a state value does not automatically create a loop. First ask whether the work belongs in an event handler or can be derived during render. Do not omit real dependencies to hide the loop. See removing unnecessary effects.

  1. What are the usecases of useLayoutEffect?

Use useLayoutEffect for a layout-dependent read/update that must occur before repaint. Keep it small because it can block painting. A measurement that must respond to later resizing needs an appropriate observation strategy; an empty dependency array alone will not track every size change. Use ordinary effects when synchronous layout work is unnecessary.

  1. How does useLayoutEffect work during server-side rendering (SSR)?

Layout effects do not run on the server because there is no browser layout to measure. Consider rendering a layout-independent fallback, moving a genuinely layout-dependent widget to a suitable client path, or using a supported framework pattern. An isomorphic-effect alias can avoid one warning but cannot make server layout exist. See layout effects and server rendering.

  1. What happens if you use useLayoutEffect for non-layout logic?

Using useLayoutEffect for unrelated work can delay painting unnecessarily. Choose an event handler for work caused by a specific action or an ordinary effect for synchronization that does not need pre-paint layout. useEffect is not an unconditional promise of running after paint, and analytics collection still needs its own correct consent and retry behavior.

  1. How does useLayoutEffect cause layout thrashing?

Layout thrashing comes from read/write patterns that repeatedly force layout calculation, not simply from the name of a Hook. Group reads and writes when possible and avoid a layout read immediately after a layout-changing write when it is unnecessary. Measure actual layout work in browser performance evidence before claiming that a refactor removes a bottleneck.

  1. How Do You Use useRef to Access a DOM Element in React? Give an example.

Attach a ref to the element and read it after commit in an event or effect. A null guard handles an unavailable node:

import { useRef } from "react"

export default function FocusInput() {
  const inputRef = useRef(null)
  return <>
    <label>Name<input ref={inputRef} /></label>
    <button onClick={() => inputRef.current?.focus()}>Focus name</button>
  </>
}

Changing ref.current is not a request to update visible content.

  1. Can you use useRef to persist values across renders??

A ref can retain a mutable value without requesting a render. Use it for values such as an interval handle that are needed by handlers or effects. If a changing value must appear in the UI, use state. Counting effect executions in a ref is not an exact render count, particularly under development checks.

  1. Can useRef be used to store previous values?

Use a ref for a previous value needed only by an effect or event handler. Do not read mutable refs during render as a general mechanism for drawing previous-value UI. If the previous value is visible, model it as state.

import { useState } from "react"

export default function PreviousCount() {
  const [count, setCount] = useState(0)
  const [previousCount, setPreviousCount] = useState(null)
  function increment() {
    setPreviousCount(count)
    setCount(count + 1)
  }
  return <>
    <p>Current: {count}; previous click value: {previousCount ?? "None"}</p>
    <button onClick={increment}>Increment</button>
  </>
}

This tracks the value before this demo's increment action, not every intermediate render.

  1. Is it possible to access a ref in the render method?

Avoid reading or writing mutable ref.current during render, apart from the documented predictable-initialization exception. A DOM ref is not populated until the node is committed and can later become null. Read it in an event handler or appropriate effect. See useRef.

  1. What are the common usecases of useRef hook?

    Some of the common cases are:
  • Automatically focus an input when a component mounts.
  • Scroll to a specific element.
  • Measure element dimensions (offsetWidth, clientHeight).
  • Control video/audio playback.
  • Integrate with non-React libraries (like D3 or jQuery).
  1. What is useImperativeHandle Hook? Give an example.

useImperativeHandle exposes a deliberate imperative handle. In React 19 a function component can receive ref as a prop; older versions commonly use forwardRef. This complete component example exposes only focus:

import { useImperativeHandle, useRef } from "react"

function FocusInput({ ref }) {
  const inputRef = useRef(null)
  useImperativeHandle(ref, () => ({
    focus() {
      inputRef.current?.focus()
    },
  }), [])
  return <label>Name<input ref={inputRef} /></label>
}

export default function FocusDemo() {
  const fieldRef = useRef(null)
  return <>
    <FocusInput ref={fieldRef} />
    <button onClick={() => fieldRef.current?.focus()}>Focus name</button>
  </>
}

See useImperativeHandle. Use props for ordinary declarative behavior rather than exposing a large internal API.

  1. When should you use useImperativeHandle?

Use useImperativeHandle when a parent needs a small imperative operation such as focusing a custom input. Prefer ordinary props for declarative state such as whether content is open. Keep the exposed handle limited and document when it can be null. The Hook is named useImperativeHandle, not useImperativeHandler.

  1. Is that possible to use useImperativeHandle without forwardRef?

Yes, in React 19 a function component can receive ref as a prop and pass it to useImperativeHandle. For React 18 and earlier, forwardRef is the usual function-component pattern. State the target version; the old blanket “No” answer is incorrect for current React.

  1. How is useMemo different from useCallback?

useMemo caches a calculation result; useCallback caches the function reference it returns. Both compare dependencies and are performance tools, not correctness guarantees. They do not automatically prevent state/context updates or move computation off the main thread. Use them only when the value/reference stability matters in the actual application.

  1. Does useMemo prevent re-rendering of child components?

useMemo alone does not block a child render. A stable prop can help a memoized child skip some parent-driven work, but the child's own state or context can still update it. Profile before combining memoization layers and verify whether React Compiler is actually enabled in the project.

  1. What is useCallback and why is it used?

useCallback caches the function reference React returns while dependencies remain equal. The function expression can still be created during render; the Hook is not a universal way to avoid allocating functions. Use it when reference stability has a measured or contractual purpose and include all reactive dependencies. See useCallback.

  1. What are Custom React Hooks, and How Can You Develop One?

A custom Hook shares logic, while each call still owns its own state unless it explicitly subscribes to shared state. A minimal complete example is:

import { useState } from "react"

function useCounter() {
  const [count, setCount] = useState(0)
  function increment() {
    setCount((previous) => previous + 1)
  }
  return { count, increment }
}

function Counter() {
  const { count, increment } = useCounter()
  return <button onClick={increment}>{count}</button>
}

export default function IndependentCounters() {
  return <><Counter /><Counter /></>
}

Clicking one counter does not update the other. A fetching Hook needs additional request-state, error, and stale-response handling; see the SWR/Vite example.

  1. How does React Fiber works? Explain in detail.

Fiber organizes internal rendering work and scheduling. Render work can be interrupted or abandoned before a commit; committing host changes has a different contract. It is incorrect to describe every commit as inherently fast or to treat all effect timing as identical.

For interviews, connect this architecture to public behavior such as pure render functions, stable identity, and transitions. Avoid making application code depend on a simplified list of Fiber fields. See the core Fiber questions.

  1. What is the useId hook and when should you use it?

The useId Hook generates IDs for relationships such as accessible labels. Matching server/client trees and appropriate root prefixes matter for hydration. It's primarily used for accessibility attributes like linking form labels to inputs.

Syntax

const id = useId()

Example: Accessible Form Input

import { useId } from "react"

function EmailField() {
  const id = useId()

  return (
    <div>
      <label htmlFor={id}>Email:</label>
      <input id={id} type="email" />
    </div>
  )
}

When to Use

  • Generating unique IDs for form elements (htmlFor, aria-describedby, aria-labelledby)
  • Creating stable IDs in server-side rendering (SSR) applications
  • Avoiding ID collisions when the same component is rendered multiple times

When NOT to Use

  • As keys in a list (use data-based keys instead)
  • As CSS selectors or query selectors
  • For any purpose that requires the ID to be predictable

Treat the generated ID as opaque: do not parse it or rely on a particular punctuation format. Use the same value to connect related accessibility attributes. See the useId reference.

  1. What is the useDeferredValue hook?

useDeferredValue can let a rendered value lag behind an urgent input value. It is not a fixed debounce timer, a network-request limiter, or a worker. A memoized slow child can help React avoid repeating the expensive part for the urgent render.

Provide the actual dataset and component when testing responsiveness; an undefined largeDataSet is not a runnable benchmark. Measure the real list and keep necessary input updates urgent. See useDeferredValue.

  1. What is the useTransition hook and how does it differ from useDeferredValue?

useTransition returns isPending and startTransition for marking controlled updates as transitions. useDeferredValue works on a value that can lag. Neither automatically moves a long synchronous computation off the main thread. Keep controlled text-input state urgent and consult the transition reference for asynchronous action details.

  1. What is the useSyncExternalStore hook?

The useSyncExternalStore hook is designed to subscribe to external stores (non-React state sources) in a way that's compatible with concurrent rendering. It's primarily used by library authors for state management libraries.

Syntax

const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?);
  • subscribe: Function to subscribe to the store, returns an unsubscribe function
  • getSnapshot: Function that returns the current store value
  • getServerSnapshot: Optional function for SSR that returns the initial server snapshot

Example: Browser Online Status

import { useSyncExternalStore } from "react"

function getSnapshot() {
  return navigator.onLine
}

function subscribe(callback) {
  window.addEventListener("online", callback)
  window.addEventListener("offline", callback)
  return () => {
    window.removeEventListener("online", callback)
    window.removeEventListener("offline", callback)
  }
}

function useOnlineStatus() {
  return useSyncExternalStore(subscribe, getSnapshot, () => true)
}

function StatusBar() {
  const isOnline = useOnlineStatus()
  return <h1>{isOnline ? "✅ Online" : "❌ Disconnected"}</h1>
}

The browser's online flag is a connectivity hint, not proof that a particular API or authenticated session is reachable. Keep subscribe stable and provide a consistent server snapshot when rendering on the server. See useSyncExternalStore.

  1. What is the useInsertionEffect hook?

useInsertionEffect is intended for CSS-in-JS library authors that need to insert styles before layout effects. Application code usually needs useEffect or useLayoutEffect instead. It does not promise that insertion always occurs before every DOM mutation; refs may not yet be attached, and state updates are not allowed there.

A real style library also needs cleanup, deduplication, multiple-root, and server-rendering behavior. A global Set plus one style insertion is not a complete implementation. See useInsertionEffect.

  1. How do you share state logic between components using custom hooks?

A custom Hook shares a procedure for using state, not the state instance itself. The two-counter example shows independent state. To share one value, use an intentional provider or external store and define its subscription behavior.

Persisting values in localStorage is a separate concern. It needs a defined browser/SSR scope, parsing and quota failures, key-change behavior, and synchronization rules. Reading localStorage during a server render or writing before a persisted value has loaded can cause mismatches or overwrite the stored value.

  1. What is the useDebugValue hook?

useDebugValue adds a label for a custom Hook in React DevTools. An optional formatting function can defer formatting until inspection. It is useful when the label helps a developer understand shared logic; it is not required for every Hook and is not restricted to published libraries. See useDebugValue.

  1. How do you handle cleanup in useEffect?

Cleanup reverses the external synchronization that setup created: remove the same event listener, clear an interval, or unsubscribe from a subscription. It runs before a replacement setup and on unmount, with additional development checks under StrictMode.

For a request, also prevent obsolete results from updating the current view and handle HTTP failures. Abort alone is not a replacement for the response contract. See the fetching example.

  1. What are the differences between useEffect and useEvent (experimental)?

The old proposed useEvent name is not the stable API to import from current React. React 19.2 introduced useEffectEvent for non-reactive logic used from effects. It is not a general UI-event handler and must not be used to hide real dependencies.

For a timer effect that needs the latest onTick prop:

import { useEffect, useEffectEvent } from "react"

export default function Timer({ onTick }) {
  const notifyTick = useEffectEvent(() => onTick())
  useEffect(() => {
    const intervalId = setInterval(() => notifyTick(), 1000)
    return () => clearInterval(intervalId)
  }, [])
  return <p>Timer active</p>
}

Use a compatible React version and Hooks linter. See useEffectEvent for call-site restrictions; do not pass an Effect Event around as an ordinary callback.

  1. What are the best practices for using React Hooks?

Follow the current Rules of Hooks and use the project's supported Hooks lint configuration. Keep render pure, include real effect dependencies, and pair subscriptions/timers with cleanup. Separate independent synchronization concerns rather than writing one effect for unrelated tasks.

Do not memoize by default, suppress dependency warnings to force a schedule, or use mutable refs as hidden rendering state. Test loading, failure, empty, and stale-response paths. These practices improve reviewability but do not guarantee bug-free code.


📚 Related React Interview Questions

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

Core React Interview Questions

Master Core React interview questions covering JSX, Virtual DOM, Components, Props, State, and more. Essential React JS ...

React Hooks Interview Questions

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

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:

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