React Interview Questions

Top 100 Best React Interview Questions & Answers 2021

Top 100 React Interview Questions and Answers

Q 1: What is React JS?

React Interview Questions – React.JS History

Current version of React.JS  V16.8.6
Initial Release to the Public (V0.3.0)
React.JS was first used 2011 for Facebook’s
Created By Jordan Walke
Create-react-app version  2.0
Create-react-app version 2.0 supports Babel 7, webpack 4, and Jest23.

React aka ReactJS or React.js is an open-source JavaScript library, developed by Facebook. With the component-based approach, it is useful in building user interface (UI) components for a single page application or mobile/web applications. It offers a simple programming model with a better quality performance.

React is mainly concerned with representing data to the data object model (DOM). The data it presents changes over time and can be updated based on the user’s action. Additional libraries (e.g. Redux and React router), state management and routing are required to create ReactJS applications.

Q 2: How does React JS work?

Here’s the sequence of steps to give you an idea about how it works:

  • Firstly, react creates a virtual DOM and runs the diffing algorithm to recognize the changes made in the virtual DOM
  • The second step is reconciliation, where it upgrades the DOM with new features
  • Next, the virtual DOM, which is lightweight in nature and is detached from the browser-specific implementation details
  • Subsequently, the ReactElements, present in virtual DOM are utilized to create basic nodes
  • Finally, when the ReactComponent changes the state; the diffing algorithm identifies the changes and automatically updates the DOM

Q 3: What are the features and advantages of ReactJS?

ReactJS is a JavaScript library offering some great features and advantages in web development and transforming the workflow. Leading companies, including PayPal, Apple, Netflix, etc. utilize it to improve framework performance.

Features of ReactJS are as follows: 

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

The advantages of ReactJS are as follows:

  • Simplifies the process of writing components
  • Improves productivity and makes maintenance smoother
  • Delivers an excellent solution for high-load application
  • Ensures stable code
  • Improves SEO (Search Engine Optimization) performance
  • Provides an easier way to integrate with frameworks
  • Ideal for mobile and web app development
  • Easy to grasp and learn

Q 4: What is DOM? 

DOM is a bona fide API (Application Programming Interface) for HTML and corresponding XML documents. It presents the logical structure of documents and how they are retrieved and coerced. The term “document” is commonly used in DOM specification, XML is deployed as a way of demonstrating the different kinds of information stored in various systems. XML displays the data as documents and DOM handles this data. DOM makes it easy for the programmers to create, add, modify or delete the elements and content of the documents.

Q 5: What is a virtual DOM?

Though the Virtual DOM objects hold similar properties as a real DOM object, it’s known as the compact version of a DOM object as it is unable to make any changes directly on the screen. Virtual DOM is more like making changes in software code than in the actual hardware. It is faster than DOM as it can be manipulated easily.

Q 6: What is JSX?

JSX means JavaScript XML, having the complete capabilities of JavaScript. It makes it easy to write HTML elements in JavaScript and also locate them in the DOM without any createElement() and/or appendChild() methods. Any HTML tags can be converted into react elements with JSX. Though it is not necessary to use JSX it’s really convenient to write React applicants with it.

Below is the syntax for a basic element in React with JSX and its equivalent without it.

Equivalent of the above using React.createElement

Q 7: Why can’t browsers read JSX?

React uses JSX (JavaScript Extension) that allows us to replicate HTML in JavaScript. Since JSX is not valid JavaScript, web browsers can’t read it directly. So, if JavaScript files have JSX, that file needs to be transpiled. A transpiler will be needed to convert JSX to regular Javascript that browsers can read and understand. The most popular transpiler right now is Babel.

Q 8: How different is React’s ES6 Syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in the following aspects:

// ES5
var React = require('react');
// ES6
import React from 'react';

********  export vs exports *********

// ES5
module.exports = Component;
// ES6
export default Component;

****** function *****
// ES5

var MyComponent = React.createClass({
  render: function() {
    return <h3> Hello CoderSera! </h3>
  },
});

// ES6
class MyComponent extends React.Component {
  render() {
    return <h3> Hello CoderSera! </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 *****

// 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>
  }
  render() {
    return;
    <h3> Hello, { this.state.name }! < /h3>
  }

Q 9: What is ReactDOM and how’s it different from React?

React, and ReactDOM are recently divided into two different libraries. All ReactDOM functionality was part of React, before v0.14.

ReactDOM acts as a bridge between React and the DOM, often used for mounting with ReactDOM. Another essential feature of ReactDOM is ReactDOM.findDOMNode() which provides you direct access to a DOM element.

For everything else, there’s React. It is used to define and create elements, for lifecycle hooks, etc. i.e. the guts of a React application. The React functionality is used in web and mobile applications whereas ReactDOM functionality is only for web apps.

Q 10: How to Create React component?

Below are the steps to create React components:

