ReactJS Interview Questions and Answers

Embark on a journey into the world of ReactJS with 'ReactJS Interview Questions and Answers.' This blog is your essential resource for preparing for ReactJS-related interviews, featuring a comprehensive collection of questions and detailed answers. Whether you're a front-end developer, a UI/UX designer, or a ReactJS enthusiast, our guide covers ReactJS fundamentals, component-based architecture, state management, and best practices. Prepare with confidence and explore the power of ReactJS in building dynamic and responsive web applications.

1. What is ReactJS?

ReactJS is a JavaScript library for building user interfaces, particularly for single-page applications where UI updates are frequent and dynamic.

2. Explain the concept of Virtual DOM in React.

The Virtual DOM is a lightweight copy of the actual DOM in memory. React uses it to improve performance by minimizing direct manipulation of the actual DOM.

3. What is React?

React is a front-end and open-source JavaScript library which is useful in developing user interfaces specifically for applications with a single page. It is helpful in building complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.

The important features of React are:

4. What are the advantages of using React?

MVC is generally abbreviated as Model View Controller.

5. What are the limitations of React?

The few limitations of React are as given below:

6. What is useState() in React?

The useState() is a built-in React Hook that allows you for having state variables in functional components. It should be used when the DOM has something that is dynamically manipulating/controlling.

In the below-given example code, The useState(0) will return a tuple where the count is the first parameter that represents the counter’s current state and the second parameter setCounter method will allow us to update the state of the counter.

...const [count, setCounter] = useState(0);const [otherStuffs, setOtherStuffs] = useState(...);...const setCount = () => {   setCounter(count + 1);   setOtherStuffs(...);   ...};

We can make use of setCounter() method for updating the state of count anywhere. In this example, we are using setCounter() inside the setCount function where various other things can also be done. The idea with the usage of hooks is that we will be able to keep our code more functional and avoid class-based components if they are not required.

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

8. 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 a 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 components differ.

On the following basis let’s compare functional and class components:

Functional 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>      )    }   }

Let’s render the following component with props and analyse how functional and class components handle props:

<Student Info name="Vivek" rollNumber="23" />

In functional components, the handling of props is pretty straightforward. 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.

Functional components use React hooks to handle state. It uses the useState hook to set the 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 class room: {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. 

9. What are the differences between controlled and uncontrolled components?

Controlled and uncontrolled components are just different approaches to handling input from 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 ✔️ 🤔

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

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. 

10. What are props in React?

The props in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.

The main purpose of props is to provide different component functionalities such as:

For example, consider we are creating an element with reactProp property as given below: <Element reactProp = "1" />
This reactProp name will be considered as a property attached to the native props object of React which already exists on each component created with the help of React library: props.reactProp;.

11. Explain React state and props.

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

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.

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 an 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);}

Note- Props are read-only. They cannot be manipulated or changed inside a component.

12. Explain about types of side effects in React component.

There are two types of side effects in React component. They are:

13. What are error boundaries?

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

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?

  1. Render phase
  2. Inside a lifecycle method
  3. 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 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 the 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 the error boundary, we can render the CounterComponent in the following way:

<ErrorBoundary> <CounterComponent/></ErrorBoundary>

14. What is React Hooks?

React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.

Using Hook, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now using the useState hook, we can keep the state in a functional component.

15. 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, the useState hook lets us define a 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 namelet [name, setName] = useState(\'\');}

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

16. What are the rules that must be followed while using React Hooks?

There are 2 rules which must be followed while you code with Hooks:

17. What is the use of useEffect React Hooks?

The useEffect React Hook is used for performing the side effects in functional components. With the help of useEffect, you will inform React that your component requires something to be done after rendering the component or after a state change. The function you have passed(can be referred to as “effect”) will be remembered by React and call afterwards the performance of DOM updates is over. Using this, we can perform various calculations such as data fetching, setting up document title, manipulating DOM directly, etc, that don’t target the output value. The useEffect hook will run by default after the first render and also after each update of the component. React will guarantee that the DOM will be updated by the time when the effect has run by it.

The useEffect React Hook will accept 2 arguments: useEffect(callback,[dependencies]);

Where the first argument callback represents the function having the logic of side-effect and it will be immediately executed after changes were being pushed to DOM. The second argument dependencies represent an optional array of dependencies. The useEffect() will execute the callback only if there is a change in dependencies in between renderings.

Example:

import { useEffect } from \'react\';function WelcomeGreetings({ name }) { const msg = `Hi, ${name}!`;     // Calculates output useEffect(() => {   document.title = `Welcome to you ${name}`;    // Side-effect! }, [name]); return <div>{msg}</div>;         // Calculates output}

The above code will update the document title which is considered to be a side-effect as it will not calculate the component output directly. That is why updating of document title has been placed in a callback and provided to useEffect().

Consider you don’t want to execute document title update each time on rendering of WelcomeGreetings component and you want it to be executed only when the name prop changes then you need to supply name as a dependency to useEffect(callback, [name]).

18. Why do React Hooks make use of refs?

Earlier, refs were only limited to class components but now it can also be accessible in function components through the useRef Hook in React.

The refs are used for:

19. What are Custom Hooks?

A Custom Hook is a function in Javascript whose name begins with ‘use’ and which calls other hooks. It is a part of React v16.8 hook update and permits you for reusing the stateful logic without any need for component hierarchy restructuring.

In almost all of the cases, custom hooks are considered to be sufficient for replacing render props and HoCs (Higher-Order components) and reducing the amount of nesting required. Custom Hooks will allow you for avoiding multiple layers of abstraction or wrapper hell that might come along with Render Props and HoCs.

The disadvantage of Custom Hooks is it cannot be used inside of the classes.

20. Explain Strict Mode in React.

StrictMode is a tool added in 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:

21. How to prevent re-renders in React?

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>  );}}

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

