Top React JS Interview Questions and Answers

Last updated on Feb 16 2022
Manohar Sharma

Table of Contents

What are the features of React?

1 2 JSX:  JSX is a syntax extension to JavaScript. It is used with React to describe what the user interface should look like. By using JSX, we can write HTML structures in the same file that contains JavaScript code.
2 2 Components: Components are the building blocks of any React application, and a single app usually consists of multiple components. It splits the user interface into independent, reusable parts that can be processed separately.
3 Virtual DOM: React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, virtual DOM changes only that object in the real DOM, rather than updating all the objects.
4 One-way data-binding: React’s one-way data binding keeps everything modular and fast. A unidirectional data flow means that when designing a React app, you often nest child components within parent components.
5 High performance: React updates only those components that have changed, rather than updating all the components at once. This results in much faster web applications.

What is an event in React?

An event is an action that a user or system may trigger, such as pressing a key, a mouse click, etc.

  • React events are named using camelCase, rather than lowercase in HTML.
  • With JSX, you pass a function as the event handler, rather than a string in HTML.

Button onPress={lightItUp}

What is arrow function in React? How is it used?

The Arrow function is the new feature of the ES6 standard. If you need to use arrow functions, it is not necessary to bind any event to ‘this.’ Here, the scope of ‘this’ is global and not limited to any calling function. So If you are using Arrow Function, there is no need to bind ‘this’ inside the constructor. It is also called ‘fat arrow ‘(=>) functions.

//General way

render() {

return(

<MyInput onChange={this.handleChange.bind(this) } />

);

}

//With Arrow Function

render() {

return(

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

);

}

What is an event in React?

An event is an action which triggers as a result of the user action or system generated event like a mouse click, loading of a web page, pressing a key, window resizes, etc. In React, the event handling system is very similar to handling events in DOM elements. The React event handling system is known as Synthetic Event, which is a cross-browser wrapper of the browser’s native event.

Handling events with React have some syntactical differences, which are:

  • React events are named as camelCase instead of lowercase.
  • With JSX, a function is passed as the event handler instead of a string.

How do you create an event in React?

We can create an event as follows.

class Display extends React.Component({

show(msgEvent) {

// code

},

render() {

// Here, we render the div with an onClick prop

return (

<div onClick={this.show}>Click Me</div>

);

}

});

Example

import React, { Component } from 'react';

class App extends React.Component {

constructor(props) {

super(props);

this.state = {

companyName: ''

};

}

changeText(event) {

this.setState({

companyName: event.target.value

});

}

render() {

return (

<div>

<h2>Simple Event Example</h2>

<label htmlFor="name">Enter company name: </label>

<input type="text" id="companyName" onChange={this.changeText.bind(this)}/>

<h4>You entered: { this.state.companyName }</h4>

</div>

);

}

}

export default App;

What are synthetic events in React?

A synthetic event is an object which acts as a cross-browser wrapper around the browser’s native event. It combines the behavior of different browser’s native event into one API, including stopPropagation() and preventDefault().

In the given example, e is a Synthetic event.

function ActionLink() {

    function handleClick(e) {

        e.preventDefault();

        console.log('You had clicked a Link.');

    }

    return (

        <a href="#" onClick={handleClick}>

              Click_Me

        </a>

    );

}

what is the difference between controlled and uncontrolled components?

The difference between controlled and uncontrolled components are:

SN Controlled Uncontrolled
1. It does not maintain its internal state. It maintains its internal states.
2. Here, data is controlled by the parent component. Here, data is controlled by the DOM itself.
3. It accepts its current value as a prop. It uses a ref for their current values.
4. It allows validation control. It does not allow validation control.
5. It has better control over the form elements and data. It has limited control over the form elements and data.

 

Explain the Lists in React.

Lists are used to display data in an ordered format. In React, Lists can be created in a similar way as we create it in JavaScript. We can traverse the elements of the list using the map() function.

Example

import React from 'react';

import ReactDOM from 'react-dom';

function NameList(props) {

  const myLists = props.myLists;

  const listItems = myLists.map((myList) =>

    <li>{myList}</li>

  );

  return (

    <div>

        <h2>Rendering Lists inside component</h2>

              <ul>{listItems}</ul>

    </div>

  );

}

const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa'];

ReactDOM.render(

  <NameList myLists={myLists} />,

  document.getElementById('app')

);

export default App;

How are forms created in React?

Forms allow the users to interact with the application as well as gather information from the users. Forms can perform many tasks such as user authentication, adding user, searching, filtering, etc. A form can contain text fields, buttons, checkbox, radio button, etc.

React offers a stateful, reactive approach to build a form. The forms in React are similar to HTML forms. But in React, the state property of the component is only updated via setState(), and a JavaScript function handles their submission. This function has full access to the data which is entered by the user into a form.

import React, { Component } from 'react';  

  

class App extends React.Component {  

  constructor(props) {  

      super(props);  

      this.state = {value: ''};  

      this.handleChange = this.handleChange.bind(this);  

      this.handleSubmit = this.handleSubmit.bind(this);  

  }  

  handleChange(event) {  

      this.setState({value: event.target.value});  

  }  

  handleSubmit(event) {  

      alert('You have submitted the input successfully: ' + this.state.value);  

      event.preventDefault();  

  }  

  render() {  

      return (  

          <form onSubmit={this.handleSubmit}>  

            <h1>Controlled Form Example</h1>  

            <label>  

                Name:  

                <input type="text" value={this.state.value} onChange={this.handleChange} />  

            </label>  

            <input type="submit" value="Submit" />  

         </form>  

      );  

  }  

}

How do you create an event in React?

A React event can be created by doing the following:

6

What are synthetic events in React?

  • Synthetic events combine the response of different browser’s native events into one API, ensuring that the events are consistent across different browsers.
  • The application is consistent regardless of the browser it is running in. Here preventDefault is a synthetic event.

7

Explain how lists work in React

  • We create lists in React as we do in regular JavaScript. Lists display data in an ordered format
  • The traversal of lists is done using the map() function

8

Why is there a need for using keys in Lists?

Keys are very important in lists for the following reasons:

  • A key is a unique identifier and it is used to identify which items have changed, been updated or deleted from the lists
  • It also helps to determine which components need to be re-rendered instead of re-rendering all the components every time. Therefore, it increases performance, as only the updated components are re-rendered

What are forms in React?

React employs forms to enable users to interact with web applications.

  • Using forms, users can interact with the application and enter the required information whenever needed. Form contain certain elements, such as text fields, buttons, checkboxes, radio buttons, etc
  • Forms are used for many different tasks such as user authentication, searching, filtering, indexing, etc

How do you create forms in React?

We create forms in React by doing the following:

9

The above code will yield an input field with the label Name and a submit button. It will also alert the user when the submit button is pressed.

10

How do you write comments in React?

There are basically two ways in which we can write comments:

  • Single-line comments

11

  • Multi-line comments

12

What is an arrow function and how is it used in React?

  • An arrow function is a short way of writing a function to React.
  • It is unnecessary to bind ‘this’ inside the constructor when using an arrow function. This prevents bugs caused by the use of ‘this’ in React callbacks.

13

How is React different from React Native?

React React Native
Release 2013 2015
Platform Web Mobile – Android, iOS
HTML Yes No
CSS Yes No
Prerequisites JavaScript, HTML, CSS React.js

How is React different from Angular?

Angular React
Author Google Facebook
Architecture Complete MVC View layer of MVC
DOM Real DOM Virtual DOM
Data-Binding Bi-directional Uni-directional
Rendering Client-Side Server-Side
Performance Comparatively slow Faster due to Virtual DOM

What are the components in React?

Components are the building blocks of any React application, and a single app usually consists of multiple components. A component is essentially a piece of the user interface. It splits the user interface into independent, reusable parts that can be processed separately.

There are two types of components in React:

14

  • Functional Components:  These types of components have no state of their own and only contain render methods, and therefore are also called stateless components. They may derive data from other components as props (properties).
function Greeting(props) {

return <h1>Welcome to {props.name}</h1>;

}
  • Class Components:  These types of components can hold and manage their own state and have a separate render method to return JSX on the screen. They are also called Stateful components as they can have a state.
class Greeting extends React.Component {

render() {

return <h1>Welcome to {this.props.name}</h1>;

}

}

What is the use of render() in React?

  • It is required for each component to have a render() function. This function returns the HTML, which is to be displayed in the component.
  • If you need to render more than one element, all of the elements must be inside one parent tag like <div>, <form>.

15

What is a state in React?

  • The state is a built-in React object that is used to contain data or information about the component. The state in a component can change over time, and whenever it changes, the component re-renders.
  • The change in state can happen as a response to user action or system-generated events. It determines the behavior of the component and how it will render.

What are props in React?

  • Props are short for Properties. It is a React built-in object that stores the value of attributes of a tag and works similarly to HTML attributes.
  • Props provide a way to pass data from one component to another component. Props are passed to the component in the same way as arguments are passed in a function.

How do you pass props between components?

17

What are the differences between state and props?

State Props
Use Holds information about the components Allows to pass data from one component to other components as an argument
Mutability Is mutable Are immutable
Read-Only Can be changed Are read-only
Child components Child components cannot access Child component can access
Stateless components Cannot have state Can have props

What is a higher-order component in React?

A higher-order component acts as a container for other components. This helps to keep components simple and enables re-usability. They are generally used when multiple components have to use a common logic.

What are the differences between class and functional components?

Class Components Functional Components
State Can hold or manage state Cannot hold or manage state
Simplicity Complex as compared to the stateless component Simple and easy to understand
Lifecycle methods Can work with all lifecycle methods Does not work with any lifecycle method
Reusability Can be reused Cannot be reused
  • Class components example:

18

  • Functional components example:

19

Explain the lifecycle methods of components.

  • getInitialState():  This is executed before the creation of the component.
  • componentDidMount():  Is executed when the component gets rendered and placed on the DOM.
  • shouldComponentUpdate():  Is invoked when a component determines changes to the DOM and returns a “true” or “false” value based on certain conditions.
  • componentDidUpdate():  Is invoked immediately after rendering takes place.
  • componentWillUnmount():  Is invoked immediately before a component is destroyed and unmounted permanently.

What is Redux?

Redux is an open-source, JavaScript library used to manage application state. React uses Redux to build the user interface. It is a predictable state container for JavaScript applications and is used for the entire application’s state management.

What are the components of Redux?

  • Store:  Holds the state of the application.
  • Action:  The source information for the store.
  • Reducer:  Specifies how the application’s state changes in response to actions sent to the store.

20

What is the Flux?

  • Flux is the application architecture that Facebook uses for building web applications. It is a method of handling complex data inside a client-side application and manages how data flows in a React application.

20

  • There is a single source of data (the store) and triggering certain actions is the only way way to update them.The actions call the dispatcher, and then the store is triggered and updated with their own data accordingly.

21

  • When a dispatch has been triggered, and the store updates, it will emit a change event that the views can rerender accordingly.

22

How is Redux different from Flux?

SN Redux Flux
1. Redux is an open-source JavaScript library used to manage application State Flux is an architecture and not a framework or library
2. Store’s state is immutable Store’s state is mutable
3. Can only have a single-store Can have multiple stores
4. Uses the concept of reducer Uses the concept of the dispatcher

What is React Router?

React Router is a routing library built on top of React, which is used to create routes in a React application.

