Top 50+ Basic & Advanced ReactJS Interview Questions
What is ReactJS?
Top 50 React JS Interview Questions And Answers: React aka ReactJS or React.js is an open-source JavaScript library, developed by Facebook. With the component-based approach, it is useful in building user interface (UI) components for a single page application or mobile/web applications. It offers a simple programming model with a better quality performance.
React is mainly concerned with representing data to the data object model (DOM). The data it presents changes over time and can be updated based on the user’s action. Additional libraries (e.g. Redux and React router), state management and routing are required to create ReactJS applications.
How does ReactJS work?
Here’s the sequence of steps to give you an idea about how it works:
- Firstly, react creates a virtual DOM and runs the diffing algorithm to recognize the changes made in the virtual DOM
- The second step is reconciliation, where it upgrades the DOM with new features
- Next, the virtual DOM, which is lightweight in nature and is detached from the browser-specific implementation details
- Subsequently, the ReactElements, present in virtual DOM are utilized to create basic nodes
- Finally, when the ReactComponent changes the state; the diffing algorithm identifies the changes and automatically updates the DOM
What are the features and advantages of ReactJS?
ReactJS is a JavaScript library offering some great features and advantages in web development and transforming the workflow. Leading companies, including PayPal, Apple, Netflix, etc. utilize it to improve framework performance.
Features of ReactJS are as follows:
- JSX
- Components
- One-way Data Binding
- Virtual DOM
- Simplicity
Advantages of ReactJS are as follows:
- Simplifies the process of writing components
- Improves productivity and makes maintenance smoother
- Delivers an excellent solution for high-load application
- Ensures stable code
- Improves SEO (Search Engine Optimization) performance
- Provides an easier way to integrate with frameworks
- Ideal for mobile and web app development
- Easy to grasp and learn
What is DOM?
DOM is a bona fide API (Application Programming Interface) for HTML and corresponding XML documents. It presents the logical structure of documents and how they are retrieved and coerced. The term “document” is commonly used in DOM specification, XML is deployed as a way of demonstrating the different kinds of information stored in various systems. XML displays the data as documents and DOM handles this data. DOM makes it easy for the programmers to create, add, modify or delete the elements and content of the documents.
What is a virtual DOM?
Though the Virtual DOM objects hold similar properties as a real DOM object, but it’s known as the compact version of a DOM object as it is unable to make any changes directly on the screen. Virtual DOM is more like making changes in software code than in the actual hardware. It is faster than DOM as it can be manipulated easily.
What is JSX?
JSX means JavaScript XML, having the complete capabilities of JavaScript. It makes it easy to write HTML elements in JavaScript and also locate them in the DOM without any createElement() and/or appendChild() methods. Any HTML tags can be converted into react elements with JSX. Though it is not necessary to use JSX but it’s really convenient to write React applicants with it.
Below is the syntax for a basic element in React with JSX and its equivalent without it.
Equivalent of the above using React.createElement
Why can’t browsers read JSX?
React uses JSX (JavaScript Extension) that allows us to replicate HTML in JavaScript. Since, JSX is not valid JavaScript, web browsers can’t read it directly. So, if JavaScript files have JSX, that file needs to be transpiled. A transpiler will be needed to convert JSX to regular Javascript that browsers can read and understand. The most popular transpiler right now is Babel.
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> }
What is ReactDOM and how’s it different from React?
React, and ReactDOM are recently divided into two different libraries. All ReactDOM functionality was part of React, before v0.14.
ReactDOM acts as a bridge between React and the DOM, often used for mounting with ReactDOM. Another essential feature of ReactDOM is ReactDOM.findDOMNode() which provides you direct access to a DOM element.
For everything else, there’s React. It is used to define and create elements, for lifecycle hooks, etc. i.e. the guts of a React application. The React functionality is used in web and mobile applications whereas ReactDOM functionality is only for web apps.
How to Create React component?
Below are the steps to create React components:
- The class components are created by first naming it like “Example”
- A constructor is added to the class component to further add a state of the class component
- Then, the Render method is introduced to return the JSX. The JSX must be wrapped in an outer element like <div>
- Now, the ‘this’ keyword must be bound inside the constructor, for it to be used anywhere
- To use the component, make sure it is imported into a file (in case the components are in separate files). Once imported, add the assigned name to the JSX
- Then, the specific ‘Props’ are passed to the component. Each prop must be given a name
- The props must be put into the arguments for the components to receive them. Once received, they can be accessed in the JSX by using ‘this.props.NameOfProp’
- Once all the above steps are performed, the code can be completed
What is the purpose of render() in React?
The render() function must return something, be it null. The component file is called the render() method by default as the component needs to present the HTML markup or JSX syntax. Each React component must have a render() mandatorily. The single React element returned represents the native DOM component. If there’s more than one HTML element is rendered, they must be grouped together inside one enclosing tag such as <form>, <group>,<div>, etc. The function must return the same result every 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;
Differences between the class component and functional component?
A functional component is kind of a standard JavaScript function.
Class components enable us to use additional features, including local state and lifecycle hooks. It specifies to extend from React and enable the component to have direct access to the store and thus holds state.
When the props are received by the component and rendered to the page, for this ‘stateless component’ pure function can be used. They are also known as dumb components or presentational components.
What are the Pure components in ReactJS?
Pure components play a vital role to re-render a component. Pure component helps to use the lifecycle method for comparing the states or props for any changes in the properties before re-rendering of the component.
In brief, pure components are meant to evaluate and compare the properties of the current state or prop with the next one and also check how the parent component is different from the child component in the hierarchy.
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')
What is the arrow function in React? How is it used?
The fat arrow => is meant to define anonymous functions. It is one of the effective and easy ways to pass parameters to callback functions. Make sure to optimize the performance while using it.
Note: Using an arrow function in render method creates a new function every 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) } /> ); }
What are the different phases of React component’s lifecycle?
Below are the different phases of React component’s lifecycle:
- Initialization
In the initialization phase, defaults and initial values for this.props and this.state are defined.
- Mounting
Mounting is the process that takes place when a component is being inserted into the DOM.
- Updating
In this phase, the component is updated whenever the state is changed or component receives a new prop.
- Unmounting
This is the phase when the component is unmounted from the DOM.
Differentiate between the controlled and uncontrolled components in React?
While creating web pages in ReactJs, the form data in handled by React components using ‘controlled’ elements
(e.g., this.state = {}, in case of defaultValue = {this.state.username} onChangeText = {text => this.setState({username: text})}, And defaultValue = {this.state.password} onChangeText = {text => this.setState({password: text})}).
Similarly, in the case of uncontrolled components, the form data is handled by the DOM itself instead of React.
(e.g., console.log(this._username, this._password) <Text>Username</Text> <TextInput ref={input => this._username = input} /> <Text>Password</Text> <TextInput \ />)
Note: Refs=uncontrolled elements, state= controlled elements
How can you differentiate between the state and props in ReactJS?
State: The state is a data structure that belongs to a single component and changes its output to respond to certain events over time. The states are managed by the component in its entirety.
Prop: Props, on the other hand, are read-only functions. Throughout the component’s lifecycle, they display a fixed character. They are stateless and are utilized to customize components at the time of their creation.
What is the difference between the HTML and React event handling process?
HTML events are written in lowercase, whereas React events are written using camelCase;
Unlike HTML events, the coder can’t stop or prevent a default behavior by returning false. It must be stated as ‘preventDefault’.
What are higher-order components?
Higher-order component (HOC) is a technique developed to reuse components in React. React API has nothing to do with HOC. HOC is a pattern which is the outcome of React’s compositional nature. A higher-order component is a function that guides a component and returns a new component.
How to embed two components in one component?
import React from 'react'; class App extends React.Component{ render(){ return( <div> <Header/> <Content/> </div> ); } } class Header extends React.Component{ render(){ return( <div> <h1> Header</h1> </div> ) } } class Content extends React.Component{ render(){ return( <h2>Content</h2> <p>The Content Text!!!</p> </div> ) } } export default App;
What is Redux?
It is a predictable state container for JS Apps. Redux is a small open-source JavaScript library for managing application state. It is a limited and straightforward API designed to be a predictable container for application state. It is executed similarly to the rendering function. The functional programming language Elm has a significant impact on Redux. It is commonly used with libraries such as React or angular for building UI. It is similar to Flux
What is Use of Redux thunk?
Redux thunk is middleware that enables to write action creators that return functions instead of actions. It can be also used as a delay function for delaying dispatch of action if a certain condition is met. The two store methods getState() and dispatch() act as parameters to the inner function.
In order to activate Redux thunk, applyMiddleware() method should be used as shown below: