React Interview Questions and Answers (original) (raw)

React is an efficient, flexible, and open-source **JavaScript **library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications with React.

In this Top React Interview Questions article, we’ve covered the **70+ Interview Questions of React that cover everything from basic to advanced React concepts such as **Virtual DOM, Components, State and Props, JSX, Hooks, Routing, and more. Whether you are a **fresher or an **experienced professional with 2 - 10 years of experience, these React Interview Questions give you all the confidence you need to ace your next technical interview.

Table of Content

React Interview Questions For Freshers

Let’s discuss some common questions that you should prepare for the interviews. These questions will help clear the interviews, especially for the front-end development role.

**1. What is ReactJS?

ReactJS is a JavaScript library used to build reusable components for the view layer in the MVC architecture. It is used to build the Single Page Application (SPA) due to its component-based architecture, efficient re-rendering with the Virtual DOM, and ability to manage dynamic content without needing full page reloads. It is written in JSX.

**Important Features of React:

2. What is the latest version of the React?

The latest stable version of React is **v19.1.0, released on **March 28, 2025 . This version builds upon the major updates introduced in **React v19.0.0, which was officially released on **December 5, 2024.

**3. Explain the MVC architecture.

The Model-View-Controller (MVC) framework is an architectural/design pattern that separates an application into three main logical components: Model, View, and Controller. Each architectural component is built to handle specific development aspects of an application. It isolates the business, logic, and presentation layers from each other

**4. Explain the building blocks of React.

The five main building blocks of React are

**5. Explain props and state in React with differences

Props are used to pass data from one component to another. The state is local data storage that is local to the component only and cannot be passed to other components.

Here is the difference table of props and state In react

**PROPS **STATE
The Data is passed from one component to another. The Data is passed within the component only.
It is Immutable (cannot be modified). It is Mutable ( can be modified).
Props can be used with state and functional components. The state can be used only with the state components/class component (Before 16.0).
Props are read-only. The state is both read and write.

**6. What is virtual DOM in React?

The **Virtual DOM in React is an in-memory representation of the actual DOM. It helps React efficiently update and render the user interface by comparing the current and previous virtual DOM states using a process called **diffing.

**How Virtual DOM Works

7. Differentiate between Real DOM and virtual DOM?

**Real DOM **Virtual DOM
The actual DOM, a tree-like structure representing the UI elements. A lightweight copy of the Real DOM used to optimize updates.
Slower as it requires direct updates to the actual DOM. Faster because it minimizes direct manipulation of the Real DOM.
Directly manipulates the Real DOM, causing re-rendering of the entire UI. Updates are made to the Virtual DOM first, then changes are batched and only the necessary changes are reflected in the Real DOM.
Entire UI might need to be re-rendered when changes occur. Only the necessary components are re-rendered, reducing unnecessary re-renders.
Less efficient due to repeated direct updates to the Real DOM. More efficient by minimizing direct DOM manipulation and batch updates.

**8. What is JSX?

JSX is basically a syntax extension of regular JavaScript and is used to create React elements. These elements are then rendered to the React DOM. All the React components are written in JSX. To embed any JavaScript expression in a piece of code written in JSX we will have to wrap that expression in curly braces {}.

**Example of JSX: The name written in curly braces { } signifies JSX

const name = "Learner"; const element = (

Hello, {name}.Welcome to GeeksforGeeks.

);

**9. What are components and their type in React?

A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier.

In React, we mainly have two types of components:

**10. How do browsers read JSX?

In general, browsers are not capable of reading JSX and only can read pure JavaScript. The web browsers read JSX with the help of a transpiler. Transpilers are used to convert JSX into JavaScript. The transpiler used is called Babel.

**11. Explain the steps to create a react application and print Hello World?

To install React, first, make sure Node is installed on your computer. After installing Node. Open the terminal and type the following command.

npx create-react-app <>

Note: The above method is now deprecated, so use the below given method for creating the React application.