22. 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 :

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>   ); }}
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>   ); }}
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>   ); }}
.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>   ); }}

23. 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:

24. What are the lifecycle methods of React?

React lifecycle hooks will have the methods that will be automatically called at different phases in the component lifecycle and thus it provides good control over what happens at the invoked point. It provides the power to effectively control and manipulate what goes on throughout the component lifecycle.

For example, if you are developing the YouTube application, then the application will make use of a network for buffering the videos and it consumes the power of the battery (assume only these two). After playing the video if the user switches to any other application, then you should make sure that the resources like network and battery are being used most efficiently. You can stop or pause the video buffering which in turn stops the battery and network usage when the user switches to another application after video play.

So we can say that the developer will be able to produce a quality application with the help of lifecycle methods and it also helps developers to make sure to plan what and how to do it at different points of birth, growth, or death of user interfaces.

The various lifecycle methods are:

25. Does React Hook work with static typing?

Static typing refers to the process of code check during the time of compilation for ensuring all variables will be statically typed. React Hooks are functions that are designed to make sure about all attributes must be statically typed. For enforcing stricter static typing within our code, we can make use of the React API with custom Hooks.

26. Differentiate React Hooks vs Classes.

React Hooks Classes
It is used in functional components of React. It is used in class-based components of React.
It will not require a declaration of any kind of constructor. It is necessary to declare the constructor inside the class component.
It does not require the use of this keyword in state declaration or modification. Keyword this will be used in state declaration (this.state) and in modification (this.setState()).
It is easier to use because of the useState functionality. No specific function is available for helping us to access the state and its corresponding setState variable.
React Hooks can be helpful in implementing Redux and context API. Because of the long setup of state declarations, class states are generally not preferred.

27. How does the performance of using Hooks will differ in comparison with the classes?

28. Do Hooks cover all the functionalities provided by the classes?

Our goal is for Hooks to cover all the functionalities for classes at its earliest. There are no Hook equivalents for the following methods that are not introduced in Hooks yet:

Since it is an early time for Hooks, few third-party libraries may not be compatible with Hooks at present, but they will be added soon.

29. What is React Router?

React Router refers to the standard library used for routing in React. It permits us for building a single-page web application in React with navigation without even refreshing the page when the user navigates. It also allows to change the browser URL and will keep the user interface in sync with the URL. React Router will make use of the component structure for calling the components, using which appropriate information can be shown. Since React is a component-based framework, it’s not necessary to include and use this package. Any other compatible routing library would also work with React.

The major components of React Router are given below:

30. Can React Hook replaces Redux?

The React Hook cannot be considered as a replacement for Redux (It is an open-source, JavaScript library useful in managing the application state) when it comes to the management of the global application state tree in large complex applications, even though the React will provide a useReducer hook that manages state transitions similar to Redux. Redux is very useful at a lower level of component hierarchy to handle the pieces of a state which are dependent on each other, instead of a declaration of multiple useState hooks.

In commercial web applications which is larger, the complexity will be high, so using only React Hook may not be sufficient. Few developers will try to tackle the challenge with the help of React Hooks and others will combine React Hooks with the Redux.

31. Explain conditional rendering in React.

Conditional rendering refers to the dynamic output of user interface markups based on a condition state. It works in the same way as JavaScript conditions. Using conditional rendering, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on.

There are different approaches for implementing conditional rendering in React. Some of them are:

32. How to create a switching component for displaying different pages?

A switching component refers to a component that will render one of the multiple components. We should use an object for mapping prop values to components.

A below-given example will show you how to display different pages based on page prop using switching component:

import HomePage from \'./HomePage\'import AboutPage from \'./AboutPage\'import FacilitiesPage from \'./FacilitiesPage\'import ContactPage from \'./ContactPage\'import HelpPage from \'./HelpPage\'const PAGES = { home: HomePage, about: AboutPage, facilitiess: FacilitiesPage, contact: ContactPage help: HelpPage}const Page = (props) => { const Handler = PAGES[props.page] || HelpPage return <Handler {...props} />}// The PAGES object keys can be used in the prop types for catching errors during dev-time.Page.propTypes = { page: PropTypes.oneOf(Object.keys(PAGES)).isRequired}

33. How to re-render the view when the browser is resized?

It is possible to listen to the resize event in componentDidMount() and then update the width and height dimensions. It requires the removal of the event listener in the componentWillUnmount() method.

Using the below-given code, we can render the view when the browser is resized.

class WindowSizeDimensions extends React.Component { constructor(props){   super(props);   this.updateDimension = this.updateDimension.bind(this); }   componentWillMount() {   this.updateDimension() } componentDidMount() {   window.addEventListener(\'resize\', this.updateDimension) } componentWillUnmount() {   window.removeEventListener(\'resize\', this.updateDimension) } updateDimension() {   this.setState({width: window.innerWidth, height: window.innerHeight}) } render() {   return <span>{this.state.width} x {this.state.height}</span> }}