CodingJump border
ReactJS Interview Questions
Published on

ReactJS Interview Questions

Table of Contents

What are the features of React?

  • JSX
  • Components
  • Virtual DOM
  • One Way Data Binding
  • High Performance

What is JSX?

JSX is a syntax extension of JavaScript. It is used with React to describe what the user interface should look like. By using JSX, we can write HTML structures in the same file that contains JavaScript code.

Can web browsers read JSX directly?

  • Web browsers cannot read JSX directly. This is because they are built to only read regular JS objects and JSX is not a regular JavaScript object
  • For a web browser to read a JSX file, the file needs to be transformed into a regular JavaScript object. For this, we use Babel

What is virtual DOM?

DOM stands for Document Object Model. The DOM represents an HTML document with a logical tree structure. Each branch of the tree ends in a node, and each node contains objects.

React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, the virtual DOM changes only that object in the real DOM, rather than updating all the objects.

Why use React instead of other frameworks, like Angular?

  • Easy creation of dynamic applications
  • Improved performance
  • Reusable components
  • Unidirectional data flow
  • Dedicated tools for easy debugging

What is the difference between the ES6 and ES5 standards?

Spread Operator

function sum(x, y, z) {
  return x + y + z

const numbers = [1, 2, 3]

// expected output: 6

Template Literal

;`string text line 1
 string text line 2
 string text line ${1 + 1 + 1}`

Arrow Functions

// Traditional Function
function (a){
  return a + 100;

// Arrow Function
a => a + 100;


class Rectangle {
  constructor(height, width) {
    this.height = height
    this.width = width

Import Keyword

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. It was introduced in ES6.

What is an event in React?

An event is an action that a user or system may trigger, such as pressing a key, a mouse click, etc.
React events are named using camelCase rather than lowercase in HTML.
With JSX, you pass a function as the event handler rather than a string in HTML.

<Button onPress={HelloWorld} />

How do you create an event in React?

class CodingJump extends React.Component {
  HelloWorld() {
    alert('Hello CodingJump!')
  render() {
    return <button onClick={this.HelloWorld}>Click me!</button>

What are synthetic events in React?

Synthetic events combine the response of different browser’s native events into one API, ensuring that the events are consistent across different browsers. So that the application response is consistent regardless of the browser it is running on.

Function SyntheticEvent {
	function handleClick(e) {
		console.log('Clicked Link');
	return (
		<a href="#" onClick={handleClick}>Click Me!</a>

Here, handleClick is a synthetic event. The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

Why is there a need for using keys in Lists?

  • A key is a unique identifier and it is used to identify which items have changed, been updated, or deleted from the lists
  • It also helps to determine which components need to be re-rendered instead of re-rendering all the components every time. Therefore, it increases performance, as only the updated components are re-rendered

What are forms in React?

React employs forms to enable users to interact with web applications.

  • Using forms, users can interact with the application and enter the required information whenever needed. Form contain certain elements, such as text fields, buttons, checkboxes, radio buttons, etc
  • Forms are used for many different tasks such as user authentication, searching, filtering, indexing, etc

What are the components in React?

Components are the building blocks of any React application, and a single app usually consists of multiple components. A component is essentially a piece of the user interface. It splits the user interface into independent, reusable parts that can be processed separately.

There are two types of components in React:

  • Functional Components
  • Class Components

Explain Functional components in React?

These types of components have no state of their own and only contain render methods, and therefore are also called stateless components. They may derive data from other components as props (properties).

Explain Class components in React?

These types of components can hold and manage their own state and have a separate render method to return JSX on the screen. They are also called Stateful components as they can have a state.

What is the use of render() in React?

  • It is required for each component to have a render() function. This function returns the HTML, which is to be displayed in the component.
  • If you need to render more than one element, all of the elements must be inside one parent tag like <div>, <form>.
class App extends React.Component {
  render() {
    return <h1>Hello CodingJump!</h1>

Explain React Fragment?

React fragments let you group a list of children without adding extra nodes to the DOM because fragments are not rendered to the DOM. So basically, we use React. Fragment where we would normally use a wrapper div.

render() {
  return (
      <ChildA />
      <ChildB />
      <ChildC />

What is a state in React?

The state is a built-in React object that is used to contain data or information about the component. The state in a component can change over time, and whenever it changes, the component re-renders.

The change in state can happen as a response to user action or system-generated events. It determines the behavior of the component and how it will render.

What are the things to take care of while using the setState() function?

  1. setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
  2. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Why Not Modify React State Directly?

Mutating state directly can lead to odd bugs and components that are hard to optimize. Optimized components might not re-render if you do, and the rendering bugs will be tricky to track down.

What are props in React?

  • Props are short for Properties. It is a React built-in object that stores the value of attributes of a tag and works similarly to HTML attributes.
  • Props provide a way to pass data from one component to another component. Props are passed to the component in the same way as arguments are passed in a function.

What is a higher-order component in React?

A higher-order component acts as a container for other components. This helps to keep components simple and enables re-usability. They are generally used when multiple components have to use a common logic.

Explain the lifecycle methods of components?

  • getInitialState(): This is executed before the creation of the component.
  • componentDidMount(): This is executed when the component gets rendered and placed on the DOM.
  • shouldComponentUpdate(): This is invoked when a component determines changes to the DOM and returns a “true” or “false” value based on certain conditions.
  • componentDidUpdate(): Is invoked immediately after rendering takes place.
  • componentWillUnmount(): Is invoked immediately before a component is destroyed and unmounted permanently.

Explain the differences between class and functional components?

Class Components Functional Components
State Can hold or manage state Cannot hold or manage state
Simplicity Complex as compared to the stateless component Simple and easy to understand
Lifecycle methods Can work with all lifecycle methods It does not work with any lifecycle method
Reusability Can be reused It cannot be reused

How do you style React components?

Inline Styling

We can style the components with inline CSS.

class MyHeader extends React.Component {
  render() {
    return <h1 style={{ color: 'red' }}>Hello Style!</h1>

JavaScript Object

We can use a javascript object, which contains property names the same as CSS.

class MyHeader extends React.Component {
  render() {
    const mystyle = {
      color: 'white',
      backgroundColor: 'DodgerBlue',
      padding: '10px',
      fontFamily: 'Arial',
    return <h1 style={mystyle}>Hello Style!</h1>

CSS Stylesheet

We can also create a separate CSS file and include the same in our react file.

body {
  background-color: #282c34;
  color: white;
  padding: 40px;
  font-family: Arial;
  text-align: center;
import React from 'react'
import './App.css'

class MyHeader extends React.Component {
  render() {
    return <h1>Hello Style!</h1>

Explain the use of CSS modules in React?

The CSS module file is created with the .module.css extension

The CSS inside a module file is available only for the component that imported it, so there are no naming conflicts while styling the components.

What are Pure Components?

React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

How to bind methods or event handlers in JSX callbacks?

  1. Binding in Constructor
  2. Public class fields syntax
  3. Arrow functions in callbacks

What is the use of refs?

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need direct access to the DOM element or an instance of a component.

What are forward refs?

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

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.

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.

What is the React context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

For example, authenticated users, locale preferences, UI themes need to be accessed in the application by many components.

Why React uses className over class attribute?

class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class. Pass a string as the className prop.

What are the lifecycle methods going to be deprecated in React v16?

The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering.

  • componentWillMount()
  • componentWillReceiveProps()
  • componentWillUpdate()

Starting with React v16.3 these methods are aliased with UNSAFE_ prefix, and the unprefixed version will be removed in React v17.

What is the purpose of getDerivedStateFromProps() lifecycle method?

The new static getDerivedStateFromProps() lifecycle method is invoked after a component is instantiated as well as before it is re-rendered. It can return an object to update the state, or null to indicate that the new props do not require any state updates.

What is a switching component?

A switching component is a component that renders one of many components. We need to use objects to map prop values to components.

What are React Mixins?

Mixins are a way to totally separate components to have common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.

One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:

Why you can’t update props in React?

The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can’t modify received props.

Explain about Polyfills?

A Polyfill is a piece of code that adds functionality to older (or just less compliant) browsers so that you can use the latest and greatest features from the W3C specification.

How to decide React vs. Redux state?

  • Based on Duration
    • Short term/Rapid changes – React
    • Midterm – Redux
    • Long term – Redux and database
  • The breadth of Use – Redux
  • Depth of passing down props – Redux
  • Unrelated components needing the same state – Redux
  • Other use cases – React

Does React Components support inheritance?

Yes, we can do inheritance. But in React components, code reuse is primarily achieved through composition rather than inheritance.

How to update a component every second?

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

React Transition Group and React Motion are popular animation packages in React ecosystem.

What can you do with Higher-Order Components?

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

Explain Flux?

Flux is an architectural pattern that enforces the uni-directional data flow. It controls derived data and enables the communication between multiple components using a central Store that 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.

Differences between Flux and Redux?

The primary difference between Flux vs Redux is that Flux includes multiple Stores per app, but Redux includes a single Store per app. Rather than placing state information in multiple Stores across the application, Redux keeps everything in one region of the app

Why is Redux enforcing a single global store?

Consider your action uses multiple stores; there is the scope of forgetting to handle the action in certain stores. This causes an issue in application management. Also, it is hard to obtain an outline of what your state includes. Updates are another issue with multiple stores in Flux. These issues lead you to what a single centralized store in Redux offers. All the changes in Redux are made through a pure function called Reducers.

What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with the 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.

List some of the cases when you should use Refs?

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

What is the difference between ReactJS and React Native?

React Native is mostly used for developing mobile applications, whereas ReactJS is used for web applications.

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.
  • The 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 the 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.

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

Redux uses ‘Store’ for storing the application’s entire state in one place. So all the component’s states are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

List down the components of Redux?

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

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.

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

Explain the role of the Reducer?

Reducers are pure functions that specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is if no work needs to be done.

What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions, and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

What are the advantages of Redux?

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

What is Redux DevTools?

Redux DevTools is a live-editing time travel environment for redux with hot reloading, action replay, and customizable UI. If you don’t want to bother with installing Redux DevTools and integrating it into your project, consider using Redux DevTools Extension for Chrome and Firefox.

How to add multiple middlewares to Redux?

You can use applyMiddleware where you can pass each piece of middleware as a new argument. For example, you can add Redux Thunk and logger middlewares

import { createStore, applyMiddleware } from 'redux'
const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore)

What is Redux Thunk?

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of action or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState() as parameters.

What is redux-saga?

Redux-saga is a library that aims to make side effects (i.e., asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.

npm install --save redux-saga

Are there any similarities between Redux and RxJS?

These libraries are very different for very different purposes, but there are some vague similarities.

Redux is a tool for managing the state throughout the application. It is usually used as an architecture for UI. Think of it as an alternative to Angular.

RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises.

Redux uses the Reactive paradigm a little bit because the Store is reactive. The Store observes actions from a distance and changes itself. RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this “observing from a distance” pattern.

What is prop drilling and how can you avoid it?

While passing a prop from each component to the next in the hierarchy from the source component to the deeply nested component. This is called prop drilling.
To avoid prop drilling, a common approach is to use React context. This allows a Provider component that supplies data to be defined and allows nested components to consume context data via either a Consumer component or a useContext hook.

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.

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.

Explain about diffing algorithms used by React?

React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms are generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree.

In this case, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:

  1. Two elements of different types will produce different trees.
  2. The developer can hint at which child elements may be stable across different renders with a key prop.

How React Router is different from the history library?

React Router is a wrapper around the history library that handles interaction with the browser’s window. history with its browser and hash histories. It also provides memory history which is useful for environments that don’t have global histories, such as mobile app development (React Native) and unit testing with Node.

Different types of components in React Router v4?

  • <BrowserRouter>
  • <HashRouter>
  • <MemoryRouter>

The above components will create browser, hash, and memory history instances. React Router v4 makes the properties and methods of the history instance associated with your router available through the context in the router object.

What is the purpose of push() and replace() methods of history?

  • push()
  • replace()

If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.

What is React Intl?

The React Intl library makes internalization in React straightforward, with off-the-shelf components and an API that can handle everything from formatting strings, dates, and numbers, to pluralization. React Intl is part of FormatJS which provides bindings to React via its components and API.

What are the main features of React Intl?

  • Display numbers with separators.
  • Display dates and times correctly.
  • Display dates relative to “now”.
  • Pluralize labels in strings.
  • Support for 150+ languages.
  • Runs in the browser and Node.
  • Built on standards.

What is Shallow Renderer in React testing?

Shallow rendering is useful for writing unit test cases in React. It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.

What is TestRenderer package in React?

This package provides a renderer that can be used to render components to pure JavaScript objects, without depending on the DOM or a native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.

What is the purpose of the ReactTestUtils package?

ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.

What is Jest?

Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It’s often used for testing components.

What is Relay?

Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.

How Relay is different from Redux?

Relay is similar to Redux in that they both use a single store. The main difference is that relay only manages state originated from the server, and all access to the state is used via GraphQL queries (for reading data) and mutations (for changing data). Relay caches the data for you and optimizes data fetching for you, by fetching only changed data and nothing more.

What is reselect and how it works?

Reselect is a selector library (for Redux) that uses the memoization concept. It was originally written to compute derived data from Redux-like applications state, but it can’t be tied to any architecture or library.

Reselect keeps a copy of the last inputs/outputs of the last call and recomputes the result only if one of the inputs changes. If the same inputs are provided twice in a row, Reselect returns the cached output. Its memoization and cache are fully customizable.

What is Flow?

Flow is a static type checker designed to find type errors in JavaScript. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most types of systems.

What is the difference between Flow and PropTypes?

Flow is a static analysis tool (static checker) that uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

PropTypes is a basic type checker (runtime checker) which has been patched onto React. It can’t check anything other than the types of props being passed to a given component. If you want more flexible type checking for your entire project Flow/TypeScript are appropriate choices.

What is a windowing technique?

Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created. If your application renders long lists of data then this technique is recommended. Both react-window and react-virtualized are popular windowing libraries that provide several reusable components for displaying lists, grids, and tabular data.

What are hooks?

Hooks is a new feature (React 16.8) that lets you use state and other React features without writing a class.

import { useState } from 'react'
function Example() {
  // Declare a new state variable, which we'll call "count", also setCount is similar to setState
  const [count, setCount] = useState(0)
  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>

Do I need to rewrite all my class components with hooks?

No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.

Does Hook cover all use cases for classes?

Hooks doesn’t cover all use cases of classes but there is a plan to add them soon. Currently, there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.

What is Concurrent Rendering?

The Concurrent rendering makes React apps to be more responsive by rendering component trees without blocking the main UI thread. It allows React to interrupt a long-running render to handle a high-priority event. i.e, When you enabled concurrent Mode, React will keep an eye on other tasks that need to be done, and if there’s something with a higher priority it will pause what it is currently rendering and let the other task finish first.

What are the benefits of using typescript with reactjs?

  • It is possible to use the latest JavaScript features
  • Use of interfaces for complex type definitions
  • IDEs such as VS Code was made for TypeScript
  • Avoid bugs with the ease of readability and Validation

What are React Server components?

React Server Component is a way to write React component that gets rendered on the server-side with the purpose of improving React app performance. These components allow us to load components from the backend.

Note: React Server Components is still under development and not recommended for production yet.