  • The class components are created by first naming it like “Example
  • A constructor is added to the class component to further add a state of the class component
  • Then, the Render method is introduced to return the JSX. The JSX must be wrapped in an outer element like
  • Now, the ‘this’ keyword must be bound inside the constructor, for it to be used anywhere
  • To use the component, make sure it is imported into a file (in case the components are in separate files). Once imported, add the assigned name to the JSX
  • Then, the specific ‘Props’ are passed to the component. Each prop must be given a name
  • The props must be put into the arguments for the components to receive them. Once received, they can be accessed in the JSX by using ‘this.props.NameOfProp
  • Once all the above steps are performed, the code can be completed

Difference between Angular 4 and angular 6

Q 11: What is the purpose of render() in React?

The render() function must return something, be it null. The component file is called the render() method by default as the component needs to present the HTML markup or JSX syntax. Each React component must have a render() mandatorily. The single React element returned represents the native DOM component. If there’s more than one HTML element is rendered, they must be grouped together inside one enclosing tag such as <form>, <group>,<div>, etc. The function must return the same result every time it is invoked.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (<div> <h1 className='App-title'> hello CoderSera </h1></div>)
  }
}

export default App;

Q 12: Differences between the class component and functional component?

A functional component is kind of a standard JavaScript function. 

 

Class components enable us to use additional features, including local state and lifecycle hooks. It specifies to extend from React and enable the component to have direct access to the store and thus holds state.

 

When the props are received by the component and rendered to the page, for this ‘stateless component’ pure function can be used. They are also known as dumb components or presentational components.

Q 13: What are the Pure components in ReactJS?

Pure components play a vital role to re-render a component. The pure component helps to use the lifecycle method for comparing the states or props for any changes in the properties before re-rendering the component.

In brief, pure components are meant to evaluate and compare the properties of the current state or prop with the next one and also check how the parent component is different from the child component in the hierarchy.

Q 14: 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')

Q 15: What is the arrow function in React? How is it used?

The fat arrow => is meant to define anonymous functions. It is one of the effective and easy ways to pass parameters to callback functions. Make sure to optimize the performance while using it.

Note: Using an arrow function in the render method creates a new function every time the component renders, which may have performance implications

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

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

Below are the different phases of React component’s lifecycle:

  • Initialization

In the initialization phase, defaults and initial values for this.props and this.state are defined.

  • Mounting

Mounting is the process that takes place when a component is being inserted into the DOM.

  • Updating

In this phase, the component is updated whenever the state is changed or the component receives a new prop.

  • Unmounting

This is the phase when the component is unmounted from the DOM.

Q 17: Differentiate between the controlled and uncontrolled components in React?

While creating web pages in ReactJs, the form data is handled by React components using ‘controlled’ elements

(e.g., this.state = {}, in case of defaultValue = {this.state.username}
 onChangeText = {text => this.setState({username: text})}, 
And
defaultValue = {this.state.password}
onChangeText = {text => this.setState({password: text})}). 

Similarly, in the case of uncontrolled components, the form data is handled by the DOM itself instead of React.

(e.g., console.log(this._username, this._password)
  <Text>Username</Text>
  <TextInput
          ref={input => this._username = input}
/>
  <Text>Password</Text>
  <TextInput
\
/>)

Note: Refs=uncontrolled elements, state= controlled elements

Q 18: How can you differentiate between the state and props in ReactJS?

State: The state is a data structure that belongs to a single component and changes its output to respond to certain events over time. The states are managed by the component in its entirety.

Prop: Props, on the other hand, are read-only functions. Throughout the component’s lifecycle, they display a fixed character. They are stateless and are utilized to customize components at the time of their creation.

Q 19: What is the difference between the HTML and React event handling process?

HTML events are written in lowercase, whereas React events are written using camelCase;

Unlike HTML events, the coder can’t stop or prevent a default behavior by returning false. It must be stated as ‘preventDefault’.

Q 20: What are higher-order components?

Higher-order component (HOC) is a technique developed to reuse components in React. React API has nothing to do with HOC. HOC is a pattern that is the outcome of React’s compositional nature. A higher-order component is a function that guides a component and returns a new component.

Advance react js interview questions

Q 21: How to embed two components in one component?

import React from 'react';
class App extends React.Component{
    render(){
        return(
            <div>
            <Header/>
            <Content/>
            </div>
        );
    }
}
class Header extends React.Component{
    render(){
        return(
            <div>
            <h1> Header</h1>
            </div>
         )
    }
}
class Content extends React.Component{
    render(){
        return(
            <h2>Content</h2>
            <p>The Content Text!!!</p>
            </div>
        )
    }
}
export default App;