Why do we need to React Router?

  • It maintains consistent structure and behavior and is used to develop single-page web applications.
  • Enables multiple views in a single application by defining multiple routes in the React application.

How is React routing different from conventional routing?

SN React Routing Conventional routing
1. Single HTML page Each view is a new HTML file
2. The user navigates multiple views in the same file The user navigates multiple files for each view
3. The page does not refresh since it is a single file The page refreshes every time user navigates
4. Improved performance Slower performance

How do you implement React routing?

We can implement routing in our React application using this method:

Considering we have the components App, About, and Contact in our application:

23

How do you style React components?

There are several ways in which we can style React components:

  • Inline Styling

24

  • JavaScript Object

25

  • CSS Stylesheet

26

Explain the use of CSS modules in React.

  • The CSS module file is created with the .module.css extension
  • The CSS inside a module file is available only for the component that imported it, so there are no naming conflicts while styling the components.

27

Differentiate between Real DOM and Virtual DOM.

Real DOM vs Virtual DOM
Real DOM Virtual DOM
1. It updates slow. 1. It updates faster.
2. Can directly update HTML. 2. Can’t directly update HTML.
3. Creates a new DOM if element updates. 3. Updates the JSX if element updates.
4. DOM manipulation is very expensive. 4. DOM manipulation is very easy.
5. Too much of memory wastage. 5. No memory wastage.

What is React?

  • React is a front-end JavaScript library developed by Facebook in 2011.
  • It follows the component-based approach which helps in building reusable UI components.
  • It is used for developing complex and interactive web and mobile UI.
  • Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.

What are the features of React?

Major features of React are listed below:

  1. It uses the virtual DOM instead of the real DOM.
  2. It uses server-side rendering.
  3. It follows uni-directional data flow or data binding.

List some of the major advantages of React.

Some of the major advantages of React are:

  1. It increases the application’s performance
  2. It can be conveniently used on the client as well as server side
  3. Because of JSX, code’s readability increases
  4. React is easy to integrate with other frameworks like Meteor, Angular, etc
  5. Using React, writing UI test cases become extremely easy

What are the limitations of React?

Limitations of React are listed below:

  1. React is just a library, not a full-blown framework
  2. Its library is very large and takes time to understand
  3. It can be little difficult for the novice programmers to understand
  4. Coding gets complex as it uses inline templating and JSX

What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){

return(

<div>

<h1> Hello World from Tecklearn!!</h1>

</div>

);

}

What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.
This Virtual DOM works in three simple steps.

1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
28

2. Then the difference between the previous DOM representation and the new one is calculated.

29

3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.

30

Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

How different is React’s ES6 syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in following aspects:
1. require vs import

// ES5

var React = require('react');

// ES6

import React from 'react';

2. export vs exports

// ES5

module.exports = Component;

// ES6

export default Component;

3. component and function

// ES5

var MyComponent = React.createClass({

render: function() {

return

<h3>Hello Tecklearn!</h3>

;

}

});




// ES6

class MyComponent extends React.Component {

render() {

return

<h3>Hello Tecklearn!</h3>

;

}

}

4. props

// ES5

var App = React.createClass({

propTypes: { name: React.PropTypes.string },

render: function() {

return

<h3>Hello, {this.props.name}!</h3>

;

}

});


// ES6

class App extends React.Component {

render() {

return

<h3>Hello, {this.props.name}!</h3>

;

}

}

5. 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>

;

}

}

How is React different from Angular?

React vs Angular
TOPIC REACT ANGULAR
1. ARCHITECTURE Only the View of MVC Complete MVC
2. RENDERING Server-side rendering Client-side rendering
3. DOM Uses virtual DOM Uses real DOM
4. DATA BINDING One-way data binding Two-way data binding
5. DEBUGGING Compile time debugging Runtime debugging
6. AUTHOR Facebook Google

 

“In React, everything is a component.” Explain.

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

What is the purpose of render() in React.

Each React component must have a render() mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div> etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

How can you embed two or more components into one?

We can embed components into one in the following way:
class MyComponent extends React.Component{

render(){

return(

<div>

<h1>Hello</h1>

<Header/>

</div>

);

}

}

class Header extends React.Component{

render(){

return

<h1>Header Component</h1>
};

}

ReactDOM.render(

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

);

What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e., immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

Differentiate between states and props.

States vs Props
Conditions State Props
1. Receive initial value from parent component Yes Yes
2. Parent component can change value No Yes
3. Set default values inside component Yes Yes
4. Changes inside component Yes No
5. Set initial value for child components Yes Yes
6. Changes inside child components No Yes

How can you update the state of a component?

State of a component can be updated using 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')

);

What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow(=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

//General way

render() {

return(

<MyInput onChange={this.handleChange.bind(this) } />

);

}

//With Arrow Function

render() {

return(

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

);

Differentiate between stateful and stateless components.

Stateful vs Stateless
Stateful Component Stateless Component
1. Stores info about component’s state change in memory 1. Calculates the internal state of the components
2. Have authority to change state 2. Do not have the authority to change state
3. Contains the knowledge of past, current and possible future changes in state 3. Contains no knowledge of past, current and possible future state changes
4. Stateless components notify them about the requirement of the state change, then they send down the props to them. 4. They receive the props from the Stateful components and treat them as callback functions.

What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:

Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.
Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.
Unmounting Phase: This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

  1. componentWillMount()  – Executed just before rendering takes place both on the client as well as server-side.
  2. componentDidMount() – Executed on the client side only after the first render.
  3. componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.
  4. shouldComponentUpdate() – Returns true or false value based on certain conditions. If you want your component to update, returntrueelse returnfalse. By default, it returns false.
  5. componentWillUpdate() – Called just before rendering takes place in the DOM.
  6. componentDidUpdate() – Called immediately after rendering takes place.
  7. componentWillUnmount()– Called after the component is unmounted from the DOM. It is used to  clear up the memory spaces.

What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences 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, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

How do you 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>

);

}

});

What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

display() {

const name = this.inputDemo.value;

document.getElementById('disp').innerHTML = name;

}

render() {

return(

<div>

Name: <input type="text" ref={input => this.inputDemo = input} />

<button name="Click" onClick={this.display}>Click</button>

<h2>Hello <span id="disp"></span> !!!</h2>

</div>

);

}

}

List some of the cases when you should use Refs.

Following are the cases when refs should be used:

  • When you need to manage focus, select text or media playback
  • To trigger imperative animations
  • Integrate with third-party DOM libraries

How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

//ChildComponent.jsx

export default class ChildComponent extends React.Component {

render() {

return(

<div>

<h1>This is a child component</h1>

</div>

);

}

}

 

//ParentComponent.jsx

import ChildComponent from './childcomponent.js';

class ParentComponent extends React.Component {

render() {

return(




<div>

<App />

</div>

);

}

}

How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.

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>

);

}

What do you know about controlled and uncontrolled components?

Controlled vs Uncontrolled Components
Controlled Components Uncontrolled Components
1. They do not maintain their own state 1. They maintain their own state
2. Data is controlled by the parent component 2. Data is controlled by the DOM
3. They take in the current values through props and then notify the changes via callbacks 3. Refs are used to get their current values

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

What are Higher Order Components (HOC)?

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

What can you do with HOC?

HOC can be used for many tasks like:

  • Code reuse, logic and bootstrap abstraction
  • Render High jacking
  • State abstraction and manipulation
  • Props manipulation

What are Pure Components?

Pure components are the simplest and fastest components which can be written. They can replace any component which only has a render().
These components enhance the simplicity of the code and performance of the application.

What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:

  • DOM manipulation was very expensive
  • Applications were slow and inefficient
  • There was huge memory wastage
  • Because of circular dependencies, a complicated model was created around models and views

Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

31

What is Redux?

Redux is one of the most trending libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

What are the three principles that Redux follows?

  1. Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
  2. State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data.
  3. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.

32

What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

List down the components of Redux.

Redux is composed of the following components:

  1. Action– It’s an object that describes what happened.
  2. Reducer–  It is a place to determine how the state will change.
  3. Store– State/ Object tree of the entire application is saved in the Store.
  4. View– Simply displays the data provided by the Store.

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

Show how the data flows through Redux?

33

How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:

function addTodo(text) {

return {

type: ADD_TODO,

text

}

}

Explain the role of Reducer.

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

How is Redux different from Flux?

Flux vs Redux
Flux Redux
1. The Store contains state and change logic 1. Store and change logic are separate
2. There are multiple stores 2. There is only one store
3. All the stores are disconnected and flat 3. Single store with hierarchical reducers
4. Has singleton dispatcher 4. No concept of dispatcher
5. React components subscribe to the store 5. Container components utilize connect
6. State is mutable 6. State is immutable

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

What are the advantages of Redux?

Advantages of Redux are listed below:

  • Predictability of outcome –Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.
  • Maintainability –The code becomes easier to maintain with a predictable outcome and strict structure.
  • Server-side rendering –You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.
  • Developer tools –From actions to state changes, developers can track everything going on in the application in real time.
  • Community and ecosystem –Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.
  • Ease of testing –Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.
  • Organization –Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.

What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

Why is switch keyword used in React Router v4?

Although a <div> is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch> tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.

Why do we need a Router in React?

A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.

<switch>

<route exact path=’/’ component={Home}/>

<route path=’/posts/:id’ component={Newpost}/>

<route path=’/posts’   component={Post}/>

List down the advantages of React Router.

Few advantages are:

  1. Just like how React is based on components, in React Router v4, the API is ‘All About Components’. A Router can be visualized as a single root component (<BrowserRouter>) in which we enclose the specific child routes (<route>).
  2. No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the<BrowserRouter>component.
  3. The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It is easy to switch over based on a similar coding style.

How is React Router different from conventional routing?

Conventional Routing vs React Routing
Topic Conventional Routing React Routing
PAGES INVOLVED Each view corresponds to a new file Only single HTML page is involved
URL CHANGES A HTTP request is sent to a server and corresponding HTML page is received Only the History attribute is changed
FEEL User actually navigates across different pages for each view User is duped thinking he is navigating across different pages

What are the advantages of using React?

MVC is generally abbreviated as Model View Controller.

  • Use of Virtual DOM to improve efficiencyReact uses virtual DOM to render the view. As the name suggests, virtual DOM is a virtual representation of the real DOM. Each time the data changes in a react app, a new virtual DOM gets created. Creating a virtual DOM is much faster than rendering the UI inside the browser. Therefore, with the use of virtual DOM, the efficiency of the app improves.
  • Gentle learning curveReact has a gentle learning curve when compared to frameworks like Angular. Anyone with little knowledge of javascript can start building web applications using React.
  • SEO friendlyReact allows developers to develop engaging user interfaces that can be easily navigated in various search engines. It also allows server-side rendering, which boosts the SEO of an app.
  • Reusable componentsReact uses component-based architecture for developing applications. Components are independent and reusable bits of code. These components can be shared across various applications having similar functionality. The re-use of components increases the pace of development.
  • Huge ecosystem of libraries to choose fromReact provides you the freedom to choose the tools, libraries, and architecture for developing an application based on your requirement.

What is JSX?

JSX stands for JavaScript XML.
It allows us to write HTML inside JavaScript and place them in the DOM without using functions like appendChild( ) or createElement( ).
As stated in the official docs of React, JSX provides syntactic sugar for React.createElement( ) function.

**Note- We can create react applications without using JSX as well.

Let’s understand how JSX works:

Without using JSX, we would have to create an element by the following process:

const text = React.createElement('p', {}, 'This is a text');

const container = React.createElement('div','{}',text );

ReactDOM.render(container,rootElement);

Using JSX, the above code can be simplified:

const container = (

<div>

<p>This is a text</p>

</div>

);

ReactDOM.render(container,rootElement);

As one can see in the code above, we are directly using HTML inside JavaScript.

What are the differences between functional and class components?

Before the introduction of Hooks in React, functional components were called stateless components and were behind class components on feature basis. After the introduction of Hooks, functional components are equivalent to class components.
Although functional components are the new trend, the react team insists on keeping class components in React. Therefore, it is important to know how these both components differ.
On the following basis let’s compare functional and class components:

  • DecalarationFunctional components are nothing but JavaScript functions and therefore can be declared using an arrow function or the function keyword:
function card(props){

return(

<div className="main-container">

<h2>Title of the card</h2>

</div>

)

}

const card = (props) =>{

return(

<div className="main-container">

<h2>Title of the card</h2>

</div>

)

}

Class components on the other hand, are declared using the ES6 class:

class Card extends React.Component{

constructor(props){

super(props);

}
render(){

return(

<div className="main-container">

<h2>Title of the card</h2>

</div>

)

}

}


  • Handling props
    Let’s render the following component with props and analyse how functional and class components handle props:
  • <StudentInfo name=”Vivek” rollNumber=”23″ />

In functional components, the handling of props is pretty straight forward. Any prop provided as an argument to a functional component, can be directly used inside HTML elements:

function StudentInfo(props){

return(

<div className="main">

<h2>{props.name}</h2>

<h4>{props.rollNumber}</h4>

</div>

)

}

In the case of class components, props are handled in a different way:

class StudentInfo extends React.Component{constructor(props){

super(props);

}

render(){

return(

<div className="main">

<h2>{this.props.name}</h2>

<h4>{this.props.rollNumber}</h4>

</div>

)

}

}

As we can see in the code above, this keyword is used in the case of class components.

Handling state
Functional components use React hooks to handle state.
It uses the useState hook to set state of a variable inside the component:

function ClassRoom(props){

let [studentsCount,setStudentsCount] = useState(0);

const addStudent = () => {

setStudentsCount(++studentsCount);

}

return(

<div>

<p>Number of students in class room: {studentsCount}</p>

<button onClick={addStudent}>Add Student</button>

</div>

)

}

Since useState hook returns an array of two items, the first item contains the current state, and the second item is a function used to update the state.
In the code above, using array destructuring we have set the variable name to studentsCount with a current value of “0” and setStudentsCount is the function that is used to update the state.
For reading the state, we can see from the code above, the variable name can be directly used to read the current state of the variable.
We cannot use React Hooks inside class components, therefore state handling is done very differently in a class component:
Let’s take the same above example and convert it into a class component:

class ClassRoom extends React.Component{

constructor(props){

super(props);

this.state = {studentsCount : 0};

this.addStudent =

this.addStudent.bind(this);

}

addStudent(){

this.setState((prevState)=>{ return 

{studentsCount: prevState.studentsCount++}

});

}

render(){

return(

<div>

<p>Number of students in classroom: {this.state.studentsCount}</p>

<button onClick={this.addStudent}>Add Student</button>

</div>

)

}

}

In the code above, we see we are using this.state to add the variable studentsCount and setting the value to “0”.
For reading the state, we are using this.state.studentsCount.
For updating the state, we need to first bind the addStudent function to this. Only then, we will be able to use the setState function which is used to update the state.

What is the virtual DOM? How does react use the virtual DOM to render the UI?

As stated by the react team, virtual DOM is a concept where a virtual representation of the real DOM is kept inside the memory and is synced with the real DOM by a library such as ReactDOM.

34

Why was virtual DOM introduced?

DOM manipulation is an integral part of any web application, but DOM manipulation is quite slow when compared to other operations in JavaScript.
The efficiency of the application gets affected when several DOM manipulations are being done. Most JavaScript frameworks update the entire DOM even when a small part of the DOM changes.
For example, consider a list that is being rendered inside the DOM. If one of the items in the list changes, the entire list gets rendered again instead of just rendering the item that was changed/updated. This is called inefficient updating.
To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.

How does it work?

35

For every DOM object, there is a corresponding virtual DOM object(copy), which has the same properties.
The main difference between the real DOM object and the virtual DOM object is that any changes in the virtual DOM object will not reflect on the screen directly. Consider a virtual DOM object as a blueprint of the real DOM object.
Whenever a JSX element gets rendered, every virtual DOM object gets updated.

**Note- One may think updating every virtual DOM object might be inefficient, but that’s not the case. Updating the virtual DOM is much faster than updating the real DOM since we are just updating the blueprint of the real DOM.

React uses two virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the previous state of the objects.
Whenever the virtual DOM gets updated, react compares the two virtual DOMs and gets to know about which virtual DOM objects were updated.
After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM.
This way, with the use of virtual DOM, react solves the problem of inefficient updating.

What are the differences between controlled and uncontrolled components?

Controlled and uncontrolled components are just different approaches to handling input form elements in react.

Feature Uncontrolled Controlled Name attrs
One-time value retrieval (e.g. on submit) ✔️ ✔️ ✔️
Validating on submit ✔️ ✔️ ✔️
Field-level Validation ✔️ ✔️
Conditionally disabling submit button ✔️ ✔️
Enforcing input format ✔️ ✔️
several inputs for one piece of data ✔️ ✔️
dynamic inputs ✔️ 🤔

Controlled component

In a controlled component, the value of the input element is controlled by React.
We store the state of the input element inside the code, and by using event-based callbacks, any changes made to the input element will be reflected in the code as well.
When a user enters data inside the input element of a controlled component, onChange function gets triggered and inside the code we check whether the value entered is valid or invalid. If the value is valid, we change the state and re-render the input element with new value.
Example of a controlled component:

function FormValidation(props) {

let [inputValue, setInputValue] = useState("");

let updateInput = e => {

setInputValue(e.target.value);

};

return (

<div>

<form>

<input type="text" value={inputValue} onChange={updateInput} />

</form>

</div>

);

}

As one can see in the code above, the value of the input element is determined by the state of the inputValue variable. Any changes made to the input element is handled by the updateInput function.

Uncontrolled component

In an uncontrolled component, the value of the input element is handled by the DOM itself.
Input elements inside uncontrolled components work just like normal HTML input form elements.
The state of the input element is handled by the DOM. Whenever the value of the input element is changed,event-based callbacks are not called. Basically, react does not perform any action when there are changes made to the input element.
Whenever use enters data inside the input field, the updated data is shown directly. To access the value of the input element, we can use ref .
Example of an uncontrolled component:

function FormValidation(props) {

let inputValue = React.createRef();

let handleSubmit = e => {

alert(`Input value: ${inputValue.current.value}`);

e.preventDefault();

};

return (

<div>

<form onSubmit={handleSubmit}>

<input type ="text" ref={inputValue} />

<button type ="submit">Submit</button>

</form>

</div>

);

}

As one can see in the code above, we are not using onChange function to govern the changes made to the input element. Instead, we are using ref to access the value of the input element.

What are the different lifecycle methods in React?

Every component in React has lifecycle methods that we can tap into, to trigger changes at a particular phase of the life cycle.
Each component in react goes through three phases: Mounting, Updating , and Unmounting.

There are corresponding lifecycle methods for each of the three phases:

36

Mounting:

There are four built-in lifecycle methods that are called in the following order when a component is mounted:

constructor( ) – This is called before anything else. We can set the initial state of the component inside this method. The constructor method is used to set the initial state and bind methods to the component.

getDerivedStateFromProps( )– This is called before rendering the elements in the DOM.
In this method, we can set the state of the component based on the props we received. This method is used very rarely.

render( )– This is the only required method in the class component. This method returns the HTML elements which are going to be rendered inside the DOM.

componentDidMount( )– It is called right after the component is rendered inside the DOM. All the statements which require the DOM nodes can be executed in this method. Network requests from a remote end-point can also be instantiated in this method.

Updating:

Updates in react are caused by changes in state or props. Update leads to re-rendering of the component. The following methods are called when a component is re-rendered:

getDerivedStateFromProps( )– This method is called again when a component is being re-rendered.

shouldComponentUpdate( )– This method is called before rendering the component when new props are received. It lets React know if the component’s output is affected by the newly received props or by the state change. By default, it returns true.

render( )– To re-render the HTML inside the DOM, the render( ) method gets called again.

getSnapshotBeforeUpdate( ) – This method is called just before the newly rendered HTML gets committed to the DOM. It stores the previous state of the component so that React has an idea of what parts of the DOM needs to be updated.

componentDidUpdate( ) – It is called after the component gets re-rendered. This method works just like the componentDidMount( ) method, the difference is that this method does not get called on initial render.

Unmounting:

componentWillUnmount( ) – This method is called just before the component gets destroyed. Any clean up statements should be executed inside this method.

Explain Strict Mode in React.

StrictMode is a tool added in the version 16.3 of React to highlight potential problems in an application. It performs additional checks on the application.

function App() {

return(

<React.StrictMode>

<div classname="App">

<Header />

<div>

Page Content

</div>

<Footer/>

</div>

</React.StrictMode>

);

}

To enable StrictMode, <React.StrictMode> tags need to be added inside the application:

import React from "react";

import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");

ReactDOM.render(

<React.StrictMode>

<App />

</React.StrictMode>,

rootElement

);

StrictMode currently helps with the following issues:

  • Identifying components with unsafe lifecycle methodsCertain lifecycle methods are unsafe to use in asynchronous react applications. With the use of third-party libraries it becomes difficult to ensure that certain lifecycle methods are not used.
    StrictMode helps in providing us a warning if any of the class components uses an unsafe lifecycle method.
  • Warning about the usage of legacy string APIIf one is using an older version of React, callback ref is the recommended way to manage refs instead of using the string refs. StrictMode gives a warning if we are using string refs to manage refs.
  • Warning about the usage of findDOMNodePreviously, findDOMNode( ) method was used to search the tree of a DOM node. This method is deprecated in React. Hence, the StrictMode gives us a warning about the usage of this method.
  • Warning about the usage of legacy context API (because the API is error-prone)

How to prevent re-renders in React?

Reason for re-renders in React: Re-rendering of a component and it’s child components occur when props or state of the component has been changed.
Re-rendering components that are not updated, affects the performance of an application.

How to prevent re-rendering:

Consider the following components:

class Parent extends React.Component {

state = { messageDisplayed: false };

componentDidMount() {

this.setState({ messageDisplayed: true});

}

render() {

console.log("Parent is getting rendered");

return(

<div className="App">

<Message />

</div>

);

}

}

class Message extends React.Component {

constructor(props) {

super(props);

this.state = { message: "Hello, this is vivek" };

}

render() {

console.log("Message is getting rendered");

return(

<div>

<p>{this.state.message}</p>

</div>

);

}

}

Parent component is the parent component and Message is the child component. Any change in the parent component will lead to re-rendering of the child component as well.
To prevent the re-rendering of child component, we use the shouldComponentUpdate( ) method:

**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s a static component.

class Message extends React.Component {

constructor(props) {

super(props);

this.state = { message: "Hello, this is vivek" };

}

shouldComponentUpdate() {

console.log("Does not get rendered");

return false;

}

render() {

console.log("Message is getting rendered");

return(

<div>

<p>{this.state.message}</p>

</div>

);

}

}

