image
author

William Dawson

Full Stack Developer

If you’re an aspiring Front-End developer and you’re preparing for interviews, this blog is for you. This blog on Top 50 Questions for React Interview is the ideal guide for you to know all the ideas you need to clear an interview with React. But let’s take a quick look at the demand and status of React on the market before beginning with the React Interview Questions.

The JavaScript instruments are firming their origins in the marketplace slowly as well as steadily, as well as there is an exponential increase in demand for React certification. It is becoming increasingly difficult to select the correct technology to develop an application or website. React is regarded as the fastest increasing framework for Javascript, among other things.

Unique characteristics such as Virtual DOM and reusable parts capture front end developer’s attention. Despite being just a ‘View’ library in MVC (Model-View-Controller), full-blown frameworks such as Angular, Meteor, Vue, etc. are strongly competitive. Check the below graph showing the common JS frameworks trend:

react interview questions
React Interview Questions

So, here are the top 50 interview questions and answers that the interviewer will most probably ask.

General React – React Interview Questions

1. Differentiate from Real DOM to Virtual DOM.

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

2. What is React?

  • React is a Facebook-developed front-end JavaScript library in 2011.
  • It follows the component-based approach that helps build UI components that can be reused.
  • It is used for complicated, interactive web and mobile user interface development.
  • Although it was only open-sourced in 2015, it is supported by one of the biggest groups.

3. What are the characteristics of React?

  • Lightweight DOM For Better Performance
  • In React, everything is treated as components.
  • React uses JSX (JavaScript eXtension) that allows us to write JavaScript that looks like HTML
  • React operates not directly on the browser’s Document Object Model (DOM) immediately, but on a virtual DOM
  • ReactJS follows unidirectional data flow or one-way data binding.

4. List some of the React’s significant benefits.

Some of the major advantages of React are:

  1. It increases the application’s performance
  2. It can be conveniently used on the client as well as server side
  3. Because of JSX, code’s readability increases
  4. Using React, writing UI test cases become extremely easy

5. What are the limitations of React?

Limitations of React are listed below:

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

6. What is JSX?

JSX is a shorthand for JavaScript XML. This is a file type used by React that uses JavaScript’s expressiveness along with HTML as a template syntax. This makes it very simple to comprehend the HTML file. This file allows robust apps and increases their efficiency. Below is a JSX instance:

render(){
    return(        
           <div>
                <h1> Hello World from Codersera!!</h1>
           </div>
          );
        }

7. What do you understand by virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object that was originally only the real DOM copy. It is a node tree that lists the components as objects and their characteristics, their characteristics and content. The rendering feature of React generates a node tree from the parts of React. It then updates this tree in reaction to the information model mutations that are caused by different user or system behavior.

This Virtual DOM works in three simple steps.

  1. The entire UI is re-rendered in Virtual DOM representation whenever any underlying information changes.
  2. Then the distinction is calculated between the prior DOM depiction and the fresh one.
  3. Once the calculations are done, only the things that have actually changed will update the real DOM.

8. Why can’t browsers read JSX?

React uses JSX (JavaScript eXtension) that allows us to write JavaScript that looks like HTML.But given JSX is not valid JavaScript, web browsers can’t read it directly. So, if JavaScript files contain JSX, that file will have to be transpired. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

9. How different is React’s ES6 Syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in 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>
  }

10. How is React different from Angular?

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

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

Building blocks of the UI of a React application are components. These parts divide the entire UI into tiny parts that are autonomous and reusable. Then it becomes independent of each of these parts without affecting the remainder of the UI.

12. Explain the purpose of render() in React.

It is seen as a normal function but render() function has to return something whether it is null. When the component file is called it calls the render() method by default because that component needs to display the HTML markup or we can say JSX syntax . Each React component must have a render() function ,It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div>, etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

import React, { Component } from 'react';

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

export default App;

13. What are hooks?

Hooks is a new feature that lets you use 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>)
}