Q 22: What is Redux?

It is a predictable state container for JS Apps. Redux is a small open-source JavaScript library for managing application states. It is a limited and straightforward API designed to be a predictable container for the application state. It is executed similarly to the rendering function. The functional programming language Elm has a significant impact on Redux. It is commonly used with libraries such as React or angular for building UI. It is similar to Flux

Q 23: What is the Use of Redux thunk?

Redux thunk is middleware that enables to write action creators that return functions instead of actions. It can be also used as a delay function for delaying the dispatch of action if a certain condition is met. The two store methods getState() and dispatch() act as parameters to the inner function.

In order to activate Redux thunk, applyMiddleware() method should be used as shown below:

Q 24: What do you know about Flux?

Flux is a basic illustration to maintain the unidirectional data stream. It is utilized to control construed data unique fragments to make them interface with that data without any issues. Flux configuration is insipid; it’s neither specific to React applications, nor is required to collect a React application.

Q 25. Is setState() is async? Why is setState() in React Async instead of Sync?

setState() actions are asynchronous and are batched for performance gains.

setState() does not immediately change this.state but creates a pending state transition. Accessing this.state after this method can potentially get the existing value. There is no guarantee of synchronous operation of calls to setState. Since setState alters the state and causes re-rendering, it can be an expensive operation that can make synchronous, leaving the browser unresponsive. Thus the setState calls are asynchronous as well as batched for better user interface experience and performance.

Q 26: Explain the role of the reducer?

With the rise of Redux as a State Management Solution, the concept of reducer became quite popular in JavaScript. Reducers are meant to handle state in an application and an individual doesn’t need to master Redux to understand Reducers.

Q 27: What is a React router and also explain its advantages?

With user action or request, routing is meant to direct users to different pages. ReactJS Router is used to create a single-page web application. It describes multiple routes in the application. When a user types a specific URL in the browser, a particular route is redirected. On top of the React, a React Router standard library system is created and with the help of React Router Package, a routing is created in the React application.

Advantages:

  • Standardized structure viewing declarations make it easy to know what are our app views quickly
  • Slow code loading
  • It is easy to manage the nested views and the progressive resolution of views using React Router
  • User can navigate backward/forward and restore the state of the view by using the browsing history feature

Q 28: Why we need a Router to React?

React Router plays a vital role in displaying multiple views in a single page application. In React application, various views cannot be viewed in the absence of React Router. It is used in various social media websites like Facebook and Instagram to render multiple views.

Q 29: What are synthetic events in React?

Synthetic events are the objects that act as a cross-browser wrapper around the native event of the browser. They help to combine distinct browser conduct into one API. This is performed to ensure coherent characteristics are shown in the occurrences across multiple browsers.

Q 30: What do you understand by refs in React?

Refs are References in React’s shorthand. It is an attribute meant to store a reference to a specific element or component which is returned by the configuration function of the rendering components. It is utilized to return references to a particular render returned element or component. When DOM measurements are needed or techniques are added to the parts, they come in handy.

class ReferenceDemo extends React.Component{
     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>
     );
   }
 }

Q 31: List some of the cases where you should use Refs?

Following are the cases when refs should be used:

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

Q 32: What is the difference between createElement and cloneElement?

createElement is the element that JSX gets transpiled to and is used by React to make React Elements (protest representations of some UI).

cloneElement is used as a part of a request to clone a component and pass it new props.

Q 33: What is the second argument that can optionally be passed to setState and what is its purpose?

A callback work will be invoked when setState has completed and the part is re-rendered. Since setState is asynchronous, it takes the callback function instantly. However, it’s best to utilize another lifecycle strategy instead of depending on this callback function, however, it’s great to know it exists.

