Interview-Questions-Img

Top 30 ReactJS Interview Questions and Answers- 2024

With new technologies being introduced every now and then, selecting the best and right technology for app and web development is getting more and more challenging. However, ReactJS has successfully evolved as the fastest-growing JavaScript library and is a buzzword in the industry today. 

It is the most popular front-end technology used by some of the biggest companies worldwide. As JavaScript is making firm roots in the market, React is becoming one of the most in-demand technologies. Companies are looking for proficient React developers to handle their projects, and aspirants are seeking reliable React certification courses to upskill themselves.

If you want to pursue a career in React and are preparing for an upcoming interview, then you have landed in the right place. Here are the top 30 ReactJS interview questions and answers that will help you improve your knowledge and prepare better. Also check out the full ReactJS Tutorial to get a grasp of the core concepts.

React Interview Questions for Experienced

To update the state of a component, use this.setState().

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (                                 
<div>

<h1>Hello {this.state.name}</h1>
<h2>Your Id is {this.state.id}</h2>
                   </div>
            );
        }
    }

ReactDOM.render(

   <MyComponent/>, document.getElementById('content')

The important methods for lifecycle of React components are as follows:

  • componentWillReceiveProps(): It is invoked immediately after the props are received from the parent class but before another render is called.

  • getInitialState(): It is executed before creating the component.  

  • componentDidMount(): It is executed on the client side when the component gets rendered the first time and placed on the DOM.

  • componentWillMount(): It is executed on the client and server-side right before the rendering.

  • shouldComponentUpdate(): It is invoked after the component determines changes to the DOM. It returns true or false values based on a few conditions. By default, it returns false. 

  • componentDidUpdate(): It is invoked right after rendering.

  • componentWillUnmount(): It is invoked before a component is unmounted from the DOM and is used to clear the memory space.

  • componentWillUpdate(): It is invoked just before rendering occurs in the DOM.

In React, a higher-order component (HOC) is a function acting as a container for other components. Thus, keeping components simple and enabling reusability. It takes a component as an argument and returns a new one with additional props. 

HOC allows reusing a common logic across multiple components. It is not a part of React but a pattern in React to reuse component logic. Examples of HOC are connected HOC from react-redux and withRouter HOC from react-router

We use HOC in the following cases:

  • Abstract behaviour and state to be reused across the application.

  • We want to share a common logic across multiple components, such as authorisation and data fetching.

  • Render a component inside another one and pass props to the wrapped component.

A functional component is a simple JavaScript function. It takes props and returns a React element. On the other hand, a class component is a JS class extending the React.Component. It has a render method to return a React element. 

Moreover, a functional component can’t have local state and lifecycle methods, whereas a class component can. However, React 16.8 allows the functional component to have a state using hooks. 

Another difference is that a functional component is simpler, easier to test and understand, and ensures better performance as compared to a class component. The latter comes in handy when we want to use local state or lifecycle methods.

 

Class Components

Functional Components

State

Can have a local state

Cannot have a local state

Reusability

Can be reused

Cannot be reused

Simplicity

It is more complicated than the stateless component.

Comparatively easier to understand. 

Lifecycle methods

It can work with all lifecycle methods.

It can’t work with any lifecycle method.

Redux is an open-source library in JavaScript that is used to manage the state of an application. React uses Redux to create UI. It is a predictable state container used for JS applications and is used for the state management of an entire application. 

Components of Redux are:

  • Action: It is the source information for the store.

  • Store: It stores the state of the application.

  • Reducer: It specifies how the state of an application changes due to actions sent to the store.

React Router is a powerful routing library used to create routes in React. It is built on top of React and helps to add new screens and flows to the app. Hence, keeping the URL in sync with the data displayed on the web page.

React Router allows you to build a single-page web application using React with navigation and you don’t need to refresh the page while navigating. Moreover, it ensures a standardised structure ad behaviour. 

It uses the component structure to call the components and use it to show appropriate information. Considering that React is a component-based framework, you don’t have to use this package as it is compatible with other routing libraries as well. 

The major components of React Router are as follows:

  • Routes: It is a new component introduced in React v6.

  • BrowserRouter: This router implementation uses HTML5 history API (popstate, pushstate, and event replacestate) to keep UI in sync with the URL. It is the parent component used to store other components.

  • Link: It is used to create links to different routes between its path and to implement navigation over the application. It works somewhat like the anchor tag in HTML.

  • Route: It renders some UI whenever there is a match between the path and current URL.

React Routing

Conventional Routing

Single HTML page.

Each view corresponds to a new HTML file.

The user navigates multiple views in the same file.

The user navigates multiple pages for each view.

Enhanced performance.

Compratiely slower performance.


The change is in only the History attribute. 


An HTTP request is sent to the server and the corresponding HTML page is received.

No page refresh as it is a single file.

The page refreshes each time a user navigates.

A router is used to define multiple routes. When a user mentions a specific URL, which matches the path of any of the routes defined within the router, the user is redirected to that route. So, you must add a Router library to your app to create multiple routes, each learning to a unique view. 

  • A router enables multiple views within one app by defining multiple routes in an application.

  • It ensures consistent structure and behaviour.

  • It is used to develop single-page web applications. 

  • You don’t have to set the History value manually. In React Router v4, you just need to wrap routes within the component.

  • Its API is all about components. A Router is a single root component enclosing the child routes.

  • There are three packages, one each for Native, Web, and Core. This supports the compact size of your application and is easy to switch over according to a similar coding style. 

Redux

Flux

It is an open-source JavaScript library that is used to manage application State.

It is an architecture rather than a framework or library.

Immutable state of store.

Mutable state of store.

Store and change logic are different. 

The store includes state and change logic.

Can have a single store.

Can have multiple stores.

The single store has hierarchical reducers.

Stores are disconnected and flat.

No concept of a dispatcher but uses the reducer concept. 

Singleton dispatcher

Moderate ReactJS Developer Interview Questions

React forms allow users to interact with web applications and enter the necessary details whenever required. Forms in React contain various elements, such as buttons, text fields, radio buttons, checkboxes, etc., and are used for different tasks, including searching, authentication, indexing, filtering, and more.  

These React forms are similar to HTML forms, but the difference is that in React, the state property of the component contains the state, which is updated via setState(). So, elements are not able to update their state directly, and the JavaScript function handles their submission. The JS function can access data entered by the user in the form. 

Here is how forms are created in React:

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}

render() {
    return (          
<form onSubmit={this.handleSubmit}>
            <label>
                Name:
                <input type="text" value={this.state.value} onChange={this.handleSubmit} />
            </label>
            <input type="submit" value="Submit" />
        </form>
    );
}

Components in React are the foundation of any React application UI, and every single app consists of multiple components. Each component is a piece of UI that splits it up into small independent and reusable pieces that can be processed separately. After that, it renders each component independently without affecting the rest of the user interface. 

React includes the following two types of components:

  • Functional Components: They have no state and include only render methods. Hence, they are also known as stateless components. Functional components may derive data from other components as properties or props. 

  • Class Components: They can hold and manage their state and contain a separate render method to return JSX on the screen. They can have their own state and are also known as stateful components. 

Each React component must have a render() function. It returns a single React element representing the native DOM component. 

If it is needed to render more than one element, they must be grouped together inside one parent or enclosing tag, such as <div>, <form>, <group>, etc. This function in React must be kept pure, which means it must return the same result every time it is invoked.

State in React is a built-in object containing information about the component. It is the heart of React components and a source of data that must be kept as simple as possible. We can say that state determines components' behaviour and rendering. 

The state can change over time, and when it changes, the component re-renders. Any change in the state can occur due to user action or system-generated events. States are mutable and create interactive and dynamic components. You can access it via this.state().

 

React

React Native

Release

2013

2015

Platform

Web

Mobile – Android, iOS

CSS

Yes

No

HTML

Yes

No

Prerequisites

JavaScript, HTML, CSS

ReactJS

 

State

Props

Use

Holds details and information regarding the components.

It allows you to pass data from one component to another as an argument.

Stateless Components

Can’t have state.

Can have props.

Read-Only

It can be changed.

It is read-only.

Mutability

Mutable

Immutable

Child Components

Can’t access.

Can access 

Basic ReactJS Interview Questions

React is an open-source JavaScript library used to develop user interfaces for single-page applications. It was developed by Facebook in 2011 and is used by several large-scale companies for their applications. 

It has a component-based approach and is a great option for building complex and reusable UI components of web and mobile apps. React was open-sourced in 2015, but it has managed to build one of the largest communities, and it constantly supports it and stays active.

Key Points about React:

  • It uses virtual DOM instead of real DOM because real DOM manipulations can be expensive.

  • React supports server-side rendering.

  • It uses reusable UI components to develop the view.

  • It follows unidirectional data binding, which means data flows in one direction.

Know more in detail about what is ReactJS.

Following are the key features of ReactJS:

  • Components: 

