Skip to main content

51 Best React Interview Questions and Answers

1) What Is React?
React is a fast, open-source, and front-end JavaScript library and It was developed by Facebook in 2011 for building complex, stateful and interactive UI in web as well as mobile Applications.

React follows the component based approach which helps you to building reusable and interactive web and mobile user interface (UI) components.

React has one of the largest communities supporting it.

The high level component Lifecycle -
At the highest level component Lifecycle, React components have lifecycle events that are -
1.      Initialization
2.      State/Property Updates
3.      Destruction

Explore to detail understanding  - React Lifecycle Components

Reactjs is very fast technology that can be trusted for complex tasks and can simply be trusted for quality outcomes.

2) When Reactjs released?
March 2013

3) What Is the current stable version of Reactjs?
The Version is - 18.

4) What Is the Repository URL of Reactjs?
https://github.com/facebook/react

5) How Is React different?
Basically, Reactjs is a limited library that is used for building interactive UI components. Also used for building complex and stateful web as well as mobile apps. But some of the other JavaScript frameworks not perform the same.

6) Why Reactjs Is used?
Reactjs is used to handle only the View part and not for others web apps as well as mobile apps.

7) What do you mean by Reactjs?
Reactjs is a fast, open-source, and front-end JavaScript library and I was developed by Facebook in 2011.

The main aim was to build the complex, stateful and interactive user interfaces for web as well as mobile apps.

8) What Are the features of React?
1.      JSX – The JSX is JavaScript Syntax Extension
2.      Components - The Reactjs is all about components
3.      One Direction Flow (Unidirectional Flux) - The React.js implements one-way data flow, which makes it easy to reason about your apps

The List of Major Features as following -
1.      React uses the virtual DOM instead of the real DOM.
2.      React uses server-side rendering.
3.      React follows unidirectional data-binding.

9) What Are the Advantages of Reactjs?
The List of Reactjs Advantages as following as -
1.      Reactjs uses virtual DOM which will improve performance of the apps.
2.      Reactjs is free and Open Source and very fast.
3.      Reactjs improves SEO Performance.
4.      It can be used for both client and server side.
5.      Also it can be used with other frameworks such as Angular, Meteor etc.
6.      It is very easy to write UI test cases because the virtual DOM system implemented entirely in JavaScript.
7.      It increases the application’s performance
8.      Reactjs code readability increases by using the JSX.

10) What Are the limitations of Reactjs?
Do you think Reactjs has any limitations? If so, tell a few?
Yes! There are some limitations (drawbacks) with this platform. The main drawback of the Reactjs is - size of its library.

It is very complex and creates lots of confusion, takes time to understand to the developers.
List of Limitations of Reactjs-
1.      Reactjs is just a library, not a framework
2.      The library of Reactjs is - very large
3.      Reactjs uses JSX for development.
4.      It creates lots of confusion to understand to developers
5.      Reactjs coding gets complex as it uses inline templating and JSX
6.      Reactjs uses only in view layer of the MVC frameworks.

11) Does Reactjs use HTML?
No!, Reactjs uses JSX (JavaScript XML) which is very similar to HTML.

12) What Is the life Cycle of Reactjs components?
1.      Initialization /Initial Rendering Phase
2.      State/Property Updates
3.      Destruction

13) What Is JSX?
JSX is stands for JavaScript XML.

This is a type of file used by Reactjs and It used in Reactjs as like HTML template syntax. The JSX makes applications robust and boosts its performance. This is simply integrates the HTML templates into the code of JavaScript.

It has become a very popular approach in the present scenario among the developers and browsers are not capable to read the code simply.

Below is an example of JSX -
class yourComponent extends React.Component {
  render() {
    var prop = this.props;

    return (
        <div className="mycompo">
          <a href={prop.url}>{prop.name}</a>
        </div>
      );
  }
}

14) Why can’t browsers read JSX?
Its follow the components approach. These components split-up the entire user interface (UI) into small independent and reusable pieces that means it renders each of these components independently without affecting the rest of the other user interface.

