Loading…

React js interview questions and Answers

By Umesh Singh
Last update: 19 Jul 2020, 44 Questions
React js interview questions

ReactJS is a JavaScript library for building reusable User interface components. It is a template-based language combined with different functions that support the HTML. Our recently updated React Interview Questions can help you crack your next interview. This means the result of any React's operation is an HTML code. You can use ReactJS to build all kinds of single-page applications.

Short Questions About React
What is the latest version of React? 16.13, released on 19th March 2020.
When was React first released? 29th May 2013
React JS is Created By Jordan Walke
License of ReactJS MIT License

This is a list of the most frequently asked react js interview questions. Please have a good read and if you want to download it, it is available in a PDF format so that you can brush up your theoretical skills on this subject.

React developer interview questions

1. Why should we not update the state directly?

One should never update the state directly because of the following reasons:

  • If you update it directly, calling the setState() afterward may just replace the update you made.
  • When you directly update the state, it does not change this.state immediately. Instead, it creates a pending state transition, and accessing it after calling this method will only return the present value.
  • You will lose control of the state across all components.

Note: Out of all the react questions, this is one that actually helps the interviewer to judge your level of understanding in this subject. Read the answer carefully to understand it properly.

2. How to call the function in render to react?

To call a function inside a render in React, use the following code:

Example

                                                    

import React, { Component, PropTypes } from 'react';

export default class PatientTable extends Component {
      constructor(props) {
        super(props);
        this.state = {
         checking:false
      };
        this.renderIcon = this.renderIcon.bind(this);
  }

  renderIcon(){
    console.log("came here")
    return(
      <div>Function called</div>
    )
  }

  render() {

   return (
       <div className="patient-container">

       {this.renderIcon}      

      </div>
   );
 }
}

3. What is Props?

Props stand for Properties in React. They are read-only components that must be kept pure. These components are passed down from the parent to the child component throughout the app. A child component cannot send the prop back to the parent component. This can help in maintaining the unidirectional data flow and is used to render the dynamically generated data.

4. What is JSX?

JSX stands for JavaScript XML. It is a file type used by React that utilizes the expressiveness of JavaScript along with HTML. This makes the HTML file easy to understand. This file makes applications robust and boosts their performance.

Example

                                                    

render(){
      return(
          <div>  <h1> Welcome To Best Interview Question!!</h1> </div>
     );
 }

5. What are controlled and uncontrolled components?

A Controlled Component is one that takes the current value through the props and notifies of any changes through callbacks such as onChange.

Example:

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

An uncontrolled component is one storing its own state internally, and you can query the DOM via a ref to find its current value as and when needed. Uncontrolled components are a bit closer to traditional HTML.

Example:

<input type="text" defaultValue="foo" ref={inputRef} />

Note: React is a widely used open-source library used for building interactive user interfaces. It is a web platform licensed under MIT. This is one of the very popular react interview questions.

6. What is function based component in React?

Basically Function Based Component are the component which are made by JavaScript Functions.It takes props as argument and return JSX.

Example

                                                    

Import React from ‘react’;
const XYZ = (props ) => {
     <div>
          <h1>React Interview Questions</h1>
     </div>
}
export default XYZ;

7. What is the difference between Element and Component?
React Component React Element
It is a simple function or class used for accepting input and returning a React element It is a simple object used for describing a DOM node and the attributes or properties as per your choice.
The React Component has to keep the references to its DOM nodes and also to the instances of the child components. The React Element is an immutable description object, and in this, you cannot apply any methods.
8. What are refs used for in React?

Refs are a function in React having the following uses:

  • Accessing DOM and React elements that you have created.
  • Changing the value of a child component without using props and others.
9. How React is different from Angular?
ReactJS AngularJS
This is an open-source JS library used for building user interfaces and uses a controller view pattern. This is a JS-based open-source front end web framework and uses an MVC based pattern.
It is developed and maintained by Facebook Developers. It is developed and maintained by Google Developers.
Based on the JSX programming language. Based on Javascript and HTML language.
It is straightforward to learn. Comparatively, it is difficult to learn.
It supports server-side rendering. It supports client-side rendering.
It has a uni-directional data binding methodology. It has a bi-directional data binding methodology.
It is based on a Virtual DOM. It is based on a regular DOM.

Note: Before getting confused with the plethora of React coding interview questions, you need to ensure the basics. This question will help you to understand the basics of reactjs and make you even more confident enough to jump onto the advanced questions.