Class Training extends Course
{
this.state = {
sampleItem: 'learn',
}
handleChange = (event) => {
console.log(this.state.sampleItem)
this.setState({
sampleItem: event.target.value      //event.target.value = Welcome
}, () => console.log(this.state.sampleItem))
};

Output:

Learn

Welcome

Q 34: What exactly would you do if the expression contains more than one line?

In such a condition, the multi-line JSX expression should be enclosed. Sometimes, it is essential to avoid multi-lines to perform the task reliably and get desirable results.

Q 35: Is it possible to nest JSX elements into other JSX elements?

Yes, it is possible and the process is similar to nesting the HTML elements except for a few things. Individual needs to be familiar with the source and destination elements in order to perform the task easily.

Q 36: How to handle a Router Redirect after a user has logged in?

The React hooks play a vital role in helping define web page visits (using the ‘routing’ analogy) by users (react-router-dom in case of web applications). When a user logs into a web app, he would be redirected to the homepage.

Firstly, we would need to set up a protected component before it is rendered to match a route. A ‘ProtectedRoute’ is created to help the user pass the ‘loggedIn’ state to the desired state object path defined by the creator.

Every login string must have a ‘pathname’ of ‘/’ so when the NavLink is acted upon, the user can be redirected to the login page (in case of correctly entered credentials) or homepage with an error description like ‘Authorization Failed’ (in case of incorrect credentials).

Q 37: How can you validate props in React?

Prop validation enables React components used in the app’s development to be rendered into easily formattable codes and error-free systems for future usage. It is beneficial in improving the React components. To achieve prop validation, running ‘Typechecking’ with ‘PropTypes’ is recommended. E.g.,

Import React, { Component } from ‘react’;
Import ‘./App.css’;
Import PropTypes from ‘prop-types’; 
Const Test = (props) => {
return( <h1>
{
props.str}<h1>
}

To check and validate a property in the above snippet,

Test.propTypes = { str:PropTypes.string }

Now, change the string type to boolean, e.g.,

Test.propTypes = { str:PropTypes.bool <em>}</em>

Once run this comes up with an error message, for the prop supplied and expected are different. 

To validate the PropType and avoid any warning or error messages, the following code snippet can be rendered:

Const Test = (props) => {
return(
       <div>
       <h1>{props.str}<h1>
       <h1>{(props.bool ? ‘bool’ : ‘no bool’)}<h1> 
       </div>
Test.propTypes = {
     str:PropTypes.string,
     bool: PropTypes.bool
}
Class App extends Component {
     render() {
          return  (
    <div className=”App”>
        <Test
        str={‘xyz’} => (str can be any pathname)
         bool={true}
          />
Or, 
Const Test = (props) => {
return(
       <div>
       <h1>{props.str}<h1>
       <h1>{(props.bool ? ‘bool’ : ‘no bool’)}<h1> 
       </div>
{
    props.ary.map((val)=> {
return(<li key={val}>{val}</li>         =>(a list must be accompanied with a key property) 
Test.propTypes = {
     str:PropTypes.string,
     bool: PropTypes.bool
     strOrNum: PropTypes.one0fType( [PropTypes.string, PropTypes.number] )
     ary:PropTypes.array0f(PropTypes,number)
}
Const Test = (props) => {
return(
       <div>
       <h1>{props.str}<h1>
       <h1>{(props.bool ? ‘bool’ : ‘no bool’)}<h1> 
       </div>
{
    props.ary0f0bj.map((val)=> {
return(<li key={val.age}>{val.name}</li>
Class App extends Component {
     render() {
          return  (
    <div className=”App”>
        <Test
        str={‘xyz’} => (str can be any pathname)
        bool
         strOrNum={10} => (if we denote a number, the rendering will pass the component)
 But, strOrNum={true} => (will fail, for it is not a number)
Let’s introduce a number array after this, i.e.,
         ary={[1,2,3]
         ary0f0bj={ [ {name:’max’, age:7}, {name:’hugh’, age:’10’] }
  />
  </div>

Q 51: What is the difference between Element and Component?

An Element is defined as a plain object that decides what should be presented on the screen; regarding DOM nodes or other components. Elements can contain other Elements in their props. It is easy to create a React element and once created, it is immutable.

The object representation of React Element would be as follows:

const element = React.createElement(
  'div',
  {id: 'login-btn'},
  'Login'
)
The above React.createElement() function returns an object:

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}
And finally it renders to the DOM using ReactDOM.render():

<div id='login-btn'>Login</div>

A component can be declared in many different ways. It can either be a class with a render() method or a function. In both cases, it takes props as an input and reverts a JSX tree as the output:

const Button = ({ onLogin }) =>
  <div id={'login-btn'} onClick={onLogin}>Login</div>
Then JSX gets transpiled to a React.createElement() function tree:

const Button = ({ onLogin }) => React.createElement(
  'div',
  { id: 'login-btn', onClick: onLogin },
  'Login'
)

Q 52: What is state in React?

State of a component is an object that keeps some information about the component that may change. It is essential to keep the state as simple as possible and reduce the number of stateful components.

Let’s create a user component with message state,

class User extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      message: 'Welcome to React world'
    }
  }

  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    )
  }
}
state

Though state is similar to props, but it is private and managed by the component. It is only accessible by the component that owns and sets it.

Q 53: Why should we not update the state directly?

If the state is updated directly, then re-rendering of the component won’t be possible.

//Wrong
this.state.message = 'Hello world'

Instead use setState() method. It sets an update to a component’s state object. The component replies by re-rendering, once the state changes.

//Correct
this.setState({ message: 'Hello World' })

Note: State object can be directly assigned either in a constructor or using the latest javascript’s class field declaration syntax.

Q 54: How to bind methods or event handlers in JSX callbacks?

Here are the 3 possible ways to achieve this:

Binding in Constructor: In JavaScript, class methods are not bound by default neither do the React event handlers aka. class methods. Generally, they are bind in constructor.

class Component extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    // ...
  }
}

Public class fields syntax: If you don’t prefer bind approach, public class fields syntax can be utilized to accurately bind callbacks.

handleClick = () => {
  console.log('this is:', this)
}
<button onClick={this.handleClick}>
  {'Click me'}
</button>

Arrow functions in callbacks: Arrow functions can be used directly in the callbacks.

<button onClick={(event) => this.handleClick(event)}>
  {'Click me'}
</button>

Note: When the callback is passed as prop to child components, they would need to do an extra re-rendering. In such cases, it is essential to go with .bind() or public class fields syntax approach to improve performance.

Q 55: How to pass a parameter to an event handler or callback?

An arrow function is utilized to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />

This is an equivalent to calling .bind:

<button onClick={this.handleClick.bind(this, id)} />

Along with these two approaches, arguments can also be passed to arrow function.

<button onClick={this.handleClick(id)} />
handleClick = (id) => () => {
    console.log("Hello, your ticket number is", id)
};

Q 56: How to tell React to build in Production mode and what will that do?

Generally, Webpack’s DefinePlugin strategy is used to set NODE_ENV to production. This will remove things like propType approval and additional warnings. It is a good idea to minify the code, for instance, React uses Uglify’s dead-code end to remove development only code and remarks, which will completely reduce the measure of your package.

Q 57: What are inline conditional expressions?

You can use either if statements or ternary expressions. Ternary expressions are available from JS to conditionally render expressions. Apart from these methods, one can also surround any expressions in JSX by wrapping them in curly braces, followed by JS logical operator (&&).

<h1>Hello!</h1>
{
    messages.length > 0 && !isLogin?
      <h2>
          You have {messages.length} unread messages.
      </h2>
      :
      <h2>
          You don't have unread messages.
      </h2>
}

Q 58: What is the difference between reacting and containers?

React is the combination of two components i.e. smart component (containers) and dumb (presentation component). Containers are quite similar to components, the only difference is the containers are concerned about the application state.

Q 59: What are some of the cases when you should use Refs?

Refs can be used in the following scenarios:

  • To handle focus, select text or media playback
  • To prompt essential animations
  • To combine with third-party DOM libraries

Q 60: What are hooks?

Hooks is a new feature that allows you to utilize state and other React features without writing a class.

Let’s see an example of useState hook example,

import {useState} from 'react';

function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>)
}

Q 61: What were the major problems with MVC framework?

Below are some of the major issues with MVC framework:

  • MVC fails to solve the code complexity, code re-use & no- flexibility problem
  • It doesn’t guarantee decoupled code

Q 62: What are the components of Redux?

Redux consists of the following components:

  • Action – It’s an object that describes what happened
  • Reducer – The changes in state are determined here
  • Store – Entire application state/object tree is saved in the Store
  • View – The data provided by the Store is displayed here

Q 63: What is the difference between Shadow DOM and Virtual DOM?

The Shadow DOM is a browser technology meant to assess variables and CSS in web components.

The Virtual DOM is a concept executed by libraries in JavaScript on top of browser APIs.

Q 64: What is React Fiber?

Fiber is the new reconciliation engine where core algorithm is re-implemented in React v16. The aim of React Fiber is to improve its suitability for different areas, including animation, layout, gestures, ability to pause, terminate or reuse work and prioritize different types of updates and latest concurrency primitives.

Q 65: What is Lifting State Up in React?

When different components want to share the same changes in data then it is essential to lift the share state up to their nearest common ancestor. In brief, if two child components need to share the same data from its parent, then instead of maintaining local state in both child components, move the state to the parent.

Q 66: What is context?

Context is an effective way to pass the data alone through the component tree without the props at every level.

For instance, authorized user, locale preference, UI theme need to be evaluated in the application by many components.

const {Provider, Consumer} = React.createContext(defaultValue)

Q 67: How to write comments in React?

The comments in React/JSX are quite similar to JavaScript Multiline comments except they are wrapped in curly braces.

Single-line comments:

<div>
  {/* Single-line comments(In vanilla JavaScript, the single-line comments are signified by double slash(//)) */}
  {`Welcome ${user}, let's play React`}
</div>

Multi-line comments:

<div>
  {/* Multi-line comments for more than
   one line */}
  {`Welcome ${user}, let's play React`}
</div>

Q 68: What is the purpose of using super constructor with props argument?

A child class constructor needs to call super() method to use this reference. And the same applies for ES6 sub-classes as well. The reason behind passing props parameter to super() call is to utilize this.props in the child constructors.

Passing props:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    console.log(this.props) // prints { name: 'John', age: 42 }
  }
}
Not passing props:

class MyComponent extends React.Component {
  constructor(props) {
    super()

    console.log(this.props) // prints undefined

    // but props parameter is still available
    console.log(props) // prints { name: 'John', age: 42 }
  }

  render() {
    // no difference outside constructor
    console.log(this.props) // prints { name: 'John', age: 42 }
  }
}

It shows that this.props is different only within the constructor else it would be the same outside the constructor.

Q 69: What is hoisting?

Hoisting is a mechanism required to move the declarations to the top of the execution scope. Your code is compiled by JavaScript before execution. When the compiler reaches an execution context, it will start splitting and evaluating the code while finding & creating a list out of the declarations. Every time it (compiler) finds a declaration, it will create a binding and when it finds an assignment or evaluation, it will look for the binding scope. If the binding couldn’t be found, it will look for the global scope. If the strict mode is on, it will show an error and if es5 is being utilized, it will create a new binding. This helps assign a variable which wasn’t declared before. After going through some steps, it will create some compiled code which can be executed then.

Q 70: What is reconciliation?

When a component’s props or state change, React will decide whether an actual DOM update is required by comparing the new and previous element rendered. If they are not equal, React will update the DOM. This entire process is known as reconciliation.

Q 71: What is Relay?

Relay is a JavaScript framework which supports an information layer and user-server connection to web applications using the React view layer.

Q 72: What is prop drilling and how to avoid it?

When you need to build a React application, a deeply nested component is required that can utilize the data provided by another component that is higher in the hierarchy. The easiest way is to pass on a prop from each component to the next from the source to the deeply nested component. This process is called prop drilling.

In order to avoid prop drilling, React Context is used. This allows a provider component supplying data to be defined and also enables nested components to consume context data through either a consumer component or a usecontext hook.

Q 73: What is React map?

A map is a data collection type which stores data in pairs. It has a unique key. The data stored in the map must be mapped to the key. It is not possible to store a duplicate pair in the map() because every stored key is unique. With this, it is easy and quick to search specific data.

Q 74: What is Redux DevTools?

Redux DevTools is meant for live-editing or debugging application’s state change. It features hot reloading, action replay and customizable UI. If you don’t want to install and integrate Redux DevTools in your project, consider using Redux DevTools extensions for Firefox and Chrome.

Q 75: What is code-splitting in React?

Code-splitting is a feature for bundlers like Webpack, Rollup and Browserify to develop multiple bundles which can be actively loaded at the runtime.

For instance, it will separate moduleA.js and all its unique dependencies which will load when the ‘Load’ button is clicked. moduleA.js

const moduleA = 'Hello';

export { moduleA };

App.js

import React, { Component } from 'react';

class App extends Component {
  handleClick = () => {
    import('./moduleA')
      .then(({ moduleA }) => {
        // Use moduleA
      })
      .catch(err => {
        // Handle failure
      });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Load</button>
      </div>
    );
  }
}

export default App;

Q 76: How to set state with a dynamic key name?

If you are utilizing ES6 or the Babel transpiler to change JSX code then you can achieve this with computed property names.

handleInputChange(event) {
  this.setState({ [event.target.id]: event.target.value })
}

Q 77: Why React uses className over class attribute?

class is a keyword and JSX is an extension in JavaScript. That’s the main reason why React utilizes className instead of class. Pass a string as the className prop.

render() {
  return <span className={'menu navigation-menu'}>{'Menu'}</span>
}

Q 78: What are fragments?

Fragment is a common pattern in React which is utilized to return multiple elements. It enables you to group a list of children without any need to add extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  )
}
There is also a shorter syntax, but it's not supported in many tools:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  )
}

Q 79: Why fragments are better than container divs?

  • Fragments act faster and don’t use much memory as they don’t create an extra DOM node. This is really beneficial for very large and deep trees.
  • Some CSS mechanisms like Flexbox and CSS Grid hold a special parent-child relationships; in order to keep the preferred payout, divs are not added in the middle.
  • The DOM Inspector is less cluttered.

Q 80: What are portals in React?

Portal is considered to render children into a DOM node that occurs outside the DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container)

First argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.

Q 81: What is Stateful Components?

A stateful component is a component that is dependent on the state of the component. They are class components that are initialized in the constructor.

import React, { Component } from 'react';
class SecondComponent extends Component {
 	constructor(props) {
 	super(props);
 this.state = {
 	toggle: true
 	};
 	// This is to bind context when passing onClick as a callback
 	this.onClick = this.onClick.bind(this);
 }
 onClick() {
 	this.setState((prevState, props) => ({
 	toggle: !prevState.toggle
 	}));
 }
 render() {
 return (
 		<div onClick={this.onClick}>
 			Hello, {this.props.name}! SecondComponent is called.
 		<br />
 		Toggle is: {this.state.toggle}
 		</div>
        );
             }
      }

Q 82: What are Stateless Functional Components?

In various applications smart components having state, render dumb components, receiving props and returning HTML as JSX. Stateless functional components are significantly more reusable and have a positive impact on the application.

They have two main characteristics:

When rendered, they receive an object along with all the props that were passed down.

They should restore the JSX to be rendered.

// When using JSX inside a module we should import React

import React from 'react';
import PropTypes from 'prop-types';
const FirstComponent = props => (
 <div>
 Hello, {props.name}! FirstComponent is called.
 </div>
);
//arrow components also can have props validation
FirstComponent.propTypes = {
      name: PropTypes.string.isRequired,
}

// It can use FirstComponent in another file it must be exposed through an export call:

export default FirstComponent;

Q 83: How to apply validation on props in React?

When the application is running in development mode, all the props will be checked by React automatically, ensuring they have the correct type. React will engender warning messages in the console if the type is incorrect. Due to the performance impact, it is deactivated in production mode. The mandatory props are defined with isRequired.

The set of predefined prop types:

  • number
  • string
  • array
  • object
  • func
  • node
  • element
  • bool
  • symbol
  • any

We can define propTypes for User component as below:

import React from 'react'
import PropTypes from 'prop-types'

class User extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired
  }

  render() {
    return (
      <>
        <h1>{`Welcome, ${this.props.name}`}</h1>
        <h2>{`Age, ${this.props.age}`}</h2>
      </>
    )
  }
}

Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.

Q 84: What are error boundaries in React v16?

Error boundaries are components that find JavaScript errors which happen anywhere in the child component tree, log those errors and show a fallback UI instead of the crashed component tree.

A class component will be an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static getDerivedStateFromError() :

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { hasError: false }
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info)
  }

  static getDerivedStateFromError(error) {
     // Update state so the next render will show the fallback UI.
     return { hasError: true };
   }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>{'Something went wrong.'}</h1>
    }
    return this.props.children
  }
}
After that use it as a regular component:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Q 85: What is ReactDOMServer?

The ReactDOMServer object is meant to render components to static markup which is used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:

renderToString()

renderToStaticMarkup()

For instance, when you run a Node-based web server like Express, Hapi, or Koa, and call renderToString to render your root component to a string, which you then send as response.

// using Express
import { renderToString } from 'react-dom/server'
import MyPage from './MyPage'

app.get('/', (req, res) => {
  res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>')
  res.write('<div id="content">')
  res.write(renderToString(<MyPage/>))
  res.write('</div></body></html>')
  res.end()
})

Q 86: How to use innerHTML in React?

The dangerouslySetInnerHTML attribute acts as React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is unsafe to use this attribute due to cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.

In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

function createMarkup() {
  return { __html: 'First &middot; Second' }
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />
}

Q 87: What is the impact of indexes as keys?

Keys are needed to be stable, unique and foreseeable for React to track all the elements.

In the below code snippet, each element’s key will be formed on ordering, instead of tied to the represented data. This limits the optimizations that React can do.

{todos.map((todo, index) =>
  <Todo
    {...todo}
    key={index}
  />
)}

When you use element data for a unique key, let’s say, todo.id is unique to this list and stable, React would automatically reorder elements without considering much.

{todos.map((todo) =>
  <Todo {...todo}
    key={todo.id} />
)}

Q 88: How you implement Server Side Rendering or SSR?

React is prepared to take care of rendering on Node servers. A distinct version of the DOM renderer is available which creates a similar pattern as on the client-side.

import ReactDOMServer from 'react-dom/server'
import App from './App'

ReactDOMServer.renderToString(<App />)

This method will return the regular HTML as a string, which can act as a server response inside a page body. On the client-side, React spots the pre-rendered content and picks up from where it ended.

Q 89: What is React Mixins?

Mixins are meant to separate elements from having standard functionality. One should refrain from using it or replacing it with higher-order components or decorators.

 import React from 'react';
var MyMixin = {
 doSomething() {
 }
};
const MyComponent = React.createClass({
 mixins: [MyMixin],
 handleClick() {
 this.doSomething(); // invoke mixin's method
 },
 render() {
 return (
 <button onClick={this.handleClick}>Do Something</button>
 );
 }
});
export default MyComponent;

Q 90: How to debug your React Native?

Follow the below steps to debug React Native app:

  • Run the application in the iOS simulator
  • Once the Command + D is pressed, a webpage will open at http://localhost:8081/debugger-ui
  • Enable Pause On Caught Exceptions for an exceptional debugging experience
  • Press Command + Option + I to open the Chrome Developer tools, or open it via View -> Developer -> Developer Tools
  • Now you can debug the React Native app

Q 91: What is the objective of getDerivedStateFromProps() lifecycle method?

A new static getDerivedStateFromProps() lifecycle method is raised after an element is represented and before it is re-rendered. It can either return an object to refresh the state or nullify stating that no state updates are required by the new props.

Example

 class MyApp extends React.Component {
  static getDerivedStateFromProps(props, state) {
    // ...
  }
}

Q 92: What is render hijacking?

The render hijacking is the ability to control what output a component will give from another component. It is done when we adorn our component by wrapping it into a Higher-Order component. One can add more props or develop other changes which can lead to a change in the logic of rendering. It won’t allow hijacking but through HOC, one can make the component to behave differently.

Q 93: What is Jest?

Jest is a JavaScript unit testing framework by Facebook. It is dependent on Jasmine and gives automated mock creation and a jsdom environment. It is basically used for testing elements.

Q 94: What is React Intl and its features?

The React Intl library establishes internalization in React clear, with off-the-shelf elements and an API that can manage various things, including formatting strings, dates, numbers, as well as pluralization. React Intl is part of FormatJS, which offers bindings to React through its components and API.

The react intl can:

  • Display numbers with separators
  • Display dates and times accurately
  • Be utilized to pluralize labels in strings
  • Support over 150+ languages
  • Run in the browser and Node
  • Be used to build on standards

Q 95: What is the difference between componentWillMount and componentDidMount?

componentWillMount() componentDidMount()
This is called only once during the entire lifetime before rendering the component to the server. It is used to evaluate props and perform any extra logic set upon them. It can be only called on the client end and is generally performed after the initial render when the client has obtained data from the server.
It is utilized to make state changes before the initial render. Apart from state changes, it enables you to make all kinds of advanced interactions.
One can’t “pause” rendering while awaiting the data to come. It is used to employ long-running processes within a component.
It is called immediately after the mounting took place. The data loading code is utilized to obtain data from the client’s end.
It is essential to avoid using any async initialization to prevent any side-effects or subscriptions in this method. Here, the data needs the initial render to be done to load properly. Therefore, users need to set an initial state accurately to eliminate undefined state errors.

Q 96: What is a switching component?

A switching component renders one of many components. Make sure to use the object to map prop values to components.

For example, a switching component displaying different pages regarding page prop:

import HomePage from './HomePage'
import AboutPage from './AboutPage'
import ServicesPage from './ServicesPage'
import ContactPage from './ContactPage'

const PAGES = {
  home: HomePage,
  about: AboutPage,
  services: ServicesPage,
  contact: ContactPage
}

const Page = (props) => {
  const Handler = PAGES[props.page] || ContactPage

  return <Handler {...props} />
}

// The keys of the PAGES object can be utilized in the prop types to spot dev-time errors.
Page.propTypes = {
  page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
}

Q 97: Why is isMounted() an anti-pattern and what is the proper solution?

The isMounted() is used to avoid calling setState() after a component has been unmounted as it starts producing warnings.

if (this.isMounted()) {
  this.setState({...})
}

Checking isMounted() before calling setState() does not only remove the warning, but also the reason for it. Using isMounted() is a code smell as you would only check it thinking that there might be a reference after the component has unmounted.

The best solution would be to look for places where setState() might be called after a component has unmounted, and fix them. Such conditions arrive when callbacks occur, when a component, waiting for some data gets unmounted prior to the data arrival. Moreover, it is ideal to cancel any callbacks in componentWillUnmount(), prior to unmounting.

Q 98: What is the difference between super() and super(props) in React using ES6 classes?

It is essential to pass props to super() method in order to use this.props in constructor().

Using super(props):

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    console.log(this.props) // { name: 'John', ... }
  }
}
Using super():

class MyComponent extends React.Component {
  constructor(props) {
    super()
    console.log(this.props) // undefined
  }
}
Outside constructor() both will display same value for this.props.

Q 99: What is the mental model of redux-saga?

Saga is a separate thread which is meant to take care of the side effects. redux-saga is a redux middleware library that handles the side effects in the app efficiently. One can simply start, pause and cancel the thread from the main application. Additionally, it can do both – use Redux application state and dispatch Redux actions.

Q 100: How to add a bootstrap for a react application?

There are three ways to add bootstrap to your React app: 

Using the Bootstrap CDN: Here, you can add both bootstrap CSS and JS resources in a head tag.

Bootstrap as Dependency: This is the best option for adding bootstrap, especially when you are using a build tool or a module bundler such as Webpack.

npm install bootstrap

React Bootstrap Package: In this case, you can add Bootstrap through a package that has recreated Bootstrap components in accordance with React components. Below packages are popular in this category,

react-bootstrap

reactstrap

 

Exit mobile version