As one can see in the code above, we have returned false from the shouldComponentUpdate( ) method, which prevents the child component from re-rendering.

Explain React state and props.

Props State
Immutable Owned by its component
Has better performance Locally scoped
Can be passed to child components Witeable/Mutable
has setState() method to modify properties
Changes to state can be asynchronous
can only be passed as props

React State

Every component in react has a built-in state object, which contains all the property values that belong to that component.
In other words, the state object controls the behaviour of a component. Any change in the property values of the state object leads to re-rendering of the component.

**Note- State object is not available in functional components but, we can use React Hooks to add state to a functional component.

How to declare a state object?

Example:

class Car extends React.Component{

constructor(props){

super(props);

this.state = {

brand: "BMW",

color: "black"

}

}

}

How to use and update the state object?

class Car extends React.Component {

constructor(props) {

super(props);

this.state = {

brand: "BMW",

color: "Black"

};

}

changeColor() {

this.setState(prevState => {

return { color: "Red" };

});

}

render() {

return (

<div>

<button onClick={() => this.changeColor()}>Change Color</button>

<p>{this.state.color}</p>

</div>

);

}

}

 

As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property using setState method.
React Props
Every react component, accepts a single object argument called props (which stands for “properties”).
These props can be passed to a component using HTML attributes and the component accepts these props as an argument.
Using props, we can pass data from one component to another.
Passing props to a component:
While rendering a component, we can pass the props as a HTML attribute:

<Car brand="Mercedes"/>

The component receives the props:
In Class component:

class Car extends React.Component {

constructor(props) {

super(props);

this.state = {

brand: this.props.brand,

color: "Black"

};

}

}

In Functional component:

function Car(props) {

let [brand, setBrand] = useState(props.brand);

}

Explain React Hooks.

What are Hooks? Hooks are functions that let us “hook into” React state and lifecycle features from a functional component.
React Hooks cannot be used in class components. They let us write components without class.

Why were Hooks introduced in React?
React hooks were introduced in the 16.8 version of React.
Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods.
The need to change a functional component to a class component, whenever state management or lifecycle methods were to be used, led to the development of Hooks.
Example of a hook:
useState hook:
In functional components, useState hook lets us define state for a component:

function Person(props) {

// We are declaring a state variable called name.

// setName is a function to update/change the value of name

let [name, setName] = useState(”);

}

The state variable “name” can be directly used inside the HTML.

What are the different ways to style a React component?

There are many different ways through which one can style a React component. Some of the ways are :

  • Inline Styling
    We can directly style an element using inline style attributes.
    Make sure the value of style is a JavaScript object:
class RandomComponent extends React.Component {

render() {

return (

<div>

<h3 style={{ color: "Yellow" }}>This is a heading</h3>

<p style={{ fontSize: "32px" }}>This is a paragraph</p>

</div>

);

}

}
  • Using JavaScript object
    We can create a separate JavaScript object and set the desired style properties.
    This object can be used as the value of the inline style attribute.
class RandomComponent extends React.Component {

paragraphStyles = {

color: "Red",

fontSize: "32px"

};




headingStyles = {

color: "blue",

fontSize: "48px"

};




render() {

return (

<div>

<h3 style={this.headingStyles}>This is a heading</h3>

<p style={this.paragraphStyles}>This is a paragraph</p>

</div>

);

}

}
  • CSS Stylesheet
    We can create a separate CSS file and write all the styles for the component inside that file. This file needs to be imported inside the component file.
import './RandomComponent.css';

class RandomComponent extends React.Component {

render() {

return (

<div>

<h3 className="heading">This is a heading</h3>

<p className="paragraph">This is a paragraph</p>

</div>

);

}

}
  • CSS Modules
    We can create a separate CSS module and import this module inside our component. Create a file with “.module.css”‘ extension,
    styles.module.css:
  • .paragraph{
  • color:”red”;
  • border:1px solid black;
  • }

We can import this file inside the component and use it:

import styles from './styles.module.css';
class RandomComponent extends React.Component {

render() {

return (

<div>

<h3 className="heading">This is a heading</h3>

<p className={styles.paragraph} >This is a paragraph</p>

</div>

);

}

}

 

Name a few techniques to optimize React app performance.

There are many ways through which one can optimize the performance of a React app, let’s have a look at some of them:

  • Using useMemo( ) –
    It is a React hook that is used for caching CPU-Expensive functions.
    Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.
    useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed.
  • Using React.PureComponent –
    It is a base component class that checks state and props of a component to know whether the component should be updated.
    Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily.
  • Maintaining State Colocation –
    This is a process of moving the state as close to where you need it as possible.
    Sometimes in React app, we have a lot of unnecessary states inside the parent component which makes the code less readable and harder to maintain. Not to forget, having many states inside a single component leads to unnecessary re-renders for the component.
    It is better to shift states which are less valuable to the parent component, to a separate component.
  • Lazy Loading –
    It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to minimal.

What are keys in React?

37

A key is a special string attribute that needs to be included when using lists of elements.
Example of a list using key:

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

const listElements = ids.map((id)=>{

return(

<li key={id.toString()}>

{id}

</li>

)

})

Importance of keys
Keys help react identify which elements were added, changed or removed.
Keys should be given to array elements for providing a unique identity for each element.
Without keys, React does not understand the order or uniqueness of each element.
With keys, React has an idea of which particular element was deleted,edited, and added.
Keys are generally used for displaying a list of data coming from an API.
***Note- Keys used within arrays should be unique among siblings. They need not be globally unique.

What is JSX?

JSX is a syntax extension of JavaScript. It is used with React to describe what the user interface should look like. By using JSX, we can write HTML structures in the same file that contains JavaScript code.

38

Can web browsers read JSX directly?

  • Web browsers cannot read JSX directly. This is because they are built to only read regular JS objects and JSX is not a regular JavaScript object
  • For a web browser to read a JSX file, the file needs to be transformed into a regular JavaScript object. For this, we use Babel

39

What is the virtual DOM?

DOM stands for Document Object Model. The DOM represents an HTML document with a logical tree structure. Each branch of the tree ends in a node, and each node contains objects.

40

React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, the virtual DOM changes only that object in the real DOM, rather than updating all the objects.

41

Why use React instead of other frameworks, like Angular?

42  Easy creation of dynamic applications: React makes it easier to create dynamic web applications because it provides less coding and provides more functionality, whereas, with JavaScript applications, code tends to get complex very quickly.
43 Improved performance: React uses virtual DOM, which makes web applications perform faster. Virtual DOM compares its previous state and updates only those components in the real DOM, whose states have changed, rather than updating all the components — like conventional web applications.
44 Reusable components: Components are the building blocks of any React application, and a single app usually consists of multiple components. These components have their own logic and controls, and they can be reused through the application, which, in turn, dramatically reduces the development time of an application.
45 Unidirectional data flow: React follows a unidirectional data flow. This means that when designing a React app, we often nest child components within parent components. And since the data flows in a single direction, it becomes easier to debug errors and know where the problem occurs in an application at the moment.
46 Dedicated tools for easy debugging: Facebook has released a chrome extension that we can use to debug React applications. This makes the process of debugging React to web applications faster and easier.

What is the difference between the ES6 and ES5 standards?

These are the few instances where ES6 syntax has changed from ES5 syntax:

  • Components and Function
  • exports vs export

47

  • require vs import

48

How do you create a React app?

These are the steps for creating a React app:

  • Install NodeJS on the computer because we need npm to install the React library. Npm is the node package manager that contains many JavaScript libraries, including React.

49

  • Install the create-react-app package using the command prompt or terminal.

50

  • Install a text editor of your choice, like VS Code or Sublime Text.

51

How to pass data between react components?

52

Parent Component to Child Component (using props)

With the help of props, we can send data from a parent to a child component.
How do we do this?

Consider the following Parent Component:

import ChildComponent from "./Child";

function ParentComponent(props) {

let [counter, setCounter] = useState(0);

let increment = () => setCounter(++counter);

return (

<div>

<button onClick={increment}>Increment Counter</button>

<ChildComponent counterValue={counter} />

</div>

);

}

As one can see in the code above, we are rendering the child component inside the parent component, by providing a prop called counterValue. Value of the counter is being passed from the parent to the child component.
We can use the data passed by the parent component in the following way:

function ChildComponent(props) {

return (

<div>

<p>Value of counter: {props.counterValue}</p>

</div>

);

}

We use the props.counterValue to display the data passed on by the parent component.
Child Component to Parent Component (using callbacks)
This one is a bit tricky. We follow the steps below:

  • Create a callback in the parent component which takes in the data needed as a parameter.
  • Pass this callback as a prop to the child component.
  • Send data from the child component using the callback.

We are considering the same example above but in this case, we are going to pass the updated counterValue from child to parent.
Step1 and Step2: Create a callback in the parent component, pass this callback as a prop.

function ParentComponent(props) {

let [counter, setCounter] = useState(0);

let callback = valueFromChild => setCounter(valueFromChild);

return (

<div>

<p>Value of counter: {counter}</p>

<ChildComponent callbackFunc={callback} counterValue={counter} />

</div>

);

}

As one can see in the code above, we created a function called callback which takes in the data received from the child component as a parameter.
Next, we passed the function callback as a prop to the child component.
Step3: Pass data from child to the parent component.

function ChildComponent(props) {

let childCounterValue = props.counterValue;

return (

<div>

<button onClick={() => props.callbackFunc(++childCounterValue)}>

Increment Counter

</button>

</div>

);

}

In the code above, we have used the props.counterValue and set it to a variable called childCounterValue.
Next, on button click, we pass the incremented childCounterValue to the props.callbackFunc.
This way, we can pass data from the child to the parent component.

What are Higher Order Components?

Simply put, Higher Order Component(HOC) is a function that takes in a component and returns a new component.

53

When do we need a Higher Order Component?

While developing React applications, we might develop components that are quite similar to each other with minute differences.
In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY, therefore, we want an abstraction that allows us to define this logic in a single place and share it across components.
HOC allows us to create that abstraction.
Example of a HOC:
Consider the following components having similar functionality
The following component displays the list of articles:

class ArticlesList extends React.Component{

constructor(props){

super(props);

this.handleChange = this.handleChange.bind(this);

this.state = {

articles : API.getArticles();

}

}

componentDidMount() {

//Listen to changes made in the API

API.addChangeListener(this.handleChange);

}

componentWillUnmount() {

// Clean up listener

API.removeChangeListener(this.handleChange);

}

handleChange() {

// Update the articles variable whenever the API changes

this.setState({

articles: DataSource.getArticles()

});

}

render(){

return(

<div>

{this.state.articles.map((article)=>(

<ArticleData article={article} key={article.id}/>

))}

</div>

)

}

}

The following component displays the list of users:

class UsersList extends React.Component{

constructor(props){

super(props);

this.handleChange = this.handleChange.bind(this);

this.state = {

users : API.getUsers();

}

}

componentDidMount() {

//Listen to changes made in the API

API.addChangeListener(this.handleChange);

}

componentWillUnmount() {

// Clean up listener

API.removeChangeListener(this.handleChange);

}

handleChange() {

// Update the users variable whenever the API changes

this.setState({

users: DataSource.getUsers()

});

}

render(){

return(

<div>

{this.state.users.map((user)=>(

<UserData user={user} key={user.id}/>

))}

</div>

)

}

}

