Home >> Interviews Q & A >> React.js Interview Questions and Answers

React.js Interview Questions and Answers

React.js Interview Questions: React.js is a JavaScript library for building user interfaces. It is written in JavaScript and maintained by Facebook.
React.js Interview Questions
Q:- What is React Js?
React js is an open-source JavaScript library created by Facebook for building complex and interactive UI in web and mobile applications.
Q:- What are the features of React Js?

Major features of React are listed below:

  1. Virtual DOM: It uses the Virtual DOM instead of the real DOM.
  2. Server-side rendering: It uses Server-side rendering.
  3. Uni-directional data flow: It follows Uni-directional data flow or data binding.
  4. Components: It uses reusable UI components.
Q:- What do you understand by Virtual DOM? Explain its working?
Virtual DOM is in-memory representation of Real DOM

In other words, A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM.

How Virtual DOM works:
  1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
  2. Now the difference between the previous DOM representation and the new one is calculated.
  3. Once the calculations are done, the real DOM will be updated with only the new things that have actually changed.
Q:- Difference between Real DOM and Virtual DOM?
Real DOM Virtual DOM
It updates slow. It updates faster.
It Can directly update HTML. It Can’t directly update HTML.
Creates a new DOM if element updates. Updates the JSX if element updates.
DOM manipulation is very expensive. DOM manipulation is very easy.
Too much of memory wastage. No memory wastage.
Q:- How to Install and Create React App?
Step-1: First, install react app creator.
For Windows:
>> npm install -g create-react-app
For Linux and Mac:
>> sudo npm install -g create-react-app
Step-2: Now, create a your project using react app.
>> create-react-app myFirstReactProject
Step-3: Now, go to the project folder & start the your app/project.
>> cd myFirstReactProject
>> npm start

Note - You can use other package manager like yarn etc.

Q:- What is the difference between NPM & NPX?

NPM: A node package manager

NPX: A npm package runner

Q:- How to specify a port to run a create-react-app based project?

If you don't want set environment variable, other option is modify scripts part of package.json

For Windows:
>> "start": "set PORT=3006 && react-scripts start"
For Linux & Mac:
>> "start": "PORT=3006 react-scripts start"

OR

>> "start": "export PORT=3006 react-scripts start"
Q: Does React js Use HTML?

No, It uses JSX which is simiar to HTML.

Q: What is JSX?
JSX stands for JavaScript XML.

Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax. React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it.

  • It is faster because it performs optimization while compiling code to JavaScript.

  • It is also type-safe and most of the errors can be caught during compilation.

  • It makes it easier and faster to write templates, if you are familiar with HTML.

class App extends React.Component {
  render() {
    return(
      

{'Welcome to React Js Interview Questions'}

) } }
How to write Expressions and Comments in JSX ?

JavaScript Expressions: We use {} to write expressions in JSX code.

Comments: While writing comments, we need to use curly brackets {}

 render() {
      return (
         

Expression & Comments in JSX:

5 is equeal to {2+3}

{//Single line Comment...} {/*Multi-line comment...*/}
); }
Q:- Why browsers can’t read JSX?

Browsers can only read JavaScript objects but JSX is not a regular JavaScript object. That's why browsers can't read JSX. To read JSX on browsers first of all we need to transform JSX code into a JavaScript object using Babel and then pass it to the browser.

Q:- What is state in React?
State of a component is an object that holds some information that may change over the lifetime of the component.
class Message extends React.Component {
  constructor(props) {
    super(props)
	
    this.state = {
      message: 'Welcome to React js Interview Questions.'
    }
  }

  render() {
    return (
      

{this.state.message}

) } }
Q:- What are props in React?

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

Q: What is the difference between state and props?

Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.

Q:- What is Components?
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation
There are mainly two types of Components:
  1. Functional Component OR Stateless Component - Only props, no state
  2. Class Component OR Stateful Component - Both props and state.
1. Functional Component: (Stateless)
function FunctionComponent(props) {
  return 

Hello, {props.name}

; } //In ES6 Style: const FunctionComponent = (props) => { return

Hello, {props.name}

; }
2. Class Component: (Stateful)
import React, { Component } from 'react';

