ad

React JS Questions with Answers to Crack the Technical Interview

React is considered as the fastest growing Javascript framework. Slowly and steadily, the JavaScript tools are firming their roots in the marketplace and the demand for React is increasing exponentially , and if you are preparing for a job interview, this is ReactJS interview questions tutorial is just the right one for you. Here’s a comprehensive list of all the common ReactJS interview questions from basic to advanced levels that are frequently asked in interviews.

Q1. What is React?

React (aka React.js or ReactJS) is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative approach.

React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.

Q2. What are the features of React?

The features of React are as follows:

 1. JSX

JSX serves as a syntax extension to JavaScript, facilitating the combination of HTML structures with JavaScript code within React files.

2. Components

JSX serves as a syntax extension to JavaScript, facilitating the combination of HTML structures with JavaScript code within React files.

3. Virtual DOM

React employs a Virtual DOM, which is a lightweight representation of the actual DOM stored in memory. This approach allows React to selectively update only the relevant parts of the real DOM when the state of an object changes.

4. Data Binding

React adopts a one-way data-binding approach, ensuring a modular and efficient structure. Unidirectional data flow signifies that in a React app, child components are often nested within parent components.

5. High Performance

React’s high performance is driven by its ability to update only the components that undergo changes, rather than refreshing the entire set. This results in significantly faster web applications.

Q3. What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){
return(

<div>

<h1> Hello World from Edureka!!</h1>

</div>

);
}

Q4. What is difference between element and component in React?

An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it cannot be mutated.

The JavaScript representation(Without JSX) of React Element would be as follows:

const element = React.createElement("div", { id: "login-btn" }, "Login");

and this element can be simiplified using JSX

<div id="login-btn">Login</div>

The above React.createElement() function returns an object as below:

{
type: 'div',
props: {
children: 'Login',
id: 'login-btn'
}
}

Finally, this element renders to the DOM using ReactDOM.render().

Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:

const Button = ({ handleLogin }) => (
<div id={"login-btn"} onClick={handleLogin}>
Login
</div>
);

Then JSX gets transpiled to a React.createElement() function tree:

const Button = ({ handleLogin }) =>
React.createElement(
"div",
{ id: "login-btn", onClick: handleLogin },
"Login"
);

Q5. How to create components in React?

Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.

1. Function Components

Function components are the simplest way to create a component in React. They are pure JavaScript functions that take a props object as the first parameter and return React elements to display the output.

Example of a function component

function Welcome({ personName }) {

return <h1>{`Welcome, ${personName}!`}</h1>;

}

In this function component, Welcome takes a personName prop and displays a personalized welcome message.

2. Class Components

Alternatively, you can use ES6 classes to define a component. The equivalent class component for the above function component would look like this:

class Greeting extends React.Component {

render() {

return <h1>{`Greetings, ${this.props.userName}!`}
</h1>;

}

}

In this class component, Greeting extends React.Component and uses a render method to display a greeting. This prop is accesed using this.props.userName.

Both function and class components accomplish the same goal of creating reusable and modular pieces of UI. The choice between them depends on the complexity of the component and whether state or lifecycle methods are needed.

Q6. List some of the major advantages of React.

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. React is easy to integrate with other frameworks like Meteor, Angular, etc
  5. Using React, writing UI test cases become extremely easy

Q7. 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 little difficult for the novice programmers to understand
  4. Coding gets complex as it uses inline templating and JSX

Q8. What is the Virtual DOM?

The Virtual DOM is like a blueprint or a copy of the real DOM that is stored in the computer’s memory. It’s a concept used by React to make updating and changing things on a webpage more efficient.

Q9. What do you understand by Virtual DOM? Explain its works.

A virtual DOM is a lightweight JavaScript object which originally is just a copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

This Virtual DOM works in three simple steps.

  1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
  2. Then the difference between the previous DOM representation and the new one is calculated.
  3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed. 

Q10. Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

Q11. How is React different from 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

Q12.  “In React, everything is a component.” Explain.

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

Q13. What is the purpose of render() in React.

Each React component must have a render() mandatorily. 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.

Q14. What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

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

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.

States vs 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

Q17. What are keys in React and why do we need them?

The “key” is a special attribute used when working with arrays of elements in React. It helps React keep track of changes, additions, and removals in the array.

When you’re rendering a list of items, React needs a way to identify each item uniquely. The “key” prop serves this purpose, allowing React to efficiently update the user interface.

Example

Suppose you have a list of books:

const books = [

{ id: 1, title: "React Magic" },

{ id: 2, title: "JavaScript Wonders" },

{ id: 3, title: "Web Development Odyssey" },

];

You can use the “key” prop when mapping over this array to render each book:

const bookItems = books.map((book) => <li
key={book.id}>{book.title}</li>);

Here, we’re using the unique id of each book as the key.

Note

  • It’s crucial to use unique keys among siblings to avoid issues.
  • If your data doesn’t have stable IDs, using the item index as a key is a last resort. However, this is not recommended if the order of items may change, as it can impact performance.
  • If you extract list items into separate components, apply keys to the component instead of the li tag.
  • The “key” attribute accepts either a string or a number, and it’s converted internally to a string type.
  • A warning message will appear in the console if the “key” prop is not present on list items.

Q18. What are Pure Components?

Pure components are the components which render the same output for the same state and props. In function components, you can achieve these pure components through memoized React.memo() API wrapping around the component. This API prevents unnecessary re-renders by comparing the previous props and new props using shallow comparison. So it will be helpful for performance optimizations.

Q19. What is state in React?

State of a component is an object that holds some information that may change over the lifetime of the component. The important point is whenever the state object changes, the component re-renders. It is always recommended to make our state as simple as possible and minimize the number of stateful components.

Q20. How are comments written in React?

Comments in React/JSX are similar to JavaScript multiline comments but are enclosed in curly braces.

Single-line comments
<div>

{/* Single-line comments(In vanilla JavaScript, the
single-line comments are represented by double
slash(//)) */}

{`Welcome, ${userName}! Let's dive into React`}

</div>
Multi-line comments
<div>

{/*

This is a multiline comment in React.

It provides additional information about the
code.

*/}

{`Welcome, ${userName}! Let's dive into React`}

</div>

In these modified examples, the comments now convey a welcoming message to the user, demonstrating how comments can be used to explain and document code within the JSX structure.

Q21. What is the difference between HTML and React event handling?

Below are some of the main differences between HTML and React event handling,

1. In HTML, the event name usually represents in lowercase as a convention:

.<button onclick="activateLasers()"></button>

Whereas in React it follows camelCase convention:

<button onClick={activateLasers}>

2. In HTML, you can return false to prevent default behavior:

<a
href="#"
onclick='console.log("The link was clicked."); return false;'
/>

Whereas in React you must call preventDefault() explicitly:

function handleClick(event) {
event.preventDefault();
console.log("The link was clicked.");
}

3. In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer “activateLasers” function in the first point for example).

Q22. What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper around the browser’s native event. Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. The native events can be accessed directly from synthetic events using nativeEvent attribute.

Q23. What are inline conditional expressions?

You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.

<h1>Hello!</h1>;
{
messages.length > 0 && !isLogin ? (
<h2>You have {messages.length} unread messages.</h2>
) : (
<h2>You don't have unread messages.</h2>
);
}

Q24. What is the difference between Shadow DOM and Virtual DOM?

The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.

Q26. What is React Fiber?

Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.

Q27. What is the main goal of React Fiber?

he goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

Its main goals are:

  1. Ability to split interruptible work in chunks.
  2. Ability to prioritize, rebase and reuse work in progress.
  3. Ability to yield back and forth between parents and children to support layout in React.
  4. Ability to return multiple elements from render().
  5. Better support for error boundaries.

Q28. What are controlled components?

A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function. That means, the displayed data is always in sync with the state of the component.

The controlled components will be implemented using the below steps,

  1. Initialize the state using use state hooks in function components or inside constructor for class components.
  2. Set the value of the form element to the respective state variable.
  3. Create an event handler to handle the user input changes through useState updater function or setState from class component.
  4. Attach the above event handler to form elements change or click events.

Q29. What are uncontrolled components?

The Uncontrolled Components are the ones that store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

The uncontrolled components will be implemented using the below steps,

  1. Create a ref using useRef react hook in function component or React.createRef() in function component.
  2. Attach this ref to the form element.
  3. The form element value can be accessed directly through ref in event handlers or componentDidMount for class components

Q30. What is the difference between createElement and cloneElement?

JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.

Q31. What is Lifting State Up in React?

When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.

Q32. Explain how lists are created in React?

Lists are essential for displaying dynamic content on a website. In React, you can create a list using the method of an array. Here’s an example:

