Introduction
It's becoming more difficult to choose the right technology for developing an app or a website. React is the fastest-growing Javascript framework among them all. Slowly but steadily, JavaScript tools are establishing themselves in the market, and demand for React certification is skyrocketing. And thus, you need to be prepared with React.js Interview Questions. But why React.js interview questions? React is a clear winner for front-end developers all over the world, thanks to its quick learning curve, reusable components, and clean abstraction. This blog on React Interview Questions is for you if you are an aspiring front-end developer who is preparing for interviews. So let us dive in and prepare ourselves for React.js interview questions!
Must Recommended Topic, Pandas Interview Questions, Hooks in React JS and Operating System Interview Questions
The React.js Interview Questions
1.What is React?
- Facebook created the React front-end JavaScript library in 2011.
- It uses a component-based approach to create reusable user interface components.
- It's used to create complex and interactive web and mobile user interfaces.
-
Despite the fact that it was only open-sourced in 2015, it has one of the largest communities behind it.
2. What are the features of React?
- Instead of using the real DOM, it employs the virtual DOM.
- Server-side rendering is used.
-
It adheres to unidirectional data flow, also known as data binding.
3. What are the major advantages of React?
- It improves the performance of the application.
- It can be used on both the client and server sides with ease.
- The readability of code improves thanks to JSX.
- Other frameworks, such as Meteor, Angular, and others, are simple to integrate with React.
-
Writing UI test cases becomes a breeze with React.
4. What are the limitations of React?
- React is a library rather than a full-fledged framework.
- It has a large library that takes some time to comprehend.
- It may be difficult to comprehend for inexperienced programmers.
-
Because it uses inline templating and JSX, the coding becomes more complicated.
5. Differentiate between Real DOM and Virtual DOM.
Real DOM |
Virtual DOM |
Slow Updates | Fast Updates |
Can update HTML directly | Cannot update HTML directly |
New DOM is created when an element updates | JSX is updated when an element is updated |
Expensive DOM manipulation | Easy DOM manipulation |
There is memory wastage | No memory wastage |
6. What is JSX?
JavaScript XML is abbreviated as JSX. This is a React-specific file that combines the expressiveness of JavaScript with HTML-like template syntax. This makes the HTML file extremely simple to comprehend. This file strengthens and improves the performance of applications. Here's an example of JSX in action:
render(){
return(
<div>
<h1> Hello World!</h1>
</div>
);
}
7. What do you understand by Virtual DOM?
A virtual DOM is a small JavaScript object that is essentially a copy of the real DOM. It's a node tree in which the elements, their attributes, and content are listed as Objects and their properties. The render function in React creates a node tree from React components. It then updates this tree in response to mutations in the data model, which are caused by various user or system actions.
8. Explain how Virtual DOM works?
There are three simple steps to using this Virtual DOM:
- The entire UI is re-rendered in Virtual DOM representation whenever any underlying data changes.
- The difference between the old and new DOM representations is then calculated.
- After the calculations are completed, the real DOM will be updated to reflect only the changes that have occurred.
9. Why can’t browsers read JSX?
Only JavaScript objects can be read by browsers, but JSX is not a regular JavaScript object. To allow a browser to read JSX, we must first convert the JSX file into a JavaScript object using JSX transformers such as Babel, and then pass it to the browser.
10. How different is React’s ES6 syntax when compared to ES5?
The following aspects of syntax have changed from ES5 to ES6:
require vs import
// ES5
var React = require('react');
// ES6
import React from 'react';
export vs exports
// ES5
module.exports = Component;
// ES6
export default Component;
component and function
// ES5
var MyComponent = React.createClass({
render: function() {
return
<h3>Hello Ninjas!</h3>
;
}
});
// ES6
class MyComponent extends React.Component {
render() {
return
<h3>Hello Ninjas!</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>
;
}
}
11. How is React different from Angular?
React |
Angular |
The architecture has only the View part of MVC |
It has complete MVC architecture |
Server-side rendering | Client-side rendering |
Virtual DOM | Real DOM |
One-way data binding | Two-way data binding |
Compile time debugging | Runtime debugging |
Made by Facebook | Made by Google |
12. Everything is a component in React. Explain.
The UI of a React application is made up of components. These components break down the entire user interface into small, reusable chunks. Then, without affecting the rest of the UI, it renders each of these components independent of one another.
13. What is the purpose of render() in React?
Render() is required for every React component. It returns a single React element that is the native DOM component's representation. If more than one HTML element needs to be rendered, they must all be contained within one enclosing tag, such as <form>, <group>, or <div>. This function must be kept pure, which means it must always return the same result.
14. What is Props?
Props is React's shorthand for Properties. They are read-only components that must be kept immutable and pure. Throughout the application, they are always passed down from the parent to the child components. A prop can never be sent back to the parent component by a child component. This aids in the preservation of unidirectional data flow and is commonly used to render dynamically generated data.
15. What is a state in React and how is it used?
React components are built around states. States serve as a data source and should be kept as simple as possible. In a nutshell, states are the objects that determine how components are rendered and behave. They, unlike the props, are mutable and create dynamic and interactive elements. This is how you get to them. state().
16. Differentiate between states and props.
State |
props |
It receives the initial value from parent component | It receives the initial value from parent component |
Parent component cannot change its value | Parent component can change its value |
It sets the default values inside component | It sets the default values inside component |
It changes inside component | It cannot change inside component |
Set initial value for child components | Set initial value for child components |
It does not change inside child components | It changes inside child components |
17. How can you update the state of a component?
The this.setState() can be used to update the state of a component.
class MyComponent extends React.Component {
constructor() {
super();
this.state = {
name: 'Max',
id: '10'
}
}
render()
{
setTimeout(()=>{this.setState({name:'Jay', id:'22'})},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?
Arrow functions are a type of short syntax for expressing a function. The functions are also known as 'fat arrows' (=>). Because auto binding is not available by default in ES6, these functions allow you to properly bind the context of your components. When working with higher order functions, arrow functions are particularly useful.
//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 components |
Stateless Component |
In memory, information about a component's state change is stored. | Calculates the components' internal state. |
Have the power to change the state | I don't have the power to change the state. |
It contains information about past, current, and potential state changes. | There is no knowledge of previous, current, or potential future state changes. |
Stateless components notify them of the state change requirement, and then they send the props down to them. | They treat the props received from Stateful components as callback functions. |
20. What are the different phases of React component’s lifecycle?
The lifecycle of a React component is divided into three stages:
- The component is about to begin its life journey and make its way to the DOM during the initial rendering phase.
- Phase of updating: After the component is added to the DOM, it can only update and re-render when a prop or state changes. This occurs only during this phase.
- The component is destroyed and removed from the DOM during the unmounting phase of its life cycle.
21. Explain the lifecycle methods of React components in detail.
The following are some of the most important lifecycle methods:
- componentWillMount()– This method is called just before rendering on both the client and server sides.
- componentDidMount()– Only executed after the first render on the client side.
- componentWillReceiveProps()– Called as soon as the props from the parent class are received and before another render.
- should
- ComponentUpdate()– Based on certain conditions, returns a true or false value. Return true if you want your component to update; otherwise, return false. It returns false by default.
- componentWillUpdate()– This method is called just before the DOM is rendered.
- componentDidUpdate()– Called as soon as the rendering is complete.
- componentWillUnmount()– When the component is unmounted from the DOM, this method is called. Its purpose is to free up memory space.
22. What is an event in React?
Events in React are the triggered responses to specific actions such as mouse hover, mouse click, key press, and so on. Taking care of these events is similar to taking care of events in DOM elements. However, there are some syntactical distinctions, such as:
- Instead of using lowercase, camel case is used to name events.
- Instead of strings, events are passed as functions.
The event argument specifies a set of properties that are unique to that event. Each event type has its own set of properties and behaviours that can only be accessed through the event handler.
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 objects that wrap the browser's native event in a cross-browser wrapper. They combine the functionality of various browsers into a single API. This is done to ensure that the properties of the events are consistent across browsers.
25. What do you understand by refs in React?
References in React are abbreviated as Refs. It's an attribute that allows you to save a reference to a specific React element or component, which will be returned by the render configuration function of the component. It's used to get references to a specific element or component returned by render(). They're useful when we need to make DOM measurements or add methods to components.
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 when you should use Refs.
The following are examples of when references should be used:
- Select text or media playback when you need to manage focus.
- To make imperative animations happen.
- Third-party DOM libraries can be integrated.
27. How do you modularize code in React?
The export and import properties can be used to modularize code. They aid in the separation of components into separate files.
//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?
Forms in React are similar to those in HTML. In React, however, the state is stored in the component's state property and can only be updated using setState(). As a result, the elements can't update their state directly, so a JavaScript function handles their submission. This function has complete access to the information that a user enters into a form.
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 |
They do not maintain their own state. | They maintain their own state. |
The parent component is in control of data. | The DOM is in control of data. |
They use props to get the current values and then use callbacks to notify them of changes. | To get their current values, refs are used. |
30. What are Higher Order Components(HOC)?
Higher Order Component is a more sophisticated method of reusing component logic. It's essentially a pattern derived from React's compositional nature. HOCs are custom components that enclose another component. They can accept any dynamically provided child component, but they will not change or copy the behaviour of their input components. HOC can be described as 'pure' components.
31. What can you do 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?
Pure components are the simplest and most quickly written components. They can be used to replace any component that has only a render(). These components improve the code's simplicity as well as the application's performance.
Learn more, Html interview questions
33. What is the significance of keys in React?
Keys are used to distinguish between different Virtual DOM Elements and the data that drives the UI. They assist React in optimising rendering by recycling all existing DOM elements. These keys must be a unique number or string, and React will only reorder the elements rather than re-rendering them if you use them. As a result, the application's performance improves.
34. What were the major problems with MVC framework?
The following are some of the most serious issues with the MVC framework:
- Manipulation of the DOM was extremely costly.
- The applications were sluggish and ineffective.
- There was a lot of wasted memory.
- A complicated model was built around models and views due to circular dependencies.
35. What is Flux?
Flux is an architectural pattern that enforces data flow in only one direction. It uses a central Store, which has authority over all data, to control derived data and enable communication between multiple components. Any data updates throughout the application must happen only here. Flux improves the application's stability and reduces run-time errors.
36. What is Redux?
In today's market, Redux is one of the most popular front-end development libraries. It is a state container for JavaScript applications that is used to manage the entire state of the application. Redux applications are simple to test and can run in a variety of environments with consistent behaviour.
37. What are the three principles that Redux follows?
- Single source of truth: Within a single store, the entire application's state is stored in an object/state tree. The single state tree simplifies debugging and inspecting the application as well as keeping track of changes over time.
- State is read-only: Triggering an action is the only way to change the state. An action is a simple JS object that describes a change. The action is the minimal representation of the change to that data, just as the state is the minimal representation of data.
- Changes are made with pure functions: Pure functions are required to specify how the state tree is transformed by actions. Pure functions are those whose return value is solely determined by the arguments' values.
38. What do you understand by “Single source of truth”?
The 'Store' function in Redux is used to store the application's entire state in one place. As a result, all of the component's state is saved in the Store, and they receive updates directly from the Store. The single state tree simplifies debugging and inspecting the application as well as keeping track of changes over time.
39. List down the components of Redux.
Redux is made up of the following elements:
- Action: An object that describes what happened is called an action.
- Reducer: This is where you'll figure out how the state will change.
- Store: The entire application's state/object tree is saved in the Store.
- View: This option simply shows the data that the Store has provided.
40. How are Actions defined in Redux?
In React, actions must have a type property that specifies the type of ACTION that is being performed. They must be defined as a String constant, and you can extend it with additional properties. Action Creators are functions in Redux that are used to create actions. An example of Action and Action Creator is shown below:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
41. Explain the role of Reducer.
Reducers are pure functions that describe how the state of the application changes in response to an ACTION. Reducers operate by taking the previous state and action and returning a new state. Based on the type of action, it determines what type of update is required and then returns new values. If no work needs to be done, it returns to the previous state.
42. What is the significance of Store in Redux?
A store is a JavaScript object that can store the state of an application and provides a few helper methods for accessing the state, dispatching actions, and registering listeners. An application's entire state/object tree is saved in a single store. As a result, Redux is very straightforward and predictable. We can send middleware to the store to handle data processing and keep track of various actions that change the state of the stores. Reducers are used in all of the actions to return a new state.
43. What are the advantages of Redux?
The following are some of Redux's benefits:
- Predictability of outcome: Because there is only one source of truth, the store, there is no confusion about how to sync the current state with actions and other parts of the app.
- Maintainability: With a predictable outcome and strict structure, the code becomes easier to maintain.
- Server-side rendering: All you have to do is pass the store that was created on the server to the client. This is very useful for the initial render and improves the user experience by improving application performance.
- Developer tools: From actions to state changes, developers can keep track of everything that is happening in the app in real time.
- Community and ecosystem: Redux has a large community and ecosystem behind it, which makes it even more appealing to use. A large group of talented people contribute to the library's improvement and development of various applications.
- Ease of testing: Redux's code is mostly made up of small, pure, and isolated functions. As a result, the code is testable and self-contained.
- Organization: Redux is very specific about how code should be organised, which makes the code more consistent and easier to work with when a team is working on it.
Must Read Web Developer Interview Questions
44. What is React Router?
React Router is a powerful routing library built on top of React that makes it easier to add new screens and flows to your app. This keeps the URL up to date with the information on the web page. It's used to create single-page web applications because it has a standardised structure and behaviour. React Router has a straightforward API.
45. Why is switch keyword used in React Router v4?
Although, within the Router, a <div> is used to encapsulate multiple routes. The'switch' keyword is used when you only want a single route to be rendered out of the many defined routes. When used, the <switch> tag matches the typed URL with the defined routes in order. When the first match is found, the specified route is rendered. As a result, the remaining routes are bypassed.
46. Why do we need a Router in React?
A Router is used to define multiple routes, and when a user types a specific URL, the user is redirected to that route if the URL matches the path of any 'route' defined inside the router. So, we need to add a Router library to our app that allows us to create multiple routes, each of which leads to a different view.
<switch>
<route exact path=’/’ component={Home}/>
<route path=’/posts/:id’ component={Newpost}/>
<route path=’/posts’ component={Post}/>
</switch>
47. List down the advantages of React Router.
Among the benefits are:
- React Router v4's API is 'All About Components,' similar to how React is built on components. A Router can be thought of as a single root component (<BrowserRouter>) in which the specific child routes (<route>) are contained.
- There's no need to set the History value manually: All we have to do in React Router v4 is wrap our routes in the <BrowserRouter> component.
- The packages are divided into two categories: There are three packages: one for Web, one for Native, and one for Core. This contributes to our application's small size. It's simple to switch over because the coding styles are similar.
48. What is React Fiber?
In React v16, Fiber is a new reconciliation engine or reimplementation of the core algorithm. React Fiber's goal is to improve its suitability in areas such as animation, layout, gestures, the ability to pause, abort, or reuse work, and assign priority to different types of updates; and new concurrency primitives.
49. What is the main goal of React Fiber?
React Fiber’s main goal are:
- The ability to divide interruptible work into manageable chunks.
- Work in progress can be prioritised, rebased, and reused.
- To support layout in React, the ability to yield back and forth between parents and children is required.
- Returning multiple elements from a render().
- Error boundaries are better supported
50. What is the difference between createElement and cloneElement?
Elements from JSX will be converted to React. To create React elements that will be used for UI object representation, use the createElement() functions. CloneElement, on the other hand, is used to duplicate an element and pass it new props.
Check out Advantages of React JS here.