10. What is the difference between componentWillMount and componentDidMount?
componentWillMount() componentDidMount()
This is called only once during the component lifecycle immediately before the component is rendered to the server. It is used to assess props and do any extra logic based upon them. It is called only on the client end, meaning, it is usually performed after the initial render when a client has received data from the server.
Used to perform state changes before the initial render. It allows you to perform all kinds of advanced interactions including state changes.
No way to “pause” rendering while waiting for the data to arrive. It can be used to set up long-running processes within a component.
It is invoked just immediately after the mounting has occurred. Putting the data loading code in this just ensures that data is fetched from the client's end.
Users should avoid using any async initialization in order to minimize any side-effects or subscriptions in this method. Here, the data does not load until the initial render is done. Hence, users must set an initial state properly to eradicate undefined state errors.
11. What is the difference between Function Based Component and Class Based Component?

The Main Difference is of Syntax. The function-Based component used props as an argument and is also called stateless component and In class-based component, we extend all the property of predefined function and used according to our need.

Class Based Component use state and the state is used as props in child component.In Class Based component we can use different lifecycle method of component.

12. What are arrow functions? How are they used?

Arrow functions, also called ‘fat arrow‘ (=>), are brief syntax for writing the expression. These functions bind the context of the components because auto binding is not available by default in ES6. Arrow functions are useful if you are working with the higher-order functions.

Example

                                                    

//General way
render() {
  return(
    <MyInput onChange={this.handleChange.bind(this) } />
  );
}

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

13. What is the purpose of render() in React?

It is compulsory for each React component to have a render(). If more than one element needs to be rendered, they must be grouped inside one tag such as <form>, <group>,<div>. This function goes back to the single react element which is the presentation of native DOM Component. This function must return the same result every time it is invoked.

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

States are at the heart of components. They are the source of data and must be kept simple. States determine components’ rendering and behavior. They are mutable and create dynamic and interactive components, and can be accessed via this.state().

Note: From the vast number of react developer interview questions, answering this will help you to align yourself as an expert in the subject. This is a very tricky question that often makes developers nervous.

15. What is the component lifecycle in ReactJS?

Component lifecycle is an important part of ReactJS. Component lifecycle falls into three categories - property updates, Initialization and Destruction. Lifecycle is a method of managing the state and properties of the components.

16. What is an event?

Events are the triggered reactions to actions like mouse hover, click, key press, etc.

17. What is Redux?

Redux is used to handle data in a reliable manner. It performs task accurately and ensures that the data has been controlled. You can also apply filters if only a specific part of data is required.

18. What is Flux?

Flux is an illustration that helps to maintain a unidirectional data stream. It also controls construed data unique fragments and makes them interface without creating issues. The configuration of Flux is insipid and is not specific to applications.

19. What is meant by pooling?

The server needs to be regularly monitored for updates. The aim is to check for the presence of new comments. This process is considered as pooling. It checks for the updates almost every 5 seconds. Pooling helps keep an eye on the users and ensure there is no negative information on servers.

20. In what cases would you use a Class Component over a Functional Component?

If your component has a state or lifecycle method, use Class component. Else, a Functional component.

21. What can you do if the expression contains more than one line?

Enclosing the multi-line JSX expression is the best option. Sometimes it becomes necessary to avoid multi-lines in order to perform the task reliably and for getting the expected results.

22. Is it possible to use the word Class in JSX?

No. This is because the word Class is an occupied word in JavaScript. If you use the word Class JSX will get translated to JavaScript.

Note: Before getting confused with the plethora of react coding interview questions, you need to ensure the basics. This question will help you to understand the core basics of react and make you even more confident enough to jump onto the advanced questions.

23. Is it possible to display props on a parent component?

Yes. This is a complex process, and the best way to do it is by using a spread operator.

24. What is React?

React is a JavaScript Library which is used to show content to user and handle user interaction.

25. What is Component?

Component is a building block of any React app which is made by either JavaScript Function of Class. Ex. Header Component, Footer Component etc.

There are two types of Components.
  • Function Based Component
  • Class Based Component
26. What are Class Based Component?

Class Based Component is the JavaScript Class. In these Components we extends the JavaScript predefined class into our component.

Example

                                                    

Import React,{Component} from ‘react’;

class ABC extends Component {

 render(){

   return(

    <div>

       <h1>Hello World</h1>

</div>

);

}}

export default ABC;

27. How to create a component in react js?

There are 3 ways to create a component in React:

  • Using a depreciated variable function
  • Using a Class
  • Using a Stateless Functional Component
