opencodez

51 Most Important ReactJS Interview Questions and Answers

To conclude our 6 Articles Series on ReactJS, here we are providing 51 Most Important and Frequently Asked ReactJSInterview Questions. These questions will be very useful for you to crack an interview and help you to make career in ReactJS.

ReactJS Tutorial Index

  1. ReactJS Tutorial# 1 – An Introduction
  2. ReactJS Tutorial# 2 – Components and Props
  3. ReactJS Tutorial# 3 – Component State and Lifecycle
  4. ReactJS Tutorial# 4 – Forms, Events, and Keys
  5. ReactJS Tutorial# 5 – React Flux and Redux
  6. ReactJS Tutorial# 6 – ReactJS Best Practices
  1. What is Reactjs :

ReactJS is a frontend Open source Javascript library initially developed by Facebook. React was used on facebook.com in 2011 and one year later it was used on instagram.com. In 2015, Facebook has announced react-native, another library that uses the same architecture to create native Android and iOS applications.

  1. Mention five benefits of ReactJS :

Easy learning curve :

React is easy to learn. Anyone with a good understanding of HTML, CSS and Javascript can learn to react easily.

Readability :

React uses JSX that improves the readability of the code.

Performance :

React uses virtual DOM to update the UI that doesnxt require to update the whole webpage for every single change. That makes the application faster.

Reusable components :

We can use one component in many places without rewriting the code.

SSR :

React supports server-side rendering that improves the page load time.

  1. What is Server side rendering? Does react support it?

React supports server-side rendering. Server-side rendering is the process of rendering a web page on the server side than in the browser. It makes the page load time faster. SSR improves the performance, SEO and user experience.

  1. What is JSX?

JSX or JavaScript XML is used in React to include XML/HTML code in JavaScript code. Later, transpilers like babel can transform these code into proper javaScript code. We can use React without JSX but JSX makes it more elegant.

render(){
 return(
 xdivx
 xh1xHello Worldx/h1x
 x/divx
 );
}
  1. What is virtual DOM in React?

Manipulating the real DOM makes one web application slow. React creates one virtual DOM for each real DOM object. The virtual DOM has the same properties as the real DOM and we can manipulate it faster than a real DOM. In react, all operations are performed on the virtual DOM object.

  1. Can browser read JSX files?

The browser canxt read JSX code. JSX is not the actual JavaScript. Browsers are designed to read only JavaScript. So, a transformer like babel is used to convert JSX code to JavaScript objects.

  1. What is a React component?

React components are the basic building block of a react application. These are like functions that take inputs and returns one react element based on the inputs. Using the components, we can split an application into reusable, independent pieces.

  1. What are the types of React component?

React components can be categorized into two types :

  1. Explain the function and class components.

Function component :

Function components are actually JavaScript functions. These functions return a react element based on input properties. For example :

function Header(props){
   return xh1xHi , {props.message}x/h1x
}

Class components :

Class components are JavaScript ES6 class that extends xReact.Componentx.  For example :

class Header extends React.Component {
    render() {
        return xh1xHi, {this.props.message}x/h1x;
    }
}
  1. When to use a class component in React?

A class component is used if we have to deal with state or lifecycle methods. Function components are preferred otherwise.

  1. What is React State?

React xstatex is an object that determines how a component renders and how it behaves. The state holds information that may change over the lifetime of a react component. The state is a private property of a component. Based on the value of a state, the react component updates its UI.

  1. What are React props?

props are used to pass data to a component. They can hold single or multiple sets of values to pass to a component. They are mainly used to pass data to a component and to trigger any state changes.

  1. Is there any difference between React state and props?

props and state both are used to hold data or information about a react component. xstatex objects are private and they are accessible only inside a component. xpropsx are used to pass data from one component to another component.

  1. How can we update state in react?

We can update the xstatex of a react component directly or indirectly. If we update it directly, it will not update the UI element linked to the state. The preferred way to update a xstatex is to use xsetStatex method. This method updates a state object and re-renders the component automatically.

  1. How does xsetStatex function work?