A single-page application has multiple components, which lay the foundation of a React app. React splits UI into multiple independent and reusable parts or components, and each can be processed separately. 

  • Unidirectional Data Binding

Unidirectional or one-way data flow means that you nest child components within parent components while designing a React app. React follows unidirectional data binding, which keeps everything fast and modular. 

  • JSX

JSX is a JavaScript syntax extension used with React to define how the user interface should look like. JSX enables us to write HTML structures in the same file containing JS code.

  • High Performance

React update only changed components rather than updating all of them. This ensures the faster performance of web applications.

  • Virtual DOM

Virtual DOM is a lightweight representation of the real DOM. Whenever there is a change in the state of an object, the virtual DOM changes only that particular object in the real DOM instead of changing all the objects.

These are the pros and cons of using ReactJS in web development:

Advantages

  • In React, component-based architecture is used to develop applications. The components used are independent, reusable, and can be shared across different applications with similar functionalities. When you reuse the components, it improves the development pace.

  • React has a gentle and easy learning curve than other frameworks like Angular. Even beginners with little knowledge of JavaSCript can work on React and use it to build applications.

  • React allows developers to choose libraries, tools, and architecture to develop applications.

  • React uses virtual DOM for rendering. So, every time there is a change in React app, a new virtual DOM is created, which is way faster than rendering the user interface within the browser. Hence, improving the efficiency of the app.

  • Developers can use React to create engaging UI that is easy to navigate in several search engines. It enables server-side rendering, which enhances the SEO of React app. 

Disadvantages

  • React has an extensive library, so you need time to understand it.

  • It is just a library and not a full-blown framework.

  • As React uses inline templating and JSX, coding can get complicated.

  • It is a bit difficult for beginners to understand React.

  • It has numerous components, and you need time to master them.

JSX in ReactJS stands for JavaScript XML, or we can say it is a syntax extension of JavaScript. JSX is a type of file that React uses to combine the expressiveness of JavaScript and HTML. 

Hence, making the HTML file much easier to understand and enhancing the performance of applications. Moreover, it describes what UI should look like and allows us to write HTML structure within the file containing JS code. Also, it helps us place it within the DOM without using functions such as createElement() or appendChild(). 

Web browsers can’t reach JSX directly as they are built to read only regular JavaScript objects, and JSX is not that. To enable a web browser to read JSX, we must transform the file into a regular JavaScript object using JSX transformers, such as Babel. Then we pass it to the browser.

In Virtual DOM, DOM stands for Document Object Model and represents an HTML document that has a logical tree structure. Each branch of this tree ends in a node, each containing objects. 

A virtual DOM is a JavaScript object which is a lightweight copy of real DOM. This node tree lists the elements along with their attributes and content as objects and their properties. The render function of React creates a node tree out of the React components and updates the tree in return to mutations on the data model caused due to several actions of the user or system. 

Whenever there is a change in the state of an object, the virtual DOM changes only that specific object in the real DOM instead of updating all the objects. 

This Virtual DOM follows the three simple steps:

  • Whenever there is a change in the underlying data, the entire user interface is re-rendered in virtual DOM representation. 

  • Calculation of difference between the previous DOM representation and the new one.

  • After the calculation, the real DOM is updated with just the objects or things that have actually changed. 

React uses two virtual DOMs to render UI. One is used to store the current state of objects, while the other is used to store the previous state of objects. When there is an update in the virtual DOM, react compares the two virtual DOMs to know which objects have been updated. 

Once it knows, React renders the objects within the real DOM rather than rendering the complete real DOM. This is how React ensures efficient updating by using the virtual DOM.

Following the steps you need to follow to create a React application:

  • Install Node.JS on your computer system, as you will need NPM to install the React library. NPM stands for Node Package Manager, which includes many JavaScript libraries, such as React.

  • Now, install the create-react-app package by using the command prompt or terminal.

  • You can install any text editor based on your preference, such as Sublime Text or VS Code.

React offers several benefits over other frameworks like Angular. Following are the reasons to select it instead of other options:

  • Reusable Components

For any React application, components are the building blocks. Any single app comprises multiple components, which have their logic and controls. You can reuse these components through the application, which will reduce the time consumed in app development.

  • Development of Dynamic Apps Made Easy

With React, creating dynamic applications is much easier as it demands less coding and offers enhanced functionality. On the other hand, JavaScript applications demand complex coding.

  • Unidirectional Data Flow

In React, data flows in one way, so while designing an app, you nest child components within parent components. As the data flows in one direction, it is easier to debug errors and find where the problem is in an application.

  • Enhanced Performance

Virtual DOM compares the previous state of an application and updates components in real DOM with a changed or updated state instead of updating all the components like conventional applications. As React uses virtual DOM, web applications created in React perform faster. 

  • Dedicated Debugging Tools

You can use Facebook’s newly released extension to debug React applications. This will make the debugging process faster and more convenient.

The syntax of ES5 and ES6 are different from each other in various aspects.

  • export vs exports

//ES5
module.exports = Component;

// ES6
export default Component;
  • require vs import

//ES5
var React = require('react');

//ES6
import React from 'react';
  • component and function

// ES5
var MyComponent = React.createClass({
    render: function() {
        return
 
<h3>Hello Edureka!</h3>
;
    }
});
 
// ES6
class MyComponent extends React.Component {
    render() {
        return
 
<h3>Hello Edureka!</h3>
;
    }
}
  • state

// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
 
<h3>Hello, {this.state.name}!</h3>
;
    }
});
 
// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
 
<h3>Hello, {this.state.name}!</h3>
;
    }
}
  • props

// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
Hello, {this.props.name}!
;
    }
});

// ES6
class App extends React.Component {
    render() {
        return
Hello, {this.props.name}!
;
    }
}

In React, an event is a triggered reaction to certain actions, such as mouse click, mouse hover, key press, etc. We can handle these events the same way we handle events in DOM elements. 

However, there are a few differences between them, which are as follows:

  • These events are passed as functions and not strings.

  • Events in React are named using camel case instead of lowercase. 

  • The event argument includes a set of properties specific to that event. Each event has its properties and behaviour, which we can access using its event handler.

Here is how you can create an event in React:

class Display extends React.Component({    
    show(evt) {
        // code   
    },   

    render() {      
        // Render the div with an onClick prop (value is a function)        
        return (            
<div onClick={this.show}>Click Me!</div>
        );    
    }
});

 

ReactJS Props are the short form of Properties. Props work similarly to HTML attributes. They are in-built objects used to store the values of attributes of a tag. They are inputs to a React component and provide a way to pass data from one component to another. They are passed the same way arguments are passed in a function. 

Props can be single-valued or objects with a set of values to pass to components of React while creating a naming convention that looks similar to an HTML tag attribute. Therefore, we can conclude that props are the data passed from a parent component to a child component. 

Props provide various component functionalities, including:

  • Triggering state changes,

  • Passing custom data to React components.

Keys in ReactJS are special string attributes that must be included while using lists of elements. They are used to identify unique virtual DOM elements with their corresponding data driving the user interface. Keys enable React to optimise rendering by recycling existing elements in the DOM. 

Keys need to be a unique string or number so that React can use them to reorder elements rather than re-rendering them. Hence, improving the performance of the application.

Significance of Keys in React

  • When given to array elements, keys provide a unique identity to each element.

  • Hence, a key is considered a unique identifier used to identify the items that have changed, been deleted or updated.

  • It is used to display a list of data coming from an API.

  • It helps to find which components must be re-rendered rather than re-rendering all the components each time. 

  • Keys can’t understand the uniqueness or order of each element without keys.

  • Keys help React get an idea of which element was edited, deleted, and added.

An arrow function is a shortcut way to write a function to React. It is a brief syntax to write a function expression. An arrow function is also known as a fat arrow (=>) and allows binding the context of components properly, as ES6 auto binding is unavailable by default. 

It is not required to bind ‘this’ in the constructor while using the arrow function, as it prevents bugs due to the use of ‘this’ in React callbacks. 

Arrow functions are primarily used when working with higher-order functions. 

  • Without Arrow Function (General way)

render() {    
    return(
        <MyInput onChange={this.handleChange.bind(this) } />
    );
}
  • With Arrow Function

render() {  
    return(
        <MyInput onChange={ (e) => this.handleOnChange(e) } />
    );
}

 

React

Angular

Author

Facebook

Google

DOM

Virtual DOM

Real DOM

Debugging

Compile-time debugging

Runtime debugging

Data-Binding

Uni-directional or one-way binding

Bi-directional or two-way binding

Architecture

View layer of MVC

Complete MVC

Rendering

Server-side

Client-side

Performance

Faster Due To Virtual Dom

Comparatively Slow

Synthetic events in React are the objects acting as a cross-browser wrapper around the native event of a browser. They combine the responses of different browsers into one API so that events show consistent properties across different browsers. So, an application stays consistent irrespective of the browser it is running in.