1. Using a depreciated variable function

In this, you need to declare a variable in your Javascript file/tag and use the React.createClass() function to create a component using this code.

var MyComponent = React.createClass({
   render() {
      return <div>
      <h1>Hello World!</h1>
      <p>This is my first React Component.</p>
      </div>
   }
})

Now, use the div element to create a unique ID for the specific page and then link the above script onto the HTML page.

<div id=”react-component”></div>

Use ReactDOM.render() function to take 2 arguments, the react component variable and the targeted HTML page.

ReactDOM.render(<MyComponent />, document.getElementById('react-component'))

Finally, save the HTML page to display the result like this one below:

2. Using a Class

Javascript has lately started supporting classes. Any React developer can easily create a class using the class extends (Inherits). Following is the code

3. Using a Stateless Functional Component

It might sound a bit complex, but this basically means that a normal function will be used in place of a variable to return a react component.

Create a const called MyComp and set it as equal to a () function. Use the arrow function, => to declare the logic of the function as follows:

const MyComponent = () => {
   return <div>
   <h1>Hello!</h1>
   <p>This is my first React Component.</p>
   </div>
}

29. How to reload the current page in react js?

Reloading/Refreshing a page using Javascript:
Use Vanilla JS to call the reload method for the specific page using the following code:

window.location.reload(false);

30. How to redirect to another page in react js?

The best way to redirect a page in React.js depends on what is your use case. Let us get a bit in detail:

If you want to protect your route from unauthorized access, use the component and try this:

Example

                                                    

import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
   if (authFails)
   return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}

31. How do you reference a DOM element in react?

In React, an object this.refs which is found as an instance inside the component can be used to access DOM elements in Reactjs.

Note: One of the most tricky react advanced interview questions, you need to answer this question with utmost clarity. Maybe explaining it with a short example or even a dry run would help you get that dream job.

32. What are React Hooks?

React Hooks were brought in by the React team to efficiently handle state management and the side-effects in function components. React Hooks is a way of making the coding effortless. They help by enabling us to write React applications by only using React components.

33. How to call one component from another component in reactjs?

To render a component with another component in Reactjs, let us take an example:

Let us suppose there are 2 components as follows:

Example

                                                    

Component 1

class Header extends React.Component{

    constructor(){
        super();
    }

    checkClick(e, notyId){
       alert(notyId);
    }
}

export default Header;

Component 2

class PopupOver extends React.Component{

    constructor(){
        super();        
    }

    render(){
        return (
            <div className="displayinline col-md-12 ">
                Hello
            </div>
        );
    }
}

export default PopupOver;


Now to call the Component 1 in Component 2, use this code:

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

34. What is React Router?

React Router is the in-built routing library for React. React Router helps to keep your UI in sync with the respective URL. It works on a simple API having powerful features like lazy loading, locational transition, and dynamic route matching built right in.

35. How to render an array of objects in react?

Now, there are two ways to render this object as an array,

First:

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

    return (
      <div>
      {listItems }
      </div>
    );
  }

Or, you could directly write the map function in the return

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    return (
      <div>
      {data.map(function(d, idx){
         return (<li key={idx}>{d.name}</li>)
       })}
      </div>
    );
  }

36. What is the difference between state and props in React?
State Props
This is the data maintained inside the component. This is the data passed in from a parent component.
The component within shall update itself using the setState function. These are read-only functions present in the child component and have to be updated manually.

Note: React is a widely used open-source library used for building interactive user interfaces. It is a web platform licensed under MIT. This is one of the very popular react interview questions.

43. What are the key benefits of ReactJS development?
Key Benefits of ReactJS Development
  • Allows Developers to Reuse the Components
  • It is Much Easier to Learn
  • The Benefit of Having JavaScript Library
  • SEO Friendly
  • It ensures faster rendering
  • The Increase in Community Base
  • The Support of Handy Tools
  • Scope for Testing the Codes etc
44. What are synthetic events?

It is a cross-browser wrapper that is around the native event of the same browser. This is the most important question in react interview questions.

Conclusion

Now that you have read all the react questions, it is time for you to go towards the next level. Applying for a developer position would require you to actually code and not just give answers to theoretical questions.

That’s why you should enhance your skills by complementing the above react developer interview questions with a practical mindset. Start coding small stuff, get your concepts crystal clear. It’s all about how you can apply your knowledge in different projects. Code and code, that’s the secret to winning the dream job!