xsetStatex function is used to update the state of a react component. If the UI of the component is dependent on the value we are updating, it will re-render the UI. For example :

setState({message : 'Hello'})
  1. How to write a callback function in xsetStatex?

We can use one callback function in the xsetStatex method that will invoke when the state is updated and the UI is re-rendered. For the callback, it is recommended to use React lifecycle methods rather than the callback method.

setState({message : 'Hello'}, () =x console.log("Inside the callback method"))
  1. What are the main differences between xstatex and xpropsx?
  1. What is a stateless component?

A stateless component has no xstatex. It may take one props as an argument and returns a react element based on the values of the xpropsx. These components also donxt have a lifecycle.

  1. What is a stateful component?

xstatefulx components are class components. They have one xstatex that is used for UI re-rendering.

  1. List all react lifecycle methods.

Following are the lifecycle methods for React (16.3+) :

  1. How to write React comments?

We can write comments in react as like below :

xdivx

   {/* This is a single line comment */}
   
   {/* This is a
       multiline
       comment 
   */}

x/divx
  1. What is an event?

Events are triggered with respect to few specific user actions like a mouse click, keypress etc. Each event contains a set of different properties.

  1. Show one example of an event.
function ClickHandler() {
   function onClicked(e) {
      console.log('Hello world is clicked.');
   }
   
   return (
      xa href="#" onClick={onClicked}x
      Hello world
      x/ax
    );
}
  1. What is xSyntheticEventx?

SyntheticEvent is a cross-browser wrapper around the browserxs native event. It is the same as the browserxs native event. It works identically across all browsers.

  1. Can you use xaddEventListenerx in react?

xaddEventListenerx is not recommended to use in xReactx. Instead of adding a listener when the element is created, we should provide one listener during the initial rendering time of a DOM element.

  1. What is xcreate-react-appx?

xcreate-react-appx is a command line tool to create one basic react application. It is officially supported by xFacebookx.

  1. What is conditional rendering?

We can use if-else or conditional operator to render a react element based on a specific condition. This is called conditional rendering.

  1. Set one example of conditional rendering.
function ShowWelcomeMsg(props) {
  const isFirstTimeLoggingIn = props.isFirstTime;
 
 if (isFirstTimeLoggingIn) {
    return xWelcomeComponent /x;
 }

 return xWelcomeBackComponent /x;
}

In this example, xWelcomeComponentx will be shown if the value of xisFirstTimeLoggingInx is true, else xWelcomeBackComponentx will be rendered.

  1. How to use inline xifx and xxxx operator?

We can use one xifx condition with xxxx operator like below :

xdivx
  {
   totalCount x 10 xx xh1x Total count is greater than 10 x/h1x
  }
x/divx

Here, if the value of xtotalCountx is greater than x10x, it will add the xh1xx/h1x line in the xdivx block.

  1. How to use inline xif-elsex and xxxx operator in React?