14. What is Props?

  • Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed.
  • Props are immutable. Because these are developed in the concept of pure functions. In pure functions, we cannot change the data of parameters. So, also cannot change the data of a prop in ReactJS.

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

The state is used so that a component can keep track of information in between any renders that it does
The state is used for mutable data or data that will change. This is particularly useful for user input. Think search bars for example. The user will type in data and this will update what they see.

16. Differentiate between states and props.

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

17. 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')
);

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

The fat arrow => is used to define anonymous functions.It is often the easiest way to pass parameters to callback functions. But you need to optimize the performance while using it. Note: Using an arrow function in render method creates a new function each 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) } />
    );
}

19. Differentiate between stateful and stateless components.

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

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

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

  • Initialization

The initialization phase is where we define defaults and initial values for this.props and this.state.

  • Mounting

Mounting is the process that occurs when a component is being inserted into the DOM

  • Updating

This is  the phase when the updating of the component occurs whenever the state  is changed  or component receives a new  prop

  • Unmounting

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

21. Explain the React component lifecycle techniques in detail.

Some of the most important lifecycle methods are:

  • componentWillMount() – It’s invoked once and immediately before the initial rendering occurs, hence before React inserts the component into the DOM. It’s very important to note that calling this.setState() within this method will not trigger a re-render.
  • componentDidMount()- this method is triggered after the render function Now the updated DOM is available for access, which means that this method is the best place for initializing other Javascript libraries that need access to the DOM and for data fetching operations.
  • componentWillReceiveProps()-componentWillReceiveProps(), invoked when a component is receiving new props. We can use this method as an opportunity to react to a prop transition before the render() method is called. Calling this.setState() within this function will not trigger an additional re-render, and we can access the old props via this.props
  • shouldComponentUpdate() -This method allows us to decide whether the next component’s state should trigger a re-render or not. This method returns a boolean value, which by default is true. But we can return false and the next methods won’t be called:
  • componentWillUpdate()-This method is called immediately before rendering(updation), when new props or state are being received. We can use this as an opportunity to perform preparation before an update occurs, however, is not allowed to use this.setState().
  • componentDidUpdate()-This method is called immediately after React updates the DOM. We can use this method to interact with the updated DOM or perform any action post-render
  • componentWillUnmount() -This method is called immediately before the component is unmounted from the DOM. We can use it to perform any cleanup we might need,

22. What is an Event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, keypress, etc. Handling these events are similar to handling events on DOM elements. But there are some syntactical differences like:

  • Events are named using camel case instead of just using the lowercase.
  • Events are passed as functions instead of strings.

The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

23. How do you create an event in React?

class Display extends React.Component({    
    show(evt) {
        // code   
    },   
    render() {      
        // Render the div with an onClick prop (value is a function)        
        return (            
                <div onClick={this.show}>Click Me!</div>
         );    
    }
});

24. What are synthetic events in React?

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

25. What do you understand by refs in React?

Refs are References in React’s shorthand. It is an attribute that helps to store a reference to a specific element or component that is returned by the configuration function of the rendering components. It is used to return references to a specific render returned element or component. When we need DOM measurements or add techniques 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>
     );
   }
 }

26. List some of the cases where you should use Refs?

Following are the cases when refs should be used:

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

27. How do you modulate React code?

By using the characteristics of export and import, we can modularize software. They assist to write the parts in separate documents independently.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(  <div>
                       <h1>This is a child component</h1>
                 </div>)
    }
}
 
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {    
    render() {        
        return(           
             <div>               
                <App />          
            </div>
        );  
    }
}

28. How are forms created in React?

React offers a stateful, reactive approach to building forms. Unlike other DOM elements, HTML form elements work differently in React. The form data, for instance, is usually handled by the component rather than the DOM, and is usually implemented using controlled components.

The difference is can use a callback function to handle form events and then using the container’s state to store the form data. This gives your component better control over the form control elements and the form data.

The callback function is triggered on events, including change of form control values, or on form submission.

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}
 