class ClassComponent extends Component {
  render() {
    return (
      

Class Component

Welcome to React's - Class Component

); } } export default ClassComponent;
Note:
  • Always start component names with a capital letter.
  • React treats components starting with lowercase letters as DOM tags.
Q:- What is the difference between Controlled vs Uncontrolled Component?

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

Features Uncontrolled Controlled
One time value retrieval (e.g. on submit)
Validating on submit
Instant field validation
Conditionally disabling submit button
Dynamic Inputs
Q:- Adjacent JSX elements must be wrapped in an enclosing tag?

If you pass multiple tags then react will through error like - Adjacent JSX elements be wrapped in an enclosing tag

class HelloWorld extends React.Component{
	render(){
		return(
			
			
		)
	}
}

In above example, if you will pass data in render method like below, it will through error.

Reason: because render() method accept only JSX, so you can pass everthing in single tag. So following is the correct way to write it.

class HelloWorld extends React.Component{
	render(){
		return(
			
) } }
Q:- Why React component names must begin with a capital letter?

In JSX, lowercase tag names are considered to be HTML tags.

Q:- What is constructor? and main purpose of it?
The constructor for a React component is called before it is mounted.
Purpose of using Constructor:

Typically, in React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.
constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { loader: false };
  this.handleClick = this.handleClick.bind(this);
}

Note: When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Q:- Is it mandatory to define constructor for React component?

No, it is not mandatory. i.e, If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.

Q:- Difference between constructor and getInitialState ?

The difference between constructor and getInitialState is the difference between ES6 and ES5 itself.

getInitialState is used with React.createClass and constructor is used with React.Component.

ES5

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

ES6

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}
Q:- React ES6 Constructor and super keyword ?
  1. Do we need to call super() inside a constructor?
  2. The answer is YES, if you would like to set a property or access this inside the constructor you need to call super().

    class MyComponent extends React.Component {
    constructor(props){
    	this.name = "Jhon"; // Error-  'this' is not allowed before super()
    }
    render () {
    	return (
    		

    Name: { this.props.name }

    ); } }

    So now we are clear that we need to call super() if we need to use this inside the constructor.

  3. What is the deal with super() vs super(props) ?
  4. if you need to access the props inside the constructor of a class then you need to call super(props).

    class MyComponent extends React.Component {
    	constructor(props){
    		super();
    		this.state = {
    			name: this.props.name; // here props would be undefined.
    		};
    	}
    	render () {
    		return (
    			

    Name: { this.state.name }

    ); } }
    class MyComponent extends Component {
    	constructor(props){
    		super(props);
    		this.state = {
    			name: this.props.name; 
    		};
    	}
    	render () {
    		return (
    			

    Name: { this.state.name }

    ); } }
Q:- What is the difference between super() and super(props)?

When you want to access this.props inside the constructor then you need to pass the props parameter in super keyword.

Q:- What the major advantages of using React Js?

Folllowing are the list of some major advantages of using React Js:

  1. Performance : it is really good performance because React Js uses virtual-DOM
  2. Rendering : it's render server side and client side both as well
  3. Reusability: React Js is all about components. So React js provides developers with the opportunity to have more time to use and create common abstractions, setting up the creation, distribution and consumption of isolated reusable parts.
  4. JSX: JSX makes it easy to read the code of your components
  5. Data Binding: React Js uses one way data binding or uni directional data flow
  6. Testability: it is easy to test, and integrate some tools like jest.
  7. Maintainability: it ensures readability and makes maintainability easier.
  8. Better Combination Technologies: React makes best use of HTML and JavaScript mixing them ideally and also incorporates CSS to provide your business with the best.
  9. Integrate With Others Framework: it’s easy to integrate with other frameworks like Backbone.js, Meteor, Angular, etc.