import React from 'react';

import ReactDOM from 'react-dom';

// Example list of items

const fruits = ['Apple', 'Banana', 'Orange', 'Grapes',
'Watermelon'];

// Using map to create a list of JSX elements

const fruitList = fruits.map((fruit, index) => {

return <li key={index}>{fruit}</li>;

});

// Rendering the list inside an unordered list

ReactDOM.render(

<ul>

{fruitList}

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

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

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

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

Q34. What are Higher-Order Components?

A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature.

We call them pure components because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

HOC can be used for many use cases:

  1. Code reuse, logic and bootstrap abstraction.
  2. Render hijacking.
  3. State abstraction and manipulation.
  4. Props manipulation.

Q35. Differentiate between stateful and stateless components.

Stateful vs Stateless

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 them as callback functions.

Q36. What is children prop?

Children is a prop that allows you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

A simple usage of children prop looks as below,

function MyDiv({ children }){
return (
<div>
{children}
</div>;
);
}

export default function Greeting() {
return (
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>
);
}

Q37. What is reconciliation?

Reconciliation is the process through which React updates the Browser DOM and makes React work faster. React use a diffing algorithm so that component updates are predictable and faster. React would first calculate the difference between the real DOM and the copy of DOM (Virtual DOM) when there’s an update of components. React stores a copy of Browser DOM which is called Virtual DOM. When we make changes or add data, React creates a new Virtual DOM and compares it with the previous one. This comparison is done by Diffing Algorithm. Now React compares the Virtual DOM with Real DOM. It finds out the changed nodes and updates only the changed nodes in Real DOM leaving the rest nodes as it is. This process is called Reconciliation.

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

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

  1. Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.
  2. Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.
  3. Unmounting Phase: This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.

Q39. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

  1. componentWillMount()  Executed just before rendering takes place both on the client as well as server-side.
  2. componentDidMount()  Executed on the client side only after the first render.
  3. componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.
  4. shouldComponentUpdate()  Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.
  5. componentWillUpdate() – Called just before rendering takes place in the DOM.
  6. componentDidUpdate()  Called immediately after rendering takes place.
  7. componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.

Q40. What is an event in React?

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

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

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

);
}
});

Q42. Why React uses className over class attribute?

The attribute names written in JSX turned into keys of JavaScript objects and the JavaScript names cannot contain dashes or reversed words, it is recommended to use camelCase whereever applicable in JSX code. The attribute class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principle reason why React uses className instead of class. Pass a string as the className prop.

render() {
return <span className={'menu navigation-menu'}>{'Menu'}</span>
}

Q43. What are fragments?

It’s a common pattern or practice in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. You need to use either or a shorter syntax having empty tag (<></>).

Below is the example of how to use fragment inside Story component.

function Story({title, description, date}) {
return (
<Fragment>
<h2>{title}</h2>
<p>{description}</p>
<p>{date}</p>
</Fragment>
);
}

Q44. Why fragments are better than container divs?

Below are the list of reasons to prefer fragments over container DOM elements,

  1. Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
  2. Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
  3. The DOM Inspector is less cluttered.

Q45. How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user 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>

);
}

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

Q47. What are portals in React?

Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. When using CSS transform in a component, its descendant elements should not use fixed positioning, otherwise the layout will blow up.

ReactDOM.createPortal(child, container);

The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.

Q48. What are stateless components?

If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.

Q49. What are stateful components?

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are either function components with hooks or class components.

Let’s take an example of function stateful component which update the state based on click event,

import React, {useState} from 'react';

const App = (props) => {
const [count, setCount] = useState(0);
handleIncrement() {
setCount(count+1);
}

return (
<>
<button onClick={handleIncrement}>Increment</button>
<span>Counter: {count}</span>
</>
)
}

Q50. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:

  • DOM manipulation was very expensive
  • Applications were slow and inefficient
  • There was huge memory wastage
  • Because of circular dependencies, a complicated model was created around models and views.

Q51. Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

Q52. What are the recommended ways for static type checking?

Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.

Q53. What is the use of react-dom package?

The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:

  1. render()
  2. hydrate()
  3. unmountComponentAtNode()
  4. findDOMNode()
  5. createPortal()

Q54. How to use innerHTML in React?

The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.

In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

function createMarkup() {
return { __html: "First · Second" };
}

function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}

 

Search within CuiTutorial

Scroll to Top