15) What Are the differences in between Real DOM and Virtual DOM?
Real DOM
1.      It updates slow as compare to Virtual DOM
2.      We can directly update the HTML on DOM at the run time.
3.      Will creates a new DOM, if element updates
4.      DOM manipulation is bit expensive
5.      There is too much memory wastage
Virtual DOM
1.      It updates faster as compare to Real DOM
2.      We can’t directly update the HTML on DOM at the run time.
3.      Will need to updates the JSX, if element updates
4.      DOM manipulation is easy as compare to the Real DOM.
5.      There is no memory wastage

16) Is it possible to nest JSX elements into other JSX elements?
Yes, it’s possible! The process is very similar to the nesting HTML elements.

17) What Is a state in Reactjs and how is it used?
The states are the heart and soul of Reactjs components. The states are objects, source of data which determine components rendering and its behavior.

The states are mutable and it used to create dynamic, stateful and interactive web and mobile components by using the - this.state().

18) What Are the Differentiate between stateful and stateless components?
Stateful Components
1.      The Stateful Components are stores the information about component’s state and have authority to change state.
2.      The Stateless components notify them about the requirement of the state change and send to props.
Stateless Component
1.      The Stateless components are used to calculates the internal state and do not have authority to change state.
2.      The Stateless components receive the props from the Stateful components and treat them as callback functions.

19) What Are the purpose of render() in React?
Each React component must have a render () functions and it returns a single Reactjs element, If more than one HTML element needs to be rendered. It must return the same result each time it is invoked.

20) What Is Props?
In Reactjs, Props are short hand for Properties.
Props are read-only components which must be kept pure. It is immutable.

21) What Are the difference between pros and state?
Props are short hand for properties and immutable while the state is mutable.

Props are read-only components while states are objects, source of data which determine components rendering and its behavior.

Both of them can update themselves easily.

22) Is it possible to display props on a parent component?
Yes, it is possible!

The best ways to perform this task is - using spread operator and also it can be done with listing the properties but it is a complex process.

23) What Are the lifecycle methods of Reactjs components?
 The lifecycle methods of the Reactjs are-
1.      componentWillMount() – This method executed just before rendering takes place both on the client and server.
2.      componentDidMount() – This method executed on the client side only after the first render.
3.      componentWillReceiveProps() – This method invoked as soon as the props are received from the parent class and before another render is called.
4.      shouldComponentUpdate() – This method returns true or false value based on certain conditions.
5.      componentWillUpdate() – This method called just before rendering takes place in the DOM.
6.      componentDidUpdate() – This method called immediately after rendering takes place.
7.      componentWillUnmount() – This method called after the component is unmounted from the DOM and used to clear the memory spaces.

24) What Is an event in React?
The events are the triggered reactions and it is very similar to handling events in DOM elements –
1.      Mouse Hover
2.      Mouse Click
3.      Key Press
4.      And too many

But there are only some syntactical differences and it looks like -
1.      Events are named using camel case instead of just using the lowercase.
2.      Events are passed as functions instead of strings.

The event argument contains a set of properties and its behavior that is accessed via its event handler only.

As an Example -
// In HTML
<button onclick="clickMe()">Click Me!</button>


As an Example -
//In React
class Display extends React.Component({   
    show(evt) {
        // TODO; your code  
    },  
    render() {     
        // Render the button with event - onClick
        return (
           <button onClick={this.show}> Click Me!</button>
        );   
    }
});



25) What Is Synthetic event?
The Synthetic Event is a cross browser wrapper around browser’s native event.

As an Example -
class DisplayAlert extends Component {
 
  alertMe() {
    alert("Hey, I am alert!");
  }

  render() {
    return (
      <button onClick={this.alertMe}>show alert </button>
    );
  }
}

export default DisplayAlert;


26) What Are the differences between Controlled and Uncontrolled Components?
Controlled Components
1.      The controlled components not maintain their own state.
2.      The data is controlled by the parent component.
Uncontrolled Components -
1.      The uncontrolled components maintain their own state.
2.      The data is controlled by the DOM

27) What Is Higher Order Components (HOC)?
Higher Order Component (HOC) is patterns, pure, and custom components that is derived from Reactjs compositional nature and provide advanced ways of reusing your components logic.

28) What can you do with HOC?
Higher Order Component (HOC) can be used for -
1.      Code reusability
2.      State abstraction and manipulation
3.      Bootstrap abstraction
4.      Props manipulation
5.      Render High jacking
6.      And may more

29) What Is Component in Reactjs?
Components are the heart of Reactjs and components let us split the user interface (UI) into independent, reusable pieces.

Create a new component class using React.createClass. When you create a new components call, you must implement render() function.

The example for the components is -
var HiMsg = React.createClass({
  render: function() {
    return <div>Hello, My name is - {this.props.name}</div>;
  }
});

ReactDOM.render(
  <HiMsg name="msg" />,
  document.getElementById('container')
);

30) What Is Controllable Component in Reactjs?
A controlled component is a component where React is in control and takes the value through Props and changes are notified to the parent component through callbacks.

Parent component controls this component either by passing the data and handling the callbacks and managing its own state.

31) What Is Uncontrollable Component in Reactjs?
Uncontrollable component is a component which stores its own state internally.

32) What Are Pure Components?
Pure components are the simplest and fastest components which can be written and it can replace any component which only has a render ().

These components increase the performance and code simplicity of the application.

33) How to update the State of the Component in Reactjs?
In the Reactjs, you can update the State of the components by using the method – setState()

34) What Are the Component Life Cycle methods in Reactjs?
The list of Component Life Cycle Methods -
1.      constructor() method
2.      componentWillMount() method
3.      componentDidMount() method
4.      render() method
5.      componentWillUpdate() method
6.      componentDidUpdate() method
7.      componentWillUnMount() method

35) What Are the methods called when Component is created or while inserting it to DOM?
The list Methods as following -
1.      constructor() method
2.      componentWillMount() method
3.      render() method
4.      componentDidMount() method

36) What Are the methods called when State or Props of the Component is changed?
The list Methods as following -
1.      componentWillReceiveProps()
2.      shouldComponentUpdate()
3.      componentWillUpdate()
4.      render()
5.      componentDidUpdate()

37) In which lifecycle event do you make AJAX requests and why?
The Ajax requests should go away in the componentDidMount life-cycle event.

38) What Is React Router?
React Router is a powerful routing library built on top of React, which helps in adding new screens, developing single page application and flows to the application.

React Router keeps the URL in sync with data which displayed on the web page and also maintains a standardized structure and behavior.

React Router has a simple API.

39) Why do we need a Router in Reactjs?
A Router is used to define multiple routes and when a user types a specific URL.
We need to add a Router library in your apps that allows you to creating multiple routes with each leading to us a unique view.

40) When would you use a Class Component over a Functional Component?
If your component has state, a lifecycle methods or a class component, you should use a functional component.

41) What Is difference between setState and forceUpdate () and findDOMNode () in Reactjs?
1.      setState() - It is used to update the state of the component. It will only add changes to the original state.
2.      forceUpdate() - It is used to forceUpdate the state of the component. It will only update to the original state.
3.      findDOMNode() - It is used to forceUpdate the state of the component. It will only update to the original state.

42) How to use Loop in Reactjs?

let rows = [];
for (var i = 0; i &lt; numrows; i++) {
    rows.push(<objectrow key="{i}">);
}

return tbody(rows);  </objectrow>


43) How to set focus in Reactjs?

class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
 
  render() {
    return(
      <div>
      <input defaultvalue="Won't focus" />
        <input ref="{(input)" /> { this.nameInput = input; }}
          defaultValue="will focus"
        /&gt;
      </div>
      );
  }
}

44) What Are the components in Flux architecture?
1.      Action
2.      Dispatcher
3.      Store
4.      View

45) What Are the popular libraries used for Flux?
1.      Redux
2.      Reflux
3.      Alt

46) What Are refs in React and why are they important?
Refs are used to return the reference to our element and allow you to get direct access to DOM elements.

Refs should be avoided but they are useful when you adding the methods to components.

As an Example -

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("My Input Value is -", this.input.value)
  }

  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type='text' ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

47) What Are keys in React and why are they important?
React keep track of what items have changed, been added and been removed from a list.

As an Example -
render () {
  return (
    <ul>
      {
        this.state.todoItems.map(({task, uid}) => {
        return <li key={uid}>{task}</li>
      })}
    </ul>
  )


48) What Is React Lifecycle Components?
In React, each component has a life-cycle which manipulate during its three main phases.

The following three phases are:
1.      Mounting
2.      Updating
3.      Unmounting

React does so by “Mounting” (adding nodes to the DOM), “Unmounting” (removing them from the DOM), and “Updating” (making changes to nodes already in the DOM).

Mounting - Lifecycle Phase 1
Mounting is used for adding nodes (elements) to the DOM.

The React has four built-in methods that gets called, in this order, when mounting a component -
1.      constructor()
2.      getDerivedStateFromProps()
3.      render()
4.      componentDidMount()

Note –
1)      The render() method is required and It always be called and the others methods are optional (you will call if needed of them).
2)      These methods are considered legacy and you should avoid them in new code:
·       UNSAFE_componentWillMount()

The Constructor Method -
The constructor() method is called when the component is initiated (before anything else). Here we can set up the initial state and other initial values.

The constructor() method is called with the props, as arguments and we should always start by calling the super(props) before initiated anything else.

As an Example,
import React from 'react';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {msg: "welcome!"};
  }
  render() {
    return (
      <h2>{this.state.msg} you anil</h2>
    );
  }
}

The getDerivedStateFromProps Method -
The getDerivedStateFromProps() method is called before rendering the elements in the DOM.

The getDerivedStateFromProps() method is called right before the render method and after the constructor method.

We can set the state object based on the initial props and it takes state as an argument, and returns an object with changes to the state.

We can update the constructor state in the getDerivedStateFromProps() method.

As an Example,
public class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {msg: "welcome!"};
  }

  static getDerivedStateFromProps(propsstate) {
    return {msg: props.yourMsg };
  }

  render() {
    return (
      <h1>{this.state.msgyou anil</h1>
    );
  }
}

The Render Method -
The render () method is used to display the actual outputs HTML to the DOM.
The render () method is required and this method has to return something whether it is null.

When Render method is called?
When render method is called it returns a new virtual DOM structure of the component.

As an Example,
import React from 'react';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {msg: "welcome!"};
  }
  render() {
    return (
      <h2>{this.state.msg} you anil</h2>
    );
  }
}

As an another Example,

public class Header extends React.Component {
  render() {
    return (
      <h2>This one is a Header component</h2>
    );
  }
}


The componentDidMount Method -
The componentDidMount method is called after the component is rendered.
The componentDidMount method is called exactly once and when The component has been initialized.

The componentDidMount method is used for -
1.      Handling the AJAX requests - GET/POST/PUT/DELETE
2.      Set timers using setTimeout or setInterval
3.      Set timers using setInterval

As an Example,
public class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {msg: "welcome!"};
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({msg: "welcome you Anil"})
    }, 1000)
  }

  render() {
    return (
      <h2>{this.state.msg}</h2>
    );
  }
}

Updating Lifecycle Phase 2
A component is updated whenever there is a change in the component's state or props.

These methods are called in the following order when a component is being re-rendered:
1)      getDerivedStateFromProps()
2)      shouldComponentUpdate()
3)      render()
4)      getSnapshotBeforeUpdate()
5)      componentDidUpdate()

Note:
1)      The render() method is required and will always be called, the others are optional and will be called if you define them.
2)      These methods are considered legacy and you should avoid them in new code:
o   UNSAFE_componentWillUpdate()
o   UNSAFE_componentWillReceiveProps()

The getDerivedStateFromProps Method -
The getDerivedStateFromProps() method is called first when a component gets updated. This is still the natural place to set the state object based on the initial props.

After changes the color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the color attribute, the color is still rendered as yellow. 

See the below example,

class Header extends React.Component {
    constructor(props) {
      super(props);
      this.state = {color: "red"};
    }

    static getDerivedStateFromProps(propsstate) {
      return {color: props.color };
    }

    changeColor = () => {
      this.setState({color: "blue"});
    }

    render() {
      return (
        <div>
        <h1>Your Color is {this.state.ecolor}</h1>
        <button type="button" onClick={this.changeColor}>Change this color</button>
        </div>
      );
    }
  }
  
  ReactDOM.render(<Header favcol="yellow"/>document.getElementById('root'));


Result of this example is – Your color is Yellow

The shouldComponentUpdate Method -
The shouldComponentUpdate() method is invoked before rendering (render method) when new props or state are being received.

The defaults value is true.

The shouldComponentUpdate() method is not called for the initial render or when forceUpdate() is used.

As an Example 1–

When shouldComponentUpdate value is fale? My Color is red after click on Change color.

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

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {color: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Color is {this.state.color}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />document.getElementById('root'));


Result of this example is – My color is red

As an Example 2–

When shouldComponentUpdate value is true? My Color is blue after click on Change color.

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

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {color: "red"};
  }

  shouldComponentUpdate() {
    return true;
  }

  changeColor = () => {
    this.setState({color: "blue"});
  }

  render() {
    return (
      <div>
      <h1>My Color is {this.state.color}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />document.getElementById('root'));


Result of this example is – My color is blue

The Render Method -
The render() method is the only required method in a class component.

The render() method is called when a component gets updated and re-render the HTML to the DOM including the new changes.

Note: The render() will not be invoked if shouldComponentUpdate() returns false.

As an Example,
class Header extends React.Component {
    constructor(props) {
      super(props);
      this.state = {color: "red"};
    }
    changeColor = () => {
      this.setState({color: "blue"});
    }
    render() {
      return (
        <div>
            <h2>My Color is {this.state.color}</h2>
            <button type="button" onClick={this.changeColor}>Change color</button>
        </div>
      );
    }
  }

Result of this example is – My color is blue

The getSnapshotBeforeUpdate Method -
The getSnapshotBeforeUpdate() method is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error.

The componentDidUpdate Method -
The componentDidUpdate() method is called after the component is updated in the DOM. This method is not called for the initial render

Note: The componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.

Unmounting Lifecycle Phase 3
The Unmounting is used when a component is removed from the DOM.

React has only one built-in method that is called when a component is unmounted.
1.      componentWillUnmount

The componentWillUnmount Method -
The componentWillUnmount() method is called when the component is removed from the DOM.

As an Example,
// container class
public class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }

  deleteHeader = () => {
    this.setState({show: false});
  }

  render() {
    let header;
    if (this.state.show) {
      header = <Child />;
    };
    return (
      <>
      <div>
        <p>{header}</p>
        <button type="button" onClick={this.deleteHeader}>Delete My Header</button>
      </div>
    );
  }
}

//Child class
public class Child extends React.Component {
  componentWillUnmount() {
    console.log("This component Header is unmounted.");
  }

  render() {
    return (
      <h1>Hello Anil!</h1>
    );
  }
}
By Anil Singh | Rating of this article (*****)

Popular posts from this blog

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from ...

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVA...

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin...

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan ...

55 Best TypeScript Interview Questions and Answers - JavaScript!

What Is TypeScript? By definition, "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript." TypeScript is a superset of JavaScript which provides optional static typing, classes and interfaces. => The TypeScript was first made public in the year 2012. => Typescript is a modern age JavaScript development language. => TypeScript is a strongly typed, object oriented, compiled language. => TypeScript was designed by Anders Hejlsberg (designer of C#) at Microsoft. => TypeScript is both a language and a set of tools. As an Example of TypeScript, class Hello {     msg : string ;      constructor ( message : string ) {          this . msg = message ;      }       getMsg () {          return "Hello, " + this . msg ;      } } TypeScript introduced a great deal...