Notice the above components, both have similar functionality but, they are calling different methods to an API endpoint.
Let’s create a Higher Order Component to create an abstraction:

class UsersList extends React.Component{

constructor(props){

super(props);

this.handleChange = this.handleChange.bind(this);

this.state = {

users : API.getUsers();

}

}

componentDidMount() {

//Listen to changes made in the API

API.addChangeListener(this.handleChange);

}

componentWillUnmount() {

// Clean up listener

API.removeChangeListener(this.handleChange);

}

handleChange() {

// Update the users variable whenever the API changes

this.setState({

users: DataSource.getUsers()

});

}

render(){

return(

<div>

{this.state.users.map((user)=>(

<UserData user={user} key={user.id}/>

))}

</div>

)

}

}

We know HOC is a function that takes in a component and returns a component.
In the code above, we have created a function called HOC which returns a component and performs a functionality that can be shared across both ArticlesList component and UsersList Component.
The second parameter in the HOC function is the function that calls the method on the API endpoint.
We have reduced the duplicated code of the componentDidUpdate and componentDidMount functions.
Using the concept of Higher Order Components, we can now render the ArticlesList and UsersList component in the following way:

const UsersListWithHOC = HOC(UsersList, (API) => API.getUsers());

const ArticlesListWithHOC = HOC(ArticlesList, (API)=> API.getArticles());

Remember, we are not trying to change the functionality of each component, we are trying to share a single functionality across multiple components using HOC.

What is prop drilling in React?

54

Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested.
To pass data between such components, we pass props from a source component, and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.
The disadvantage of using prop drilling is that the components that should otherwise be not aware of the data have access to the data.

What are error boundaries?

Introduced in the version 16 of React, Error boundaries provide a way for us to catch errors that occur in the render phase.

What is an error boundary?

Any component which uses one of the following lifecycle methods, is considered an error boundary.
In what places can an error boundary detect an error?

  • Render phase
  • Inside a lifecycle method
  • Inside the constructor

Without using error boundaries:

class CounterComponent extends React.Component{

constructor(props){

super(props);

this.state = {

counterValue: 0

}

this.incrementCounter = this.incrementCounter.bind(this);

}

incrementCounter(){

this.setState(prevState => counterValue = prevState+1);

}

render(){

if(this.state.counter === 2){

throw new Error('Crashed');

}

return(

<div>

<button onClick={this.incrementCounter}>Increment Value</button>

<p>Value of counter: {this.state.counterValue}</p>

</div>

)

}

}

In the code above, when the counterValue equals to 2, we throw an error inside the render method.
When we are not using the error boundary, instead of seeing an error, we see a blank page.
Since any error inside the render method, leads to unmounting of the component.
To display an error that occurs inside the render method, we use error boundaries.
With error boundaries:
As mentioned above, error boundary is a component using one or both of the following methods:
static getDerivedStateFromError and componentDidCatch.
Let’s create an error boundary to handle errors in render phase:

class ErrorBoundary extends React.Component {

constructor(props) {

super(props);

this.state = { hasError: false };

}

static getDerivedStateFromError(error) {

return { hasError: true };

}

componentDidCatch(error, errorInfo) {

logErrorToMyService(error, errorInfo);

}

render() {

if (this.state.hasError) {

return <h4>Something went wrong</h4>

}

return this.props.children;

}

}

In the code above, getDerivedStateFromError function renders the fallback UI interface when the render method has an error.
componentDidCatch logs the error information to an error tracking service.
Now with error boundary, we can render the CounterComponent in the following way:

<ErrorBoundary>

<CounterComponent/>

</ErrorBoundary>

What is React?

React is a declarative, efficient, flexible open source front-end JavaScript library developed by Facebook in 2011. It follows the component-based approach for building reusable UI components, especially for single page application. It is used for developing interactive view layer of web and mobile apps. It was created by Jordan Walke, a software engineer at Facebook. It was initially deployed on Facebook’s News Feed section in 2011 and later used in its products like WhatsApp & Instagram.

What are the features of React?

React framework gaining quick popularity as the best framework among web developers. The main features of React are:

  • JSX
  • Components
  • One-way Data Binding
  • Virtual DOM
  • Simplicity
  • Performance

What are the advantages of React?

The advantages of React are:

  • Easy to Learn and USe
  • Creating Dynamic Web Applications Becomes Easier
  • Reusable Components
  • Performance Enhancement
  • The Support of Handy Tools
  • Known to be SEO Friendly
  • The Benefit of Having JavaScript Library
  • Scope for Testing the Codes

What are the limitations of React?

The limitations of React are:

  • The high pace of development
  • Poor Documentation
  • View Part
  • JSX as a barrier

What is JSX?

JSX stands for JavaScript XML. It is a React extension which allows writing JavaScript code that looks similar to HTML. It makes HTML file easy to understand. The JSX file makes the React application robust and boosts its performance. JSX provides you to write XML-like syntax in the same file where you write JavaScript code, and then preprocessor (i.e., transpilers like Babel) transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.

Example

class App extends React.Component {

render() {

return(

<div>

<h1>Hello JavaTpoint</h1>

</div>

)

}

}

In the above example, text inside <h1> tag return as JavaScript function to the render function. After compilation, the JSX expression becomes a normal JavaScript function, as shown below.

  1. React.createElement(“h1”, null, “Hello JavaTpoint”);

Why can’t browsers read JSX?

Browsers cannot read JSX directly because they can only understand JavaScript objects, and JSX is not a regular JavaScript object. Thus, we need to transform the JSX file into a JavaScript object using transpilers like Babel and then pass it to the browser.

Why we use JSX?

  • It is faster than regular JavaScript because it performs optimization while translating the code to JavaScript.
  • Instead of separating technologies by putting markup and logic in separate files, React uses components that contain both.
  • t is type-safe, and most of the errors can be found at compilation time.
  • It makes easier to create templates.

What do you understand by Virtual DOM?

A Virtual DOM is a lightweight JavaScript object which is an in-memory representation of real DOM. It is an intermediary step between the render function being called and the displaying of elements on the screen. It is similar to a node tree which lists the elements, their attributes, and content as objects and their properties. The render function creates a node tree of the React components and then updates this node tree in response to the mutations in the data model caused by various actions done by the user or by the system.

Explain the working of Virtual DOM.

Virtual DOM works in three steps:
1. Whenever any data changes in the React App, the entire UI is re-rendered in Virtual DOM representation.

55

2. Now, the difference between the previous DOM representation and the new DOM is calculated.

56

3. Once the calculations are completed, the real DOM updated with only those things which are changed.

A

How is React different from Angular?

The React is different from Angular in the following ways.

Angular React
Author Google Facebook Community
Developer Misko Hevery Jordan Walke
Initial Release October 2010 March 2013
Language JavaScript, HTML JSX
Type Open Source MVC Framework Open-Source JS Framework
Rendering Client-Side Server-Side
Data-Binding Bi-directional Uni-directional
DOM Regular DOM Virtual DOM
Testing Unit and Integration Testing Unit Testing
App Architecture MVC Flux
Performance Slow Fast, due to virtual DOM.

 

How React’s ES6 syntax is different from ES5 syntax?

The React’s ES6 syntax has changed from ES5 syntax in the following aspects.

The React’s ES6 syntax has changed from ES5 syntax in the following aspects.

require vs. Import

// ES5  

var React = require('react');  

   

// ES6  

import React from 'react';

exports vs. export

// ES5  

module.exports = Component;  

   

// ES6  

export default Component;

component and function

// ES5  

var MyComponent = React.createClass({  

    render: function() {  

        return(  

          <h3>Hello JavaTpoint</h3>  

        );  

    }  

});  

   

// ES6  

class MyComponent extends React.Component {  

    render() {  

        return(  

          <h3>Hello Javatpoint</h3>  

        );  

    }  

}  

props

// ES5  

var App = React.createClass({  

    propTypes: { name: React.PropTypes.string },  

    render: function() {  

        return(  

           <h3>Hello, {this.props.name}!</h3>  

        );  

    }  

});  

   

// ES6  

class App extends React.Component {  

    render() {  

        return(  

          <h3>Hello, {this.props.name}!</h3>  

        );  

    }  

}

state

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>  

        );  

    }  

}

What is the difference between ReactJS and React Native?

The main differences between ReactJS and React Native are given below.

SN ReactJS React Native
1. Initial release in 2013. Initial release in 2015.
2. It is used for developing web applications. It is used for developing mobile applications.
3. It can be executed on all platforms. It is not platform independent. It takes more effort to be executed on all platforms.
4. It uses a JavaScript library and CSS for animations. It comes with built-in animation libraries.
5. It uses React-router for navigating web pages. It has built-in Navigator library for navigating mobile applications.
6. It uses HTML tags. It does not use HTML tags.
7. In this, the Virtual DOM renders the browser code. In this, Native uses its API to render code for mobile applications.

What do you understand from “In React, everything is a component.”

In React, components are the building blocks of React applications. These components divide the entire React application’s UI into small, independent, and reusable pieces of code. React renders each of these components independently without affecting the rest of the application UI. Hence, we can say that, in React, everything is a component.

Explain the purpose of render() in React.

It is mandatory for each React component to have a render() function. Render function is used to return the HTML which you want to display in a component. If you need to rendered more than one HTML element, you need to grouped together inside single enclosing tag (parent tag) such as <div>, <form>, <group> etc. This function returns the same result each time it is invoked.

Example:

If you need to display a heading, you can do this as below.

import React from 'react'




class App extends React.Component {

   render (){

      return (

         <h1>Hello World</h1>

      )

   }

}

export default App

Points to Note:

  • Each render() function contains a return statement.
  • The return statement can have only one parent HTML tag.

How can you embed two or more components into one?

You can embed two or more components into the following way:

import React from 'react'




class App extends React.Component {

   render (){

      return (

         <h1>Hello World</h1>

      )

   }

}

class Example extends React.Component {

   render (){

      return (

         <h1>Hello JavaTpoint</h1>

      )

   }

}

export default App

What is Props?

Props stand for “Properties” in React. They are read-only inputs to components. Props are an object which stores the value of attributes of a tag and work similar to the HTML attributes. It gives a way to pass data from the parent to the child components throughout the application.

It is similar to function arguments and passed to the component in the same way as arguments passed in a function.

Props are immutable so we cannot modify the props from inside the component. Inside the components, we can add attributes called props. These attributes are available in the component as this.props and can be used to render dynamic data in our render method.

What is a State in React?

The State is an updatable structure which holds the data and information about the component. It may be changed over the lifetime of the component in response to user action or system event. It is the heart of the react component which determines the behavior of the component and how it will render. It must be kept as simple as possible.

Let’s create a “User” component with “message state.”

import React from 'react'

class User extends React.Component {

  constructor(props) {

    super(props)

    this.state = {

      message: 'Welcome to JavaTpoint'

    }

  }

  render() {

    return (

      <div>

        <h1>{this.state.message}</h1>

      </div>

    )

  }

}

export default User

Differentiate between States and Props.

The major differences between States and Props are given below.

SN Props State
1. Props are read-only. State changes can be asynchronous.
2. Props are immutable. State is mutable.
3. Props allow you to pass data from one component to other components as an argument. State holds information about the components.
4. Props can be accessed by the child component. State cannot be accessed by child components.
5. Props are used to communicate between components. States can be used for rendering dynamic changes with the component.
6. The stateless component can have Props. The stateless components cannot have State.
7. Props make components reusable. The State cannot make components reusable.
8. Props are external and controlled by whatever renders the component. The State is internal and controlled by the component itself.