Q:- In which component of lifecycle methods should one make an AJAX call?

Folllowing are the best libraries for making AJAX calls in React Js:

  1. Fetch - It is a new, promise based simple and standardised API to make AJAX calls and replace XMLHttpRequest.
  2. Axios - It Promise based HTTP client for the browser and node.js
  3. jQuery $.ajax - It is basic way to make AJAX calls.
  4. Superagent - It is a light weight AJAX API library created for better readability and flexibility.
You should fetch data in the componentDidMount() lifecycle method.
Q:- What is the use of render() function in React?
  1. render() is the most widely used method in react lifecycle.
  2. render method is required when you are writing a React component using as a class method.
  3. render() method called by default because it needs to display the HTML markup or we can say JSX syntax.
Q:- Why do we use Keys in React?

Keys help React identify which items have changed, are added, or are removed.

const friuts = [0 => "Apple", 1 => "Orange", 2 => "Banana", 3 => "Mango"];
const listItems = friuts.map((index, items) =>
  
  • {items}
  • );
    Q:- What are React Events?

    React Events are reactions which are triggered by specific user actions like Button Click, Mouse Hover, etc.

    Q:- How is React different from Angular?
    Keys React Angular
    Architecture Only the View of MVC Complete MVC
    Language JSX TypeScript
    Rendering Server side rendering Server side rendering (Angularjs - Client Side)
    DOM Uses virtual DOM Uses real/regular DOM
    Data Binding Uni-Directional: One-way data binding Bi-Directional: Two-way data binding
    Debugging Compile time debugging Run time debugging
    Learning Curve Low Medium
    Author Facebook Google
    Q:- What is Reconciliation?
    Reconciliation is the process through which React updates the DOM.

    In React.js, when a component's props or state change, React decides whether an Real DOM update is necessary by comparing the newly returned element with the previously rendered one with the help of Virtual DOM. When they are not equal, React will update the DOM. This process is called "reconciliation".

    The algorithm which react use behind this is called - Diffing Algorithm.

    Q:- ESLint and name some popular React-specific linters?
    • ESLint is a popular JavaScript linter.
    • Linting tools like ESLint allow developers to discover problems with their JavaScript code without executing it.
    • One of the most common for React is an npm package called eslint-plugin-react.

    Advantages of Using ESLint

    • You will find bugs and errors before they happen.
    • You will spend less time testing new features.
    • Your code (and your team’s code) will be more consistent.
    Q:- How can we find the version of React at runtime in the browser?
    const REACT_VERSION = React.version;
    
    Q:- What is Hooks? When and Where would I use a Hooks?
    Hooks:

    Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

    useState is a Hook that lets you add React state to function components.

    import React, { useState } from 'react';
    
    function myFunction() {
      // Code Snippets
    }
    
    When would I use a Hooks?

    If you are making a functional component and if you need to add/use state to inside that functional component, then you can use a Hook inside the existing functional component.

    Where would I use a Hooks?
    1. Hooks should be used only inside functional components.
    2. Hooks can be used inside your another own custom Hooks.
    Q:- What Debugging Tools are being used for Testing React Applications?
    1. Linters (eslint, jslint)
    2. Debuggers (React Developer Tools)
    Q:- What the major disadvantages of using React.js?

    Folllowing are the list of some major disadvantages of using React.js:

    1. It covers only 'View' part in MVC (Model-View-Controller).
    2. React Js is just a JavaScript library, Not a framework.
    3. It's library is very large and takes time to understand.
    4. it uses inline templating and JSX.

    React.js used by Facebook, Instagram, Netflix, PayPal, Apple etc. One of the most important reason may be it has very high demand in IT Industry. If you know Reactjs very well you can get very high Package. Learn React.js - React.js Tutorial

    Full Stack Tutorials

    Author @FullStackTutorials | View all Articles