render() {
    return (        
         
 
 
<form onSubmit={this.handleSubmit}>
            <label>
                Name:
                <input type="text" value={this.state.value} onChange={this.handleSubmit} />
            </label>
            <input type="submit" value="Submit" />
        </form>
 
 
 
    );
}

29. What do you know about controlled and uncontrolled components?

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

30. What do you mean by Higher Order Components (HOC)?

A higher-order component in React is a pattern used to share common functionality between components without repeating code.

A higher-order component is actually not a component though, it is a function that takes a component and returns a new component. It transforms a component into another component and adds additional data or functionality

31. What can be done with HOC?

HOC can be used for many tasks like:

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

32. What are pure components?

Instead of writing shouldComponent method in our components, React introduced a new Component with built-in shouldComponentUpdate implementation it is the React.PureComponent component.

React.PureComponent implements it with a shallow prop and state comparison.you can use React.PureComponent for a performance boost in some cases

33. What is the significance of keys in React?

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Keys Must Only Be Unique Among Siblings.

React keys are useful when working with dynamically created components or when your lists are altered by the users. Setting the key value will keep your components uniquely identified after the change.

34. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:

  • MVC doesn’t solve the Code complexity problem. It doesn’t solve the code reuse or no-flexibility problem either.
  • It doesn’t guarantee decoupled code.

35. What do you understand by Flux?

Flux is an architecture that Facebook uses internally when working with React. It is not a framework or a library. It is simply a new kind of architecture that complements React and the concept of Unidirectional Data Flow.

Flux is probably better explained by explaining its individual components:

  • Actions – Helper methods that facilitate passing data to the Dispatcher
  • Dispatcher – Receives actions and broadcasts payloads to registered callbacks
  • Stores – Containers for application state & logic that have callbacks registered to the dispatcher
  • Controller Views – React Components that grab the state from Stores and pass it down via props to child components.

36. What is Redux?

Redux is a state management tool. While it’s mostly used with React, it can be used with any other JavaScript framework or library.

Redux allows you to manage your entire application state in one object, called the Store.

Updates to the Store will trigger re-renders of components that are connected to the part of the store that was updated. When we want to update something, we call an Action. We also create functions to handle these actions and return the updated Store. These functions are called Reducers.

37. What are the three principles that Redux follows?

Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. 

Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.

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

single source of truth (SSOT) is the practice of structuring information models and associated data schema such that every data element is mastered (or edited) in only one place

Redux uses ‘ Store ‘ to store the entire state of the application at one location. So all the state of the component is stored in the store and the store itself receives updates. The single state tree makes tracking modifications simpler over time and debugging or inspecting the request.

39. List down the components of Redux.

Redux is composed of the following components:

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

40. Show how the data flows through Redux?

41. How are Actions defined in Redux?

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

function addTodo(text) {
       return {
                type: ADD_TODO,    
                 text    
    }
}

42. Explain the role of Reducer.

Reducers are simple features that indicate how the state of the application changes in an ACTION reaction. Reduces job by taking the preceding state and action, and then returns a fresh state. It determines what kind of update is required based on the action type, and then returns new values. If there is no work to be accomplished, it returns the prior state as it is.

43. What is the significance of store in Redux?

A store is a JavaScript object that can hold the state of the application and provide some help methods for accessing the state, dispatching actions, and recording listeners. An application’s entire state / object tree is stored in a single shop. Redux is very easy and predictable as a consequence. We can transfer middleware to the shop to manage data processing and to maintain a log of different activities that alter the storage status. Through reducers, all activities return a fresh state.

44. How is Redux different from Flux?

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

45. What are the advantages of Redux?

Advantages of Redux are listed below:

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

46. What is React Router?

React Router is a powerful routing library built on top of React .This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API . React Router offers a way to write your code so that it will show certain components of your app only if the route matches what you define.

47. Why is switch keyword used in React Router v4?

Within the Switch component, Route and Redirect components are nested inside. Starting from the top Route/Redirect component in the Switch, to bottom Route/Redirect, each component is evaluated to be true or false based on whether or not the current URL in the browser matches the path/from prop on the Route/Redirect component.