How can you update the State of a component?

We can update the State of a component using this.setState() method. This method does not always replace the State immediately. Instead, it only adds changes to the original State. It is a primary method which is used to update the user interface(UI) in response to event handlers and server responses.

Example

import React, { Component } from 'react';

import PropTypes from 'prop-types';




class App extends React.Component {

   constructor() {

      super();

      this.state = {

          msg: "Welcome to JavaTpoint"

      };

      this.updateSetState = this.updateSetState.bind(this);

   }

   updateSetState() {

       this.setState({

          msg:"Its a best ReactJS tutorial"

       });

   }

   render() {

      return (

         <div>

             <h1>{this.state.msg}</h1>

             <button onClick = {this.updateSetState}>SET STATE</button>

         </div>

      );

   }

}

export default App;


Differentiate between stateless and stateful components.

The difference between stateless and stateful components are:

SN Stateless Component Stateful Component
1. The stateless components do not hold or manage state. The stateful components can hold or manage state.
2. It does not contain the knowledge of past, current, and possible future state changes. It can contain the knowledge of past, current, and possible future changes in state.
3. It is also known as a functional component. It is also known as a class component.
4. It is simple and easy to understand. It is complex as compared to the stateless component.
5. It does not work with any lifecycle method of React. It can work with all lifecycle method of React.
6. The stateless components cannot be reused. The stateful components can be reused.

What are the different phases of React component’s lifecycle?

Initial Phase: It is the birth phase of the React lifecycle when the component starts its journey on a way to the DOM. In this phase, a component contains the default Props and initial State. These default properties are done in the constructor of a component.

Mounting Phase: In this phase, the instance of a component is created and added into the DOM.

Updating Phase: It is the next phase of the React lifecycle. In this phase, we get new Props and change State. This phase can potentially update and re-render only when a prop or state change occurs. The main aim of this phase is to ensure that the component is displaying the latest version of itself. This phase repeats again and again.

Unmounting Phase: It is the final phase of the React lifecycle, where the component instance is destroyed and unmounted(removed) from the DOM.

Explain the lifecycle methods of React components in detail.

  • getInitialState(): It is used to specify the default value of this.state. It is executed before the creation of the component.
  • componentWillMount(): It is executed before a component gets rendered into the DOM.
  • componentDidMount(): It is executed when the component gets rendered and placed on the DOM. Now, you can do any DOM querying operations.
  • componentWillReceiveProps(): It is invoked when a component receives new props from the parent class and before another render is called. If you want to update the State in response to prop changes, you should compare this.props and nextProps to perform State transition by using this.setState() method.
  • shouldComponentUpdate(): It is invoked when a component decides any changes/updation to the DOM and returns true or false value based on certain conditions. If this method returns true, the component will update. Otherwise, the component will skip the updating.
  • componentWillUpdate(): It is invoked before rendering takes place in the DOM. Here, you can’t change the component State by invoking this.setState() method. It will not be called, if shouldComponentUpdate() returns false.
  • componentDidUpdate(): It is invoked immediately after rendering takes place. In this method, you can put any code inside this which you want to execute once the updating occurs.
  • componentWillUnmount(): It is invoked immediately before a component is destroyed and unmounted permanently. It is used to clear up the memory spaces such as invalidating timers, event listener, canceling network requests, or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.

What are Pure Components?

Pure components introduced in React 15.3 version. The React.Component and React.PureComponent differ in the shouldComponentUpdate() React lifecycle method. This method decides the re-rendering of the component by returning a boolean value (true or false). In React.Component, shouldComponentUpdate() method returns true by default. But in React.PureComponent, it compares the changes in state or props to re-render the component. The pure component enhances the simplicity of the code and performance of the application.

What are Higher Order Components(HOC)?

In React, Higher Order Component is an advanced technique for reusing component logic. It is a function that takes a component and returns a new component. In other words, it is a function which accepts another function as an argument. According to the official website, it is not the feature(part) in React API, but a pattern that emerges from React’s compositional nature.

What can you do with HOC?

You can do many tasks with HOC, some of them are given below:

  • Code Reusability
  • Props manipulation
  • State manipulation
  • Render highjacking

What is the difference between Element and Component?

The main differences between Elements and Components are:

SN Element Component
1. An element is a plain JavaScript object which describes the component state and DOM node, and its desired properties. A component is the core building block of React application. It is a class or function which accepts an input and returns a React element.
2. It only holds information about the component type, its properties, and any child elements inside it. It can contain state and props and has access to the React lifecycle methods.
3. It is immutable. It is mutable.
4. We cannot apply any methods on elements. We can apply methods on components.
5. Example:
const element = React.createElement(
‘div’,
{id: ‘login-btn’},
‘Login’
)
Example:
function Button ({ onLogin }) {
return React.createElement(
‘div’,
{id: ‘login-btn’, onClick: onLogin},
‘Login’
)
}

How to write comments in React?

In React, we can write comments as we write comments in JavaScript. It can be in two ways:

A. Single Line Comments: We can write comments as /* Block Comments */ with curly braces:

  1. {/* Single Line comment */}

B. Multiline Comments: If we want to comment more that one line, we can do this as

    1. { /*
    2.    Multi
    3.    line
    4.    comment
    5. */ }

Why is it necessary to start component names with a capital letter?

In React, it is necessary to start component names with a capital letter. If we start the component name with lower case, it will throw an error as an unrecognized tag. It is because, in JSX, lower case tag names are considered as HTML tags.

What are fragments?

In was introduced in React 16.2 version. In React, Fragments are used for components to return multiple elements. It allows you to group a list of multiple children without adding an extra node to the DOM.

Example

render() {

  return (

    <React.Fragment>

      <ChildA />

      <ChildB />

      <ChildC />

    </React.Fragment>

  )

}

There is also a shorthand syntax exists for declaring Fragments, but it’s not supported in many tools:

render() {

  return (

    <>

      <ChildA />

      <ChildB />

      <ChildC />

    </>

  )

}

Why are fragments better than container divs?

  • Fragments are faster and consume less memory because it did not create an extra DOM node.
  • Some CSS styling like CSS Grid and Flexbox have a special parent-child relationship and add <div> tags in the middle, which makes it hard to keep the desired layout.
  • The DOM Inspector is less cluttered.

How to apply validation on props in React?

Props validation is a tool which helps the developers to avoid future bugs and problems. It makes your code more readable. React components used special property PropTypes that help you to catch bugs by validating data types of values passed through props, although it is not necessary to define components with propTypes.

We can apply validation on props using App.propTypes in React component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you need to set the App.defaultProps.

class App extends React.Component {

          render() {}
}

Component.propTypes = { /*Definition */};

What is create-react-app?

Create React App is a tool introduced by Facebook to build React applications. It provides you to create single-page React applications. The create-react-app are preconfigured, which saves you from time-consuming setup and configuration like Webpack or Babel. You need to run a single command to start the React project, which is given below.

  1. $ npx create-react-app my-app

This command includes everything which we need to build a React app. Some of them are given below:

  • It includes React, JSX, ES6, and Flow syntax support.
  • It includes Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
  • It includes a fast, interactive unit test runner with built-in support for coverage reporting.
  • It includes a live development server that warns about common mistakes.
  • It includes a build script to bundle JS, CSS, and images for production, with hashes and source maps.

What do you understand by refs in React?

Refs is the shorthand used for references in React. It is an attribute which helps to store a reference to particular DOM nodes or React elements. It provides a way to access React DOM nodes or React elements and how to interact with it. It is used when we want to change the value of a child component, without making the use of props.

How to create refs?

Refs can be created by using React.createRef() and attached to React elements via the ref attribute. It is commonly assigned to an instance property when a component is created, and then can be referenced throughout the component.

class MyComponent extends React.Component {

  constructor(props) {

    super(props);

    this.callRef = React.createRef();

  }

  render() {

    return <div ref={this.callRef} />;

  }

}

What are Forward Refs?

Ref forwarding is a feature which is used for passing a ref through a component to one of its child components. It can be performed by making use of the React.forwardRef() method. It is particularly useful with higher-order components and specially used in reusable component libraries.

Example

import React, { Component } from 'react';

import { render } from 'react-dom';




const TextInput = React.forwardRef((props, ref) => (

  <input type="text" placeholder="Hello World" ref={ref} />

));




const inputRef = React.createRef();




class CustomTextInput extends React.Component {

  handleSubmit = e => {

    e.preventDefault();

    console.log(inputRef.current.value);

  };

  render() {

    return (

      <div>

        <form onSubmit={e => this.handleSubmit(e)}>

          <TextInput ref={inputRef} />

          <button>Submit</button>

        </form>

      </div>

    );

  }

}

export default App;

Which is the preferred option callback refs or findDOMNode()?

The preferred option is to use callback refs over findDOMNode() API. Because callback refs give better control when the refs are set and unset whereas findDOMNode() prevents certain improvements in React in the future.

class MyComponent extends Component {

  componentDidMount() {

    findDOMNode(this).scrollIntoView()

  }

  render() {

    return <div />

  }

}

The recommended approach is:

class MyComponent extends Component {

  componentDidMount() {

    this.node.scrollIntoView()

  }

  render() {

    return <div ref={node => this.node = node} />

  }

}

class MyComponent extends Component {

  componentDidMount() {

    this.node.scrollIntoView()

  }

  render() {

    return <div ref={node => this.node = node} />

  }

}

What is the use of Refs?

The Ref in React is used in the following cases:

  • It is used to return a reference to the element.
  • It is used when we need DOM measurements such as managing focus, text selection, or media playback.
  • It is used in triggering imperative animations.
  • It is used when integrating with third-party DOM libraries.
  • It can also use as in callbacks.

What is React Router?

React Router is a standard routing library system built on top of the React. It is used to create Routing in the React application using React Router Package. It helps you to define multiple routes in the app. It provides the synchronous URL on the browser with data that will be displayed on the web page. It maintains the standard structure and behavior of the application and mainly used for developing single page web applications.

Why do we need a Router in React?

React Router plays an important role to display multiple views in a single page application. It is used to define multiple routes in the app. When a user types a specific URL into the browser, and if this URL path matches any ‘route’ inside the router file, the user will be redirected to that particular Route. So, we need to add a Router library to the React app, which allows creating multiple routes with each leading to us a unique view.

<switch>

      <h1>React Router Example</h1>

      <Route path="/" component={Home} />

      <Route path="/about" component={About} />

      <Route path="/contact" component={Contact} />

</switch>

List down the advantages of React Router.

The important advantages of React Router are given below:

  • In this, it is not necessary to set the browser history manually.
  • Link uses to navigate the internal links in the application. It is similar to the anchor tag.
  • It uses Switch feature for rendering.
  • The Router needs only a Single Child element.
  • In this, every component is specified in <Route>.
  • The packages are split into three packages, which are Web, Native, and Core. It supports the compact size of the React application.

How is React Router different from Conventional Routing?

The difference between React Routing and Conventional Routing are:

SN Conventional Routing React Routing
1. In Conventional Routing, each view contains a new file. In React Routing, there is only a single HTML page involved.
2. The HTTP request is sent to a server to receive the corresponding HTML page. Only the History attribute <BrowserRouter> is changed.
3. In this, the user navigates across different pages for each view. In this, the user is thinking he is navigating across different pages, but its an illusion only.