xdivx
  {totalCount x 10 ? (
    xh1xTotal count is greater than 10x/h1x
  ) : (
    xh1xTotal count is less than 10x/h1x
  )
x/divx

This will change the message in the xdivx block based on the value of xtotalCountx.

  1. How to prevent a component from rendering in React?

To prevent a component from rendering, we can return xnullx.

function ShowWelcomeMsg(props) {
  if (!props.isFirstTime) {
    return null;
  }
  
  return (
      xdivx Welcome to our website! x/divx
  );
}

Here, if the value of xisFirstTimex is false, it will not render the component.

  1. What are createElement and cloneElement?

React.createElement is used to create one react element which will be used as a UI component. React.cloneElement is used to clone an element.

  1. Can we create one list without using xkeyx in react?

We can create one list without xkeyx for each element but it will cause issues with the react component rendering the list. Even on the browser console, it will throw one error.

  1. What is the use of xkeyx in react list?

Keys are used to provide each list element with a stable identity. The keys should be unique. The best practice is to use xidx of the data as the key.

  1. Is it a good practice to use item index as xkeyx of list elements?

It is not a good practice to use the index of an item as the xkeyx of the list elements. For example, if the order of the items changes, it will impact negatively and may cause issues with the react component state.

  1. Is it required the keys to be unique globally in a react application?

The keys should be unique among the sibling lists. But we can use the same keys if we have two different arrays.

  1. What is Lifting state up in React?

If several states need to share common data, we can lift the state up to its closest common ancestor. That means the child components will not hold any local state, instead, the parent component will hold the common state. This same state will be used by all parent and child components.

  1. What are children prop?

Children props are used to pass components to other components as properties. This can be accessed by using {props.children}. For example :

function ShowMessage(props) {
  return xdivx{props.children}x/divx;
}

class MainComponent extends React.Component {
  render() {
    return (
      xShowMessagex
        xdivxHellox/divx

        xdivxWorldx/divx
      x/ShowMessagex
    );
  }
}

ReactDOM.render(
  xMainComponent /x,

  document.getElementById("root")
);

We are accessing the children inside xShowMessagex function.

  1. What is the dynamic import in React?

Dynamic import is used to load a component dynamically. For example :

import("./ShowMessage").then(showMessage =x {
  console.log(showMessage.show("Hello"));
});
  1. What is react Context?

React context is used to pass data through a tree of react components. Using context, we can share data globally between react components.

  1. How can we create one context object?

We can create one context object using the xReact.createContext({})x function call. The argument of this function is the default value.

  1. What are Context provider and Context consumer?

Context provider is used to provide values to a context. The provided values can be used by any other components in the application. Similarly, context consumers are used to reading the value of a context.

  1. What are error boundaries?

Error boundaries are used to catch JavaScript errors anywhere in the child components. These are used to log the error and show a fallback UI. It was introduced in React 16.

  1. What are Fragments?

Fragments are used to group a list of children components without using any extra nodes to the DOM. For example :

render() {
	return (

		xReact.Fragmentx

		xComponentA /x

		xComponentB /x

		xComponentC /x

		x/React.Fragmentx

	);

}
  1. What are empty tags xxx/x used for ?

Empty tags are used for declaring fragments in React.

  1. What are higher-Order components ?

A higher-order component is a function that takes one react component and returns one new component. We can use it for state abstraction/manipulation, props manipulation or for reusing of code.

  1. What are react portals?

Portal is used to render children into a DOM node. xcreatePortalx method is used for it.

ReactDOM.createPortal(child, container)

The second argument is a DOM element and the first argument is any renderable react child.

  1. What are the difference beween getInitialState() and constructor() ?

If we are creating one component by extending xReact.Componentx,  the constructor is used to initialize the state. Again, if we are creating one component by using the xReact.createClassx function, xgetInitialStatex is used to initialize the state.

  1. What is StrictMode?

StrictMode is used to run additional checks and warnings for react components. It runs only on development build. It doesnxt impact the production build. It highlights the problems in an application without rendering any visible UI. xxReact.StrictModex x/React.StrictModexx are used to enable strictmode for any part of an application.

  1. What is xprop-typesx library used for?

xprop-typesx library is used to do runtime type checking for props and similar objects in a react application. Using xnpmx, we can install this library.

npm install --save prop-types
  1. What are react hooks?

React hooks are introduced in React 16.8. Using hooks, we can use state and other react features without writing a class.

import React, { useState } from "react";

function Clicker() {
  const [click, setClick] = useState(0);

  return (
    xdivx
      xbutton onClick={() =x setClick(click + 1)}xClick mex/buttonx
    x/divx
  );
}

In this example, we are declaring one state variable xclickx with the initial state x0x. xuseStatex is a hook in this example.

Hope you find these questions and answers useful. Please let us know if need to know more or any question for us. Happy to answer you.

All the best !

x