Switch is that it will only render the first matched <Route/> child. This is really handy when we have nested routes such as the below:

<Switch>
  <Route path="/accounts/new" component={AddForm} />
  <Route path={`/accounts/:accountId`} component={Profile} />
</Switch>


48. Why do we need a Router in React?

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

The <Route/> component imported from the React Router package takes in two props, the path to direct the user to the specified path and the component to define the content in the said path

<switch>
    <route exact path=’/’ component={Home}/>
    <route path=’/posts/:id’ component={Newpost}/>
    <route path=’/posts’   component={Post}/>
</switch>

49. List down the advantages of React Router.

Few advantages are:

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

50. How is React Router different from conventional routing?

TopicConventional RoutingReact Routing
PAGES INVOLVEDEach view corresponds to a new fileOnly single HTML page is involved
URL CHANGESA HTTP request is sent to a server and corresponding HTML page is receivedOnly the History attribute is changed
FEELUser actually navigates across different pages for each viewUser is duped thinking he is navigating across different pages

Apply as a coder

How useful was this post?

How useful was this post?

Click on a star to rate it!

Average rating 3.4 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

Please do Rate Us and Share!

Related Blogs

  • author
    Kela Casey

    Top Javascript Game Engines and Libraries

    Gaming is something everyone enjoys, be it a 10-year-old kid or an employed person. There’s no better recreation at home than to plug in your headphones or speakers and get lost in the world of video games. After all, what’s better than fighting criminals or driving supercars at very high speed, or play a...

  • author
    Lucas White

    Best Javascript Animation Libraries for 2021

    Animations are something which fascinate everyone, be it in any movie, video, or even games. When you think about making a website, the first thing you wonder is how to make your website stand out from its competitors. While there are many ways to make it stand out like giving out unique content, creating...

  • author
    Adam Davidson

    How to Prepare Your App now according to all new Rails 6.1?

    Rails 6.1 has finally been launched. There seems to be a range of memory optimizations for your Rails apps that should boost their efficiency and speed. A variety of new features are going to be introduced soon too. Although 3rd-party libraries are now providing means to manage several databases, horizontal sharding and making switches...

image

About The Author

William is a CTO and a full-stack engineer with 10 years of experience. He has spent the past seven years doing web and mobile apps. He’s good at designing architecture and implementing agile development process. The technologies he’s worked with include: Node.js, Elixir, Rails, AngularJS, React, React Native, Objective-C, iOS, Java, Android. He’s also familiar with C++, Haskell, C#/.NET. He is an enthusiastic programmer and a great guy to know

Recents

Michael J. Ryan says:

#1 portions are dated and overly simplified, the browser DOM has seen a lot of significant improvements, and so has React…

#5-4 JSX is *not* complex at all imho… some developers don’t like it, and there’s a heavy overlap with developers who don’t like JavaScript in general, or like tech in different files or prefer general templating DSL.

#9 part is demonstrating CommonJS vs ESM … the other is React’s legacy interface VS class based inheritance, which is supported natively in all modern browsers (though JSX isn’t without transformation).

#10-2 React supports both SSR and client

#12 ignores functional components

#13 doesn’t explain functional components

#16.1 is wrong, state isn’t received from the parent (not to be confused with state initialized from prop, or context)

#16.5 likewise with 16.1

#16.6 both no, you can send a function/event handler for child to bubble out, or use context.

#18 fat-arrow is a JavaScript thing as of ES6, not specific to react. It is a context bound lambda expression.

#21 neglects functional component hooks.

#23 unbound function

#25 example is just plain *WRONG*

#27 demo is wrong

#28 demo is wrong

… not reading beyond #28 …

Try our One-Week Risk Free Trial for Hiring a Coder

Know more Hire a Coder

Hire Top 1% Remote Developers, Free For The First Week

Connect with quality remote developers and code your ideas away.

X