Why you get “Router may have only one child element” warning?

It is because you have not to wrap your Route’s in a <Switch> block or <div> block which renders a route exclusively.

Example

render((

  <Router>

    <Route {/* ... */} />

    <Route {/* ... */} />

  </Router>

)

should be

render(

  <Router>

    <Switch>

      <Route {/* ... */} />

      <Route {/* ... */} />

    </Switch>

  </Router>

)

Why switch keyword used in React Router v4?

The ‘switch’ keyword is used to display only a single Route to rendered amongst the several defined Routes. The <Switch> component is used to render components only when the path will be matched. Otherwise, it returns to the not found component.

How to use styles in React?

We can use style attribute for styling in React applications, which adds dynamically-computed styles at render time. It accepts a JavaScript object in camelCased properties rather than a CSS string. The style attribute is consistent with accessing the properties on DOM nodes in JavaScript.

Example

const divStyle = {

  color: 'blue',

  backgroundImage: 'url(' + imgUrl + ')'

};

function HelloWorldComponent() {

  return <div style={divStyle}>Hello World!</div>

}

How many ways can we style the React Component?

We can style React Component in mainly four ways, which are given below:

  • Inline Styling
  • CSS Stylesheet
  • CSS Module
  • Styled Components

Explain CSS Module styling in React.

CSS Module is a CSS file where all class names and animation names are scoped locally by default. It is available only for the component which imports it, and without your permission, it cannot be applied to any other Components. You can create CSS Module file with the .module.css extension.

What are Styled Components?

Styled-Components is a library for React. It is the successor of CSS Modules. It uses enhance CSS for styling React component systems in your application, which is written with a mixture of JavaScript and CSS. It is scoped to a single component and cannot leak to any other element in the page.

The styled-components provides:

  • Automatic critical CSS
  • No class name bugs
  • Easier deletion of CSS
  • Simple dynamic styling
  • Painless maintenance

What were the major problems with MVC framework?

The major problems with the MVC framework are:

  • DOM manipulation was very expensive.
  • It makes the application slow and inefficient.
  • There was a huge memory wastage.
  • It makes the application debugging hard.

Explain the Flux concept.

Flux is an application architecture that Facebook uses internally for building the client-side web application with React. It is neither a library nor a framework. It is a kind of architecture that complements React as view and follows the concept of Unidirectional Data Flow model. It is useful when the project has dynamic data, and we need to keep the data updated in an effective manner.

What is Redux?

Redux is an open-source JavaScript library used to manage application state. React uses Redux for building the user interface. The Redux application is easy to test and can run in different environments showing consistent behavior. It was first introduced by Dan Abramov and Andrew Clark in 2015.

React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model. React Redux is conceptually simple. It subscribes to the Redux store, checks to see if the data which your component wants have changed, and re-renders your component.

What are the three principles that Redux follows?

The three principles that redux follows are:

  1. Single source of truth: The State of your entire application is stored in an object/state tree inside a single Store. The single State tree makes it easier to keep changes over time. It also makes it easier to debug or inspect the application.
  2. The State is read-only: There is only one way to change the State is to emit an action, an object describing what happened. This principle ensures that neither the views nor the network callbacks can write directly to the State.
  3. Changes are made with pure functions: To specify how actions transform the state tree, you need to write reducers (pure functions). Pure functions take the previous State and Action as a parameter and return a new State.

List down the components of Redux.

The components of Redux are given below.

  • STORE: A Store is a place where the entire State of your application lists. It is like a brain responsible for all moving parts in Redux.
  • ACTION: It is an object which describes what happened.
  • REDUCER: It determines how the State will change.

Explain the role of Reducer.

Reducers read the payloads from the actions and then updates the Store via the State accordingly. It is a pure function which returns a new state from the initial State. It returns the previous State as it is if no work needs to be done.

What is the significance of Store in Redux?

A Store is an object which holds the application’s State and provides methods to access the State, dispatch Actions and register listeners via subscribe(listener). The entire State tree of an application is saved in a single Store which makes the Redux simple and predictable. We can pass middleware to the Store which handles the processing of data as well as keep a log of various actions that change the Store’s State. All the Actions return a new state via reducers.

How is Redux different from Flux?

The Redux is different from Flux in the following manner.

SN Redux Flux
1. Redux is an open-source JavaScript library used to manage application State. Flux is neither a library nor a framework. It is a kind of architecture that complements React as view and follows the concept of Unidirectional Data Flow model.
2. Store’s State is immutable. Store’s State is mutable.
3. In this, Store and change logic are separate. In this, the Store contains State and change logic.
4. It has only a single Store. It can have multiple Store.
5. Redux does not have Dispatcher concept. It has single Dispatcher, and all actions pass through that Dispatcher.

What are the advantages of Redux?

The main advantages of React Redux are:

  • React Redux is the official UI bindings for react Application. It is kept up-to-date with any API changes to ensure that your React components behave as expected.
  • It encourages good ‘React’ architecture.
  • It implements many performance optimizations internally, which allows to components re-render only when it actually needs.
  • It makes the code maintenance easy.
  • Redux’s code written as functions which are small, pure, and isolated, which makes the code testable and independent.

How to access the Redux store outside a component?

You need to export the Store from the module where it created with createStore() method. Also, you need to assure that it will not pollute the global window space.

  1. store = createStore(myReducer)
  2. export default store

What is React? What are some of its standouts?

React is a front-end JavaScript library. It was developed by Facebook in 2011. It enhances application performance while allowing for working on both client-side and server-side.

Writing UI test cases is simple with React, which is also easy to integrate with Angular, Meteor, and other popular JS frameworks. Here are some of the major standouts of React:

  • Excellent for developing complex and interactive web and mobile UI
  • Follows the component-based approach and helps in building reusable UI components
  • Features one of the largest community support
  • Makes use of the virtual DOM instead of the real DOM
  • Relies on server-side rendering
  • Supports unidirectional data flow or data binding

React has something called a state. What is it and how it is used?

States are the source of data for React components. In other words, they are objects responsible for determining components behavior and rendering. As such, they must be kept as simple as possible.

Accessible by means of this.state(), state is mutable and creates dynamic and interactive components. Use of a state can be visualized by the following code snippet:

class App extends React.Component {

constructor() {

super();

this.state={

foo: 'bar'

}

}

Why do we use render() in React?

In React, each component must have a render() function. It returns a single React element, which is, in fact, the representation of the native DOM component.

When there is a need for more than one HTML element to be rendered, we group them in one enclosing tag, which can be,or some other tag. There is a need for the render() function to return the same result each time it is invoked i.e. it needs to be kept pure.

Draw a diagram showing how data flows through Redux.

Q

Explain major differences between the ES5 and ES6 syntax with relevant examples.

The syntax has witnessed a great change from ES5 to ES6. Important differences between the two releases of ECMAScript are:

  • Require vs. Import – The require used in ES5 is now replaced with import.var React = require(‘react’); //is now replaced with
    import React from ‘react’; //in ES6
  • Export vs. Exports – Instead of exports, now export is used.export default Component; // replaces
    module.exports = Component; // in ES6
  • Component and Function – The use of component and function has also changed from ES5 to ES6.

In ES5:

var MyComponent = React.createClass({

render: function() {

return
Hello World!
;

}

});

In ES6:

class MyComponent extends React.Component {

render() {

return
Hello World!
;

}

}
  • Props – Rules for using props has also changed from ES5 to ES6

In ES5:

var App = React.createClass({

propTypes: { name: React.PropTypes.string },

render: function() {

return
Hello, !
;

}

});

In ES6:

class App extends React.Component {

render() {

return
Hello, !
;

}

}
  • State – Using state has also been tweaked for ES6.

In ES5:

var App = React.createClass({

getInitialState: function() {

return { name: 'world' };

},

render: function() {

return
Hello, !
;

}

});

In ES6:

class App extends React.Component {

constructor() {

super();

this.state = { name: 'world' };

}

render() {

return
Hello, !
;

}

}

Explain the Virtual DOM and it’s working.

A virtual DOM is a lightweight JS object. It is simply a copy of the real DOM. A virtual DOM is a node tree that lists various elements, their attributes, and content as objects and their properties.

The render() function in React is responsible for creating a node tree from the React components. This tree is then updated in response to the mutations resulting in the data model due to various actions made by the user or the system.

Virtual DOM operates in three simple steps:

  • Step 1 – The entire UI is re-rendered in Virtual DOM representation as soon as there are some underlying data changes.
  • Step 2 – Now, the difference between the previous DOM representation and the new one (resulted from underlying data changes) is calculated.
  • Step 3 – After the calculations are successfully carried out, the real DOM is updated in line with only the things that actually underwent changes

How does the Real DOM differ from the Virtual DOM?

  • DOM Manipulation – Real DOM supports a very expensive DOM manipulation. Virtual DOM, on the contrary, has an inexpensive DOM manipulation.
  • Element Update – Real DOM creates a new DOM when an element updates. Virtual DOM doesn’t do so in such a case. Instead, it updates the JSX.
  • Memory Wastage – Real DOM causes a lot of memory wastage while there is no memory wastage for Virtual DOM.
  • Update Speed – Real DOM updates slowly. On the other end, the virtual DOM updates faster.
  • Updating HTML – Real DOM can directly update HTML, while virtual DOM can’t update HTML directly.

Explain various lifecycle methods of React components.

  • componentDidMount() – Executes on the client side after the first render
  • componentDidUpdate() – Called immediately after rendering takes place in the DOM
  • componentWillMount() – Executes immediately before rendering starts on both the client-side and the server-side
  • componentWillReceiveProps() – Invokes when props are received from the parent class and before another render is called
  • componentWillUnmount() – Used to clear up the memory space. Called right after the component is unmounted from the DOM
  • componentWillUpdate() – Called immediately before rendering takes place in the DOM
  • shouldComponentUpdate() – Returns either true or false. Though false by default, needs to be set to return true if the component needs to be updated

Explain JSX with a code example. Why can’t browsers read it?

JSX is a contraction of the JavaScript XML. It uses the expressiveness of JavaScript for making the HTML code easily understandable. JSX files make applications robust while boosting their performance. A code example of JSX is:

JSX isn’t a regular JS object. The inability of browsers in reading JSX is due to the fact that browsers can only read regular JS objects.

Give a code example to demonstrate embedding two or more components into one.

class MyComponent extends React.Component{

render(){

return(
Hello
);

}

}

class Header extends React.Component{

render(){

return
Header Component
};

}

ReactDOM.render(

, document.getElementById('content')

);

Give a code example to modularize code in React.

In order to modularize code in React, export and import properties are used. They assist in writing the components distinctly in different files:

export default class ChildComponent extends React.Component {

render() {

return(
This is a child component
);

}

}

import ChildComponent from './childcomponent.js';

class ParentComponent extends React.Component {

render() {

return(
);

}

}

How does the React Router differ from conventional routing?

  • Changes in the URL – A HTTP request is sent to a server for receiving a corresponding HTML page in conventional routing. React routing necessitates only for a change in the History attribute.
  • Navigation – In conventional routing, the user actually navigates across different web pages for each individual view. In React routing, however, the users feel like they are navigating across distinct webpages while in actuality they aren’t.
  • Pages – Whereas in React routing only a single HTML page is involved, each view corresponds to a new file in conventional routing.

How does the state differ from props in React?

  • Changes inside child components are possible with props but not with state
  • Changes inside the component aren’t possible with props but with state
  • Props allow for a parent component to change the value, state doesn’t

How will you distinguish Redux from Flux?

  • Changes in the URL – A HTTP request is sent to a server for receiving a corresponding HTML page in conventional routing. React routing necessitates only for a change in the History attribute.
  • Navigation – In conventional routing, the user actually navigates across different web pages for each individual view. In React routing, however, the users feel like they are navigating across distinct webpages while in actuality they aren’t.
  • Pages – Whereas in React routing only a single HTML page is involved, each view corresponds to a new file in conventional routing.

How would you create a form in React?

React forms are identical to HTML forms. However, the state is contained in the state property of the component in React and is updateable only via the setState() method.

Therefore, the elements in a React form can’t directly update their state. Their submission is handled by a JS function, which has full access to the data entered into the form by a user.

Following code demonstrates creating a form in React:

handleSubmit(event) {

alert('A name was submitted: ' + this.state.value);

event.preventDefault();

}

render() {

return (

Top of Form

Name:

Bottom of Form

);

}

What are the advantages of using Redux?

  • Better Code Organization – Redux is precise in terms of how the code needs to be organized. This results in a consistent code workable for any development team
  • Developer Tools – Allow developers to track each and everything, ranging from actions to state changes, happening in the application in real-time
  • Easy Testing – Redux code is mainly composed of functions that are isolated, pure, and small. Hence, testing is much easy and simple
  • Large-scale Community – Redux is backed by a mammoth community. It contributes to an ever-growing and refined library and ready-to-use applications
  • Maintainability – Thanks to a predictable outcome and strict structure, the code is easier to maintain.
  • Output Predictability – There is no confusion about syncing the current state with actions as well as other parts of the application as there is only a single source of truth, which is the store.
  • Server-side Rendering – There is a need of only passing the store created on the server-side to the client-side. In addition to this being useful for initial render, it also offers a better user experience because it optimizes the application performance

What do you understand by Props in React?

Prop is a contraction for Properties in React. These read-only components need to be kept immutable i.e., pure. Throughout the application, props are passed down from the parent components to the child components.

In order to maintain the unidirectional data flow, a child component is restricted from sending a prop back to its parent component. This also helps in rendering the dynamically generated data.

Where would you put AJAX calls in your React code?

It is possible to use any AJAX library with React, such as Axios, jQuery AJAX, as well as the inbuilt browser window.fetch.

Data with AJAX calls need to be added to the componentDidMount() lifecycle method. By doing this, it is possible to use the setState() method for updating component as soon as the data is retrieved.

Write a sample code to update the state of a component in React?

State of a component in React is updated with this.setState() as demonstrated in the following code example:

class MyComponent extends React.Component {

constructor() {

super();

this.state = {

name: 'Akhil',

id: '101'

}

}

render()

{

setTimeout(()=>)},2000)

return (
Hello
Your Id is
);

}

}