npm create vite@latest

Navigate to the folder.

cd <>

This is the first code of ReactJS Hello World!

Javascript `

import React from "react"; import "./App.css"; function App() { return

Hello World !
; } export default App;

`

**Output:

Type the following command to run the application

npm start

Screenshot-2025-03-06-150225

React app

**12. How to create an event in React?

To create an event in React, attach an event handler like onClick, onChange, etc., to a JSX element. Define the handler function to specify the action when the event is triggered, such as updating state or executing logic.

Javascript `

function Component() { doSomething(e); { e.preventDefault(); // Some more response to the event } return ; }

`

**13. Explain the creation of a List in React?

Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus on a website. To create a list in React use the map method of array as follows.

Javascript `

import React from "react"; import ReactDOM from "react-dom/client"; // Import react-dom/client

const numbers = [1, 2, 3, 4, 5];

const updatedNums = numbers.map((number) => { return

  • {number}
  • ; // Add a unique "key" prop });

    const root = ReactDOM.createRoot(document.getElementById("root")); // Create the root root.render(

    ); // Render the list into the root element

    `

    **Output:

    Screenshot-2025-03-06-164012

    List

    **14. What is a key in React?

    A key is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.

    There are two ways to write comments in React.

    /* This is a multi-line comment. It can span multiple lines. */

    // This is a single-line comment

    **16. Explain the difference between React and Angular?

    **React **Angular
    React is a JavaScript library. As it indicates react js updates only the virtual DOM is present and the data flow is always in a single direction. Angular is a framework. Angular updates the Real DOM and the data flow is ensured in the architecture in both directions.
    React is more simplified as it follows MVC ie., Model View Control. The architecture is complex as it follows MVVM models ie., Model View-ViewModel.
    It is highly scalable. It is less scalable than React JS.
    It supports Uni-directional data binding which is one-way data binding. It supports Bi-directional data binding which is two way data binding.
    It has a virtual DOM. It has regular DOM.

    **17. Explain the use of render method in React?

    React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.

    **18. What is state in React?

    The state is an instance of React Component Class that can be defined as an object of a set of observable properties that control the behaviour of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component.

    **19. Explain props in React?

    React allows us to pass information to a Component using something called props (which stands for properties). Props are objects which can be used inside a component

    We can access any props inside from the component’s class to which the props is passed. The props can be accessed as shown below:

    this.props.propName;

    **20. What is higher-order component in React?

    Higher-order components or HOC is the advanced method of reusing the component functionality logic. It simply takes the original component and returns the enhanced component. HOC are beneficial as they are easy to code and read. Also, helps to get rid of copying the same logic in every component.

    **21. Explain the difference between functional and class component in React?

    **Functional Components Class Components
    A functional component is just a plain JavaScript pure function that accepts props as an argument A class component requires you to extend from React. Component and create a render function
    No render method used It must have the render() method returning JSX
    Also known as Stateless components Also known as Stateful components
    React lifecycle methods (for example, componentDidMount) cannot be used in functional components. React lifecycle methods can be used inside class components (for example, componentDidMount).
    Constructors are not used. Constructor is used as it needs to store state.
    Uses hooks like useState for managing state. Uses this.state and this.setState for state management.

    **22. Explain one way data binding in React?

    ReactJS uses one-way data binding which can be Component to View or View to Component. It is also known as one-way data flow, which means the data has one, and only one way to be transferred to other parts of the application. In essence, this means child components are not able to update the data that is coming from the parent component. It is easy to debug and less prone to errors.

    23. What is Context API in React?

    The Context API is a way to share data (such as theme, language preference, etc.) across components without having to pass props down manually at every level. It provides a Provider component to set the value and a Consumer component or useContext() hook to access it.

    24. What is the role of shouldComponentUpdate() in React?

    shouldComponentUpdate() is a lifecycle method that allows you to control whether a component should re-render when it receives new props or state. If it returns false, React will skip the re-render process for that component.

    25. What is the use of dangerouslySetInnerHTML in React?

    dangerouslySetInnerHTML is an attribute used to set raw HTML inside a component. It is generally discouraged because it can expose the application to XSS (cross-site scripting) attacks, but it is sometimes used for rendering third-party HTML content.

    26. What are Pure Components in React?

    A Pure Component is a type of React component that only re-renders if the props or state it receives change. React provides React.PureComponent, which is a base class that automatically performs a shallow comparison of props and state to determine if a re-render is necessary.

    27. What is the significance of setState() in React?

    setState() is a method used to update the state of a component. When the state is updated, React re-renders the component and its child components to reflect the changes.

    Here, we cover all intermediate level react interview questions with answers, that recommeded for freshers as well as for experienced professionals having 1 - 2 years of experience.

    **28. What is conditional rendering in React?

    Conditional rendering in React involves selectively rendering components based on specified conditions. By evaluating these conditions, developers can control which components are displayed, allowing for dynamic and responsive user interfaces in React applications.

    Let us look at this sample code to understand conditional rendering.

    {isLoggedIn == false ? : }

    Here if the boolean isLoggedIn is false then the DisplayLoggedOut component will be rendered otherwise DisplayLoggedIn component will be rendered.

    **29. What is React Router?

    React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

    To install react router type the following command.

    npm i react-router-dom

    **30. Explain the components of a react-router.

    The main components of a react-router are:

    1. **Router(usually imported as BrowserRouter): It is the parent component that is used to store all of the other components. Everything within this will be part of the routing functionality
    2. **Switch: The switch component is used to render only the first route that matches the location rather than rendering all matching routes.
    3. **Route: This component checks the current URL and displays the component associated with that exact path. All routes are placed within the switch components.
    4. **Link: The Link component is used to create links to different routes.

    31. How is React routing different from conventional routing?

    **React Routing **Conventional Routing
    Used in Single Page Applications (SPA). Typically used in Multi-Page Applications (MPA).
    No full page reloads. React updates only the necessary parts of the UI. Full page reload is triggered for every navigation request.
    React uses a **client-side router (e.g., React Router) to handle navigation and manage different views within the same page. Uses **server-side routing where the server responds with new HTML for each navigation.
    Routes are managed by JavaScript, and the browser’s address bar reflects the application’s state. Routes correspond to different server-side routes, and the server responds with new HTML files.

    **32. Explain the lifecycle methods of components

    A React Component can go through four stages of its life as follows.

    **33. Explain the methods used in mounting phase of components

    Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time on the webpage. he mounting phase consists of two such predefined functions as described below

    **34. What is this.setState function in React?

    We use the setState() method to change the state object. It ensures that the component has been updated and calls for re-rendering of the component. The state object of a component may contain multiple attributes and React allows using setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each attribute value independently.

    **35. What is the use of ref in React?

    Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They have wide functionality as we can use callbacks with them.

    The syntax to use ref is :

    const node = this.myCallRef.current;

    **36. What are hooks in React?

    Hooks are a new addition in React 16.8. They let developers use state and other React features without writing a class. Hooks doesn’t violate any existing React concepts. Instead, Hooks provide a direct API to react concepts such as props, state, context, refs and life-cycle

    **37. Explain the useState hook in React?

    The most used hook in React is the useState() hook. Using this hook we can declare a state variable inside a function but only one state variable can be declared using a single useState() hook. Whenever the useState() hook is used, the value of the state variable is changed and the new variable is stored in a new cell in the stack.

    **Syntax:

    const [state, setState] = useState(initialState);

    **38. Explain the useEffect hook in React?

    The useEffect hook in React eliminates the side effect of using class based components. It is used as an alternative to componentDidUpdate() method. The useEffect hook accepts two arguments where second argument is optional.

    useEffect(function, dependency)

    The dependency decides when the component will be updated again after rendering.

    **39. What is React Fragments?

    when we are trying to render more than one root element we have to put the entire content inside the ‘div’ tag which is not loved by many developers. So since React 16.2 version, Fragments were introduced, and we use them instead of the extraneous ‘div’ tag. The following syntax is used to create fragment in react.

    <React.Fragment>

    Child-1


    Child-2


    </React.Fragment>

    **40. What is a react developer tool?

    React Developer Tools is a Chrome DevTools extension for the React JavaScript library. A very useful tool, if you are working on React applications. This extension adds React debugging tools to the Chrome Developer Tools. It helps you to inspect and edit the React component tree that builds the page, and for each component, one can check the props, the state, hooks, etc.

    **41. How to use styles in ReactJS?

    CSS modules are a way to locally scope the content of your CSS file. We can create a CSS module file by naming our CSS file as App.modules.css and then it can be imported inside App.js file using the special syntax mentioned below.

    **Syntax:

    import styles from './App.module.css';

    **42. Explain styled components in React?

    Styled-component Module allows us to write CSS within JavaScript in a very modular and reusable way in React. Instead of having one global CSS file for a React project, we can use styled-component for enhancing the developer experience. It also removes the mapping between components and styles – using components as a low-level styling construct

    The command to install styled components is

    npm i styled-components

    Using the below code we can custom style a button in React

    Javascript ``

    import styled from 'styled-components'

    const Button = styled.div width : 100px ; cursor: pointer ; text-decoration : none; export default Button;

    ``

    **43. What is prop drilling and its disadvantages?

    Prop drilling is basically a situation when the same data is being sent at almost every level due to requirements in the final level. The problem with Prop Drilling is that whenever data from the Parent component will be needed, it would have to come from each level, Regardless of the fact that it is not needed there and simply needed in last.

    44. What is conditional rendering in React?

    Conditional rendering in React is used when you want to render different UI elements based on certain conditions. For example, rendering a login button if a user is not logged in or rendering a logout button when the user is logged in.

    JavaScript `

    const isLoggedIn = true; return (

    {isLoggedIn ?Logout : Login}
    );

    `

    45. What are controlled components in React?

    Controlled components are React components where the form data is handled by the state within the component. The form element's value is controlled via the React state, making the form elements responsive to changes.

    For further reading, check out our dedicated article on **Intermediate ReactJS Intermediate Interview Questions. Inside, you’ll discover over 20 questions with detailed answers.

    React Interview Questions for Experienced

    Here, we cover **advanced react interview questions with answers for experienced professionals, who have over 5+ years of experience.

    **46. What is custom hooks in React?

    Custom hooks are normal JavaScript functions whose names start with “use” and they may call other hooks. We use custom hooks to maintain the DRY concept that is Don’t Repeat Yourself. It helps us to write a logic once and use it anywhere in the code.

    **47. How to optimize a React code?

    We can improve our react code by following these practices:

    **48. What is the difference between useref and createRef in React ?

    Here is the difference table of useref and createRef in React

    useRef createRef
    It is a hook. It is a function.
    It uses the same ref throughout the component's lifecycle. It creates a new ref every time component re-renders.
    It saves its value between re-renders in a functional component. It creates a new ref for every re-render.
    It returns a mutable ref object (i.e., can be changed). It returns a read-only ref object (cannot be modified directly).
    Used for accessing DOM elements, persisting values, or managing timers in functional components. Used for class components, especially when referencing DOM elements.
    const myRef = useRef(); const myRef = React.createRef();

    **49. What is react-redux?

    React-redux is a state management tool which makes it easier to pass these states from one component to another irrespective of their position in the component tree and hence prevents the complexity of the application. As the number of components in our application increases it becomes difficult to pass state as props to multiple components. To overcome this situation we use react-redux

    **50. What are benefits of using react-redux?

    They are several benfits of using react-redux such as:

    **51. Explain the core components of react-redux?

    There are four fundamental concepts of redux in react which decide how the data will flow through components

    **52. How can we combine multiple reducers in React?

    When working with Redux we sometimes require multiple reducers. In many cases, multiple actions are needed, resulting in the requirement of multiple reducers. However, this can become problematic when creating the Redux store. To manage the multiple reducers we have function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them.

    **Syntax

    import { combineReducers } from "redux"; const rootReducer = combineReducers({ books: BooksReducer, activeBook: ActiveBook });

    **53. Explain CORS in React?

    In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there.

    We can setup CORS evironment in frontend using two methods:

    **54. What is axios and how to use it in React?

    Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.

    To install axios package in react use the following command.

    npm i axios

    **55. Write a program to create a counter with increment and decrement?

    We can create the counter app with increment and decrement by writing the below code in the terminal:

    Javascript `

    import React, { useState } from "react";

    const App = () => { const [counter, setCounter] = useState(0) const handleClick1 = () => { setCounter(counter + 1) }

    const handleClick2 = () => {
        setCounter(counter - 1)
    }
    
    return (
        <div>
            <div>
                {counter}
            </div>
            <div className="buttons">
                <button onClick={handleClick1}>
                    Increment
                </button>
                <button onClick={handleClick2}>
                    Decrement
                </button>
            </div>
        </div>
    )

    }

    export default App

    `

    **Output:

    Animationkk

    Counter App using React

    **56. Explain why and how to update state of components using callback?

    It is advised to use a callback-based approach to update the state using setState because it solves lots of bugs upfront that may occur in the future.We can use the following syntax to update state using callback

    this.setState(st => { return( st.stateName1 = state1UpdatedValue, st.stateName2 = state2UpdatedValue ) })

    **57. What is React-Material UI?

    React Material UI is an open-source React component library, offering prebuilt components for creating React applications. Developed by Google in 2014, it's compatible with JavaScript frameworks like Angular.js and Vue.js. Renowned for its quality designs and easy customization, it's favored by developers for rapid development.

    **58. What is flux architecture in redux?

    Flux architecture in Redux is a design pattern used for managing application state in a unidirectional data flow. In this architecture, actions are dispatched to modify the store, which holds the entire application state. The store sends the updated state to the view (UI), and the cycle repeats when new actions are triggered. Redux follows this structure to ensure a predictable and maintainable state management system for large applications.

    59. What are custom hooks in React?

    Custom hooks are user-defined functions that use built-in hooks like useState, useEffect, etc., to reuse stateful logic across components. They allow you to extract and share common logic.

    60. How can you optimize React performance?

    Optimizing React performance can be achieved using:

    61. What is the Strict Mode in React?

    Strict Mode in React is a tool that helps developers find and fix problems in their app while developing. It only works in development and doesn’t affect the app when it’s running in production. When enabled, it checks for potential issues, such as old features that should no longer be used, and gives warnings to help avoid bugs.

    We can enable the strict mode by by wrapping your application or specific components inside the ****<React.StrictMode>**.

    JavaScript `

    import React from "react"; import ReactDOM from "react-dom";

    const App = () => { return (

    Hello, World!

    ); };

    ReactDOM.render( <React.StrictMode> </React.StrictMode>, document.getElementById("root") );

    `

    62. What is Redux and how does it work with React?

    Redux is a state management library that helps manage the application state globally. It uses actions, reducers, and a central store to control state. React-Redux is used to connect Redux state to React components.

    63. How does React handle concurrency?

    React's Concurrent Mode is a set of features that help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed. It allows React to interrupt rendering and prioritize high-priority tasks.

    64. How does React handle server-side rendering (SSR)?

    Server-side rendering (SSR) is the process of rendering a React application on the server and sending the fully rendered HTML to the client. This improves the initial page load performance and SEO.

    65. What are forms in React?

    In React, **forms are a way to capture user input, such as text fields, checkboxes, radio buttons, and buttons. React provides controlled and uncontrolled components for handling form elements, allowing developers to manage user input and form state in an efficient and structured way.

    66. How to create forms in React?

    Creating forms in React involves handling user input and managing the form's state. In React, form elements like , are controlled components, meaning their values are controlled by the React state.

    import React, { useState } from 'react';

    function MyForm() { // State to store input values const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState('');

    // Handle input change for each field
    const handleNameChange = (e) => setName(e.target.value);
    const handleEmailChange = (e) => setEmail(e.target.value);
    const handleMessageChange = (e) => setMessage(e.target.value);
    
    // Handle form submission
    const handleSubmit = (e) => {
        e.preventDefault();  // Prevent default form submission behavior
        console.log('Form submitted:', { name, email, message });
    };
    
    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label>Name:</label>
                <input type="text" value={name} onChange={handleNameChange} />
            </div>
            <div>
                <label>Email:</label>
                <input type="email" value={email} onChange={handleEmailChange} />
            </div>
            <div>
                <label>Message:</label>
                <textarea value={message} onChange={handleMessageChange} />
            </div>
            <button type="submit">Submit</button>
        </form>
    );

    }

    export default MyForm;

    `

    **Output:

    Screenshot-2025-03-06-162200

    React Form

    67. What is Lazy Loading in React?

    Lazy Loading in React is a technique used to load components only when they are needed, instead of loading everything at once when the app starts. This helps improve the performance of the app by reducing the initial loading time.

    In React, React.lazy() is used to implement lazy loading for components, which allows you to split your code into smaller bundles and load them only when required.

    68. How is React different from React Native?

    **React **React Native
    A JavaScript library for building user interfaces, primarily for web applications. A framework for building mobile applications using JavaScript and React.
    Focuses on developing web applications. Focuses on developing native mobile applications for iOS and Android.
    Renders HTML using the **Virtual DOM. Renders native mobile components using **native APIs (e.g., View, Text, Image).
    Uses **web technologies like HTML, CSS, and JavaScript. Uses **native mobile components and styles for building mobile UIs.
    Runs in the browser on a web server. Runs on mobile devices and communicates with native code.
    Can be deployed on browsers like Chrome, Firefox, etc. Can be deployed as native apps on iOS and Android platforms.

    69. What is Memoization in React?

    **Memoization in React is an optimization technique used to improve the performance of a component by preventing unnecessary re-renders. It involves caching the results of expensive function calls and reusing the cached result when the inputs to the function haven't changed. This is particularly useful when a component’s rendering process is slow, and you want to avoid recalculating or re-rendering unnecessarily.

    How Memoization Works in React:

    React provides two key APIs for memoization:

    1. React.memo(): This is a higher-order component (HOC) used to prevent re-renders of functional components if their props have not changed.
    2. useMemo(): A hook that memorizes the result of a computation and only recomputes it when its dependencies change.

    70. What is Reoncillation in React?

    **Reconciliation in React is the process of updating the **DOM when a component's state or props change. React uses the **Virtual DOM to efficiently determine what parts of the actual DOM need to be updated. Here's a simplified overview:

    Top 10 Commonly Asked ReactJS Interview Questions

    1. **What is React?
    2. **What are the key features of React?
    3. **What is the Virtual DOM, and how does it work?
    4. **What are React components?
    5. **What is the difference between a functional component and a class component in React?
    6. **What are React Hooks?
    7. **What is useState in React?
    8. **What are Custom Hooks?
    9. **What is JSX?
    10. **What is the difference between props and state in React?

    React Interview Questions and Answers | GeeksforGeeks

    Conclusion

    This **React Interview Questions and Answers covers a wide range of topics, from basic concepts to advanced techniques. Whether you're a **beginner or an experienced developer, mastering these questions will enhance your readiness for React interviews and boost your confidence.

    For further reading, check out our dedicated article on **Advanced ReactJS Intermediate Interview Questions. Inside, you’ll discover over 20 questions with detailed answers.