ReactDOM.render(

, document.getElementById('content')

);

You must’ve heard that “In React, everything is a component.” What do you understand from the statement?

The building blocks of a React application’s UI are called components. Any app UI created using React is divisible into a number of small independent and reusable pieces, known as components.
React renders each of the components independent of each other. Hence, there is no effect of rendering a component on the rest of the app UI.

What are the distinct features of React?

The distinct features of React include the following.

  1. It uses Virtual DOM in place of Real DOM
  2. It applies server-side rendering
  3. It follows the unidirectional flow of data
  4. It is data binding

What are the advantages of React?

There are varied advantages of React which include:

  1. It improves the performance of the application.
  2. It can be used for the client-side and the customer side.
  3. It increases the readability of code’s using JSX.
  4. It is easy to integrate with various other frameworks, including Angular, Meteor, etc.
  5. User Interface becomes more comfortable with React.

Are there are any limitations to React?

There are several limitations of React which include:

  1. It acts as a library and not as a framework.
  2. The contents of the library are so large that it consumes a considerable amount of time to understand.
  3. It is difficult to understand for the novice.
  4. The coding process becomes more complicated when inline templating and JSX are applied.

Can browsers read JSX?

No, the browsers cannot read JSX because it is not a regular JavaScript object.

What are the differences between React and Angular?

There are several differences between React and Angular, which include the following:

Basis of Difference React Angular
Architecture It only supports the view of MVC It supports a complete MVC view
Render It offers server-side rendering It offers client-side rendering
DOM It applies virtual DOM It applies real DOM
Data binding It supports one-way data binding It supports two-way data binding
Debug It applies to compile-time debugging It applies runtime debugging
Developer Developed by Facebook Developed by Google

What is the relation between React and its components?

React, and its components are closely related. The components of React acts as the building blocks of React application for the user interface. The splitting up of this entire user interface in different small, independent, and reusable pieces help in creating React application’s User Interface.

What is Props in React?

Props is referred to the properties in React, including immutable, child components, parent component, etc.

What are states in React?

States in react acts as a source of data and are kept simple so that the objects which determine component rendering and behavior become mutable other than props and develop a dynamic and interactive component.

Can parent component change value in States and Props?

The parent component can change the value in Props but not in the state.

Can changes be made inside the component?

The changes can be made inside the state but not in Props.

Can we make changes inside child components?

Yes, we can make changes inside the child component in Props but not in the case of States.

What is a Stateful component?

A Stateful component stores the change in memory to React. It has the authority to change state and contains vital information of past, current, and future changes.

How is Stateless component different from a Stateful component?

The stateless component calculates the internal state of the component but does not have the authority to change state. There is no knowledge about the past, current, or future but receives props from the Stateful component, which are treated as a callback function.

Define Synthetic Events in React?

The Synthetic Events in React are the objects in React, which acts as a cross-browser wrapper around the browser’s native event. The main purpose is to combine the different browsers on the API so that the event shows various properties.

Define Refs in React?

Refs stands for References to React. It helps in storing a reference to a particular react element or component that can be returned by the component render configuration function.

When are Refs mostly used?

Refs are mostly used in the following cases:

  1. When there is a need to manage focus, select the text, or apply media playback.
  2. To initiate imperative animations.
  3. To join with the third-party DOM libraries.

Can we modularize code in React? How?

Yes, we can modularize code in React. It can be done by using export and import properties.

What are the controlled components in React?

The controlled components in React are referred to as those components which can maintain their state. The data is controlled by their parent component, and they take into consideration the current values using props and thereafter, notify the changes using callbacks.

How are uncontrolled components different from controlled components?

The uncontrolled components maintain their state, and their data is controlled by DOM. The Refs are used in uncontrolled components to get their current values instead of using props in case of controlled components.

Define HOC in React?

The full form of HOC is the Higher-Order Component. It is an advanced way of reusing the component logic, which wraps another component along with it.

What are the benefits of HOC?

There are several benefits of HOC, which include the following:

  1. Reuse of Code.
  2. Application of logic and bootstrap abstraction
  3. Offers a high hacking facility
  4. Supports state abstraction and manipulation
  5. It offers props manipulation

What are pure components?

Pure components include the components which are simple and easy to be written. They can easily replace any component which as a render().

Define Reducers in React?

Reducers are the pure functions that clearly states as to how the application state changes when certain actions are made. This way, it takes into account the previous state and action to turn out to a new state.

What is a store in Redux?

A store in Redux is a JavaScript object that can hold applications state and provide help to access them and applying dispatch actions along with register listeners.

Why do we need a Router to React?

We need a Router to React so that we could define the multiple routes whenever the user types a particular URL. This way, the application of a particular router can be made when the URL matches the path defined inside the router.

 

 

So, this brings us to the end of the ReactJS Interview Questions blog.
This Tecklearn ‘Top ReactJS Interview Questions and Answers’ helps you with commonly asked questions if you are looking out for a job in Front End Development. If you wish to learn ReactJS and build a career in Front End Development domain, then check out our interactive, ReactJS with Redux Training, that comes with 24*7 support to guide you throughout your learning period.

React.js with Redux Training

About the Course

Tecklearn’s React JS Training Course will help you master the fundamentals of React—an important web framework for developing user interfaces—including JSX, props, state, and events. In this course, you will learn how to build simple components & integrate them into more complex design components. After completing this training, you will be able to build the applications using React concepts such as JSX, Redux, Asynchronous Programming using Redux Saga middleware, Fetch data using GraphQL, perform Testing using Jest, successively Deploy applications using Nginx and Docker plus build Mobile applications using React Native. Accelerate your career as a React.js developer by enrolling into this React.js training.

Why Should you take React.js with Redux Training?

  • The average salary for “React Developer” ranges from $100,816 per year to $110,711 per year, based on the role (Front End Developer/Full Stack Developer) – Indeed.com
  • React Native Supports Cross-platform Development (iOS and Android), and it can reduce the development effort by almost 50% without compromising quality or productivity
  • Currently, React JS is being used by major companies like Walmart, Netflix, and HelloSign.

What you will Learn in this Course?

Introduction to Web Development and React.js

  • Fundamentals of React
  • Building Blocks of Web Application Development
  • Single-page and Multi-page Applications
  • Different Client-side Technologies
  • MVC Architecture
  • Introduction to React
  • Installation of React
  • JSX and its use case
  • DOM
  • Virtual DOM and its working
  • ECMAScript
  • Difference between ES5 and ES6
  • NPM Modules

 

Components, JSX & Props

  • React Elements
  • Render Function
  • Components
  • Class Component
  • Thinking In Components
  • What Is JSX
  • JSX Expressions
  • Creating Your First Component
  • Functional Components

 

React State Management using Redux

  • Need of Redux
  • Redux Architecture
  • Redux Action
  • Redux Reducers
  • Redux Store
  • Principles of Redux
  • Pros of Redux
  • NPM Packages required to work with Redux
  • More about react-redux package

React & Redux  

  • The React Redux Node Package
  • Provider Component
  • Connecting React Components with Redux Store
  • Reducer Composition
  • Normalization: Points to Keep in Mind When Designing a Redux Store
  • Redux Middleware

 

React Hooks

  • Caveat of JavaScript classes.
  • Functional components and React hooks
  • What are React hooks?
  • Basic hooks
  • useState() hook
  • How to write useState() hook when state variable is an array of objects
  • useEffect() hook
  • Fetch API data using useEffect() hook
  • useContext() hook
  • Rules to write React hooks
  • Additional hooks
  • Custom hooks

 

Fetch Data using GraphQL

  • What is GraphQL?
  • Cons of Rest API
  • Pros of GraphQL
  • Frontend backend communication using GraphQL
  • Type system
  • GraphQL datatypes
  • Modifiers
  • Schemas
  • GraphiQL tool
  • Express framework
  • NPM libraries to build server side of GraphQL
  • Build a GraphQL API
  • Apollo client
  • NPM libraries to build client side of GraphQL
  • How to setup Apollo client

 

React Application Testing and Deployment

  • Define Jest
  • Setup Testing environment
  • Add Snapshot testing
  • Integrate Test Reducers
  • Create Test Components
  • Push Application on Git
  • Create Docker for React Application

 

Introduction to React Native

  • What is React Native
  • Use of JSX elements With React Native
  • The anatomy of a React Native application
  • React Native installation and setup
  • Running the app on Android Simulator and Android Device
  • Working with Styles and Layout
  • Connecting React Native to Redux

 

React with Redux Projects

 

 

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Top React JS Interview Questions and Answers"

Leave a Message

Your email address will not be published. Required fields are marked *