Basic level – ReactJS Interview Questions

Q. What are the advantages of ReactJS?

Below are the advantages of ReactJS:

  1. Increases the application’s performance with Virtual DOM
  2. JSX makes code easy to read and write
  3. It renders both on the client and server-side
  4. Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library
  5. Easy to write UI Test cases and integration with tools such as JEST.

Q. How does React work?

React creates a virtual DOM. When state changes in a component it firstly runs a “diffing” algorithm, which identifies what has changed in the virtual DOM. The second step is reconciliation, where it updates the DOM with the results of the difference.Q. What is the use of refs?Entry

Refs provide a way to access DOM nodes or React elements created in the render method. They should be avoided in most cases, however, they can be useful when we need direct access to the DOM element or an instance of a component.

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();  }
  render() {
    return <div ref={this.myRef} />;  }
}

Q. What are props in React?

Props are inputs to a React component. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. i.e, They are data passed down from a parent component to a child component.

The primary purpose of props in React is to provide the following component functionality:

  1. Pass custom data to your React component.
  2. Trigger state changes.
  3. Use via this.props.reactProp inside component’s render() method.

For example, let us create an element with reactProp property,

 <Element reactProp = "1" />

This reactProp (or whatever you came up with) the name then becomes a property attached to React’s native props object which originally already exists on all components created using React library.

 props.reactProp;

Q. What is Context API in ReactJS?

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

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. Using context, we can avoid passing props through intermediate elements.

// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  // Assign a contextType to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

Q. What are React Hooks?

Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class.

With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.Q. What are the major features of ReactJS?Entry

The major features of ReactJS are as follows,

  • It uses VirtualDOM instead RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering
  • Follows Unidirectional data flow or data binding
  • Uses reusable/composable UI components to develop the view

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

what-is-jsx

Q. 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
babel

Q. What is the 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.

virtualdom

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.

real-dom

Q. Why use React instead of other frameworks, like Angular?

Dynamic Easy creation of dynamic applications: React makes it easier to create dynamic web applications because it provides less coding and provides more functionality, whereas, with JavaScript applications, code tends to get complex very quickly.
ImprovedImproved performance: React uses virtual DOM, which makes web applications perform faster. Virtual DOM compares its previous state and updates only those components in the real DOM, whose states have changed, rather than updating all the components — like conventional web applications.
ReusableReusable components: Components are the building blocks of any React application, and a single app usually consists of multiple components. These components have their own logic and controls, and they can be reused through the application, which, in turn, dramatically reduces the development time of an application.
Data flowUnidirectional data flow: React follows a unidirectional data flow. This means that when designing a React app, we often nest child components within parent components. And since the data flows in a single direction, it becomes easier to debug errors and know where the problem occurs in an application at the moment.
DedicatedDedicated tools for easy debugging: Facebook has released a chrome extension that we can use to debug React applications. This makes the process of debugging React to web applications faster and easier.

Q. What is the difference between the ES6 and ES5 standards?

These are the few instances where ES6 syntax has changed from ES5 syntax:

  • Components and Function
es5
  • exports vs export
exports.
  • require vs import
require

Q. How do you create a React app?

These are the steps for creating a React app:

  • Install NodeJS on the computer because we need npm to install the React library. Npm is the node package manager that contains many JavaScript libraries, including React.
node-js.
  • Install the create-react-app package using the command prompt or terminal.
create
  • Install a text editor of your choice, like VS Code or Sublime Text.
atom

Q. 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={lightItUp} />

Q. How do you create an event in React?

A React event can be created by doing the following:

Question 9

Q. 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.
  • The application is consistent regardless of the browser it is running in. Here, preventDefault is a synthetic event.

Q. Explain how lists work in React

  • We create lists in React as we do in regular JavaScript. Lists display data in an ordered format
  • The traversal of lists is done using the map() function
const

Q. Why is there a need for using keys in Lists?

Keys are very important in lists for the following reasons:

  • 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

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

Q. How do you create forms in React?

We create forms in React by doing the following: 

/class-name

The above code will yield an input field with the label Name and a submit button. It will also alert the user when the submit button is pressed. 

simple

Q. How do you write comments in React?

There are basically two ways in which we can write comments:

  • Single-line comments
return
  • Multi-line comments
multi-line

Q. What is an arrow function and how is it used in React?

  • An arrow function is a short way of writing a function to React.
  • It is unnecessary to bind ‘this’ inside the constructor when using an arrow function. This prevents bugs caused by the use of ‘this’ in React callbacks.
arrow

Q. How is React different from React Native?

ReactReact Native
Release20132015
PlatformWebMobile – Android, iOS
HTMLYesNo
CSSYesNo
PrerequisitesJavaScript, HTML, CSSReact.js

Q. How is React different from Angular?

AngularReact
AuthorGoogleFacebook
ArchitectureComplete MVCView layer of MVC
DOMReal DOMVirtual DOM
Data-BindingBi-directionalUni-directional
RenderingClient-SideServer-Side
PerformanceComparatively slowFaster due to Virtual DOM

In case you have any doubts about these Basic React interview questions and answers, please leave your questions in the comment section below.

ReactJS Interview Questions on Components

Here are some ReactJS Interview Questions on components.

Q. 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:

react-component
  • Functional Components: 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).
function Greeting(props) {  return <h1>Welcome to {props.name}</h1>;}
  • Class Components: 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.
class Greeting extends React.Component {  render() {    return <h1>Welcome to {this.props.name}</h1>;  }}

Q. 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>.
default-app

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

Q. How do you implement state in React?

state-holds

Q. How do you update the state of a component?

We can update the state of a component by using the built-in ‘setState()’ method:

class-app

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

Q. How do you pass props between components?

Introduction to Java Spring Framework 101

Learn AOP in Java, Spring MVC & Spring JDBCENROLL NOW

Introduction to Java Spring Framework 101

Q. What are the differences between state and props?

StateProps
UseHolds information about the componentsAllows to pass data from one component to other components as an argument
MutabilityIs mutableAre immutable
Read-OnlyCan be changedAre read-only
Child componentsChild components cannot access Child component can access 
Stateless componentsCannot have stateCan have props

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

Q. How can you embed two or more components into one?

We can embed two or more components into one using this method:

classapp-extends

Q. What are the differences between class and functional components?

Class ComponentsFunctional Components
StateCan hold or manage stateCannot hold or manage state
SimplicityComplex as compared to the stateless componentSimple and easy to understand
Lifecycle methodsCan work with all lifecycle methodsDoes not work with any lifecycle method
ReusabilityCan be reusedCannot be reused
  • Class components example:
class-components.
  • Functional components example:
functional-components

Q. Explain the lifecycle methods of components.

  • getInitialState(): This is executed before the creation of the component.
  • componentDidMount(): Is executed when the component gets rendered and placed on the DOM.
  • shouldComponentUpdate(): 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.

So far, if you have any doubts about the above React interview questions and answers, please ask your questions in the section below.

ReactJS Redux Interview Questions

Here are some ReactJS Interview Questions on the ReactJS Redux concept.

Q. What is Redux?

Redux is an open-source, JavaScript library used to manage the application state. React uses Redux to build the user interface. It is a predictable state container for JavaScript applications and is used for the entire application’s state management.

Q. What are the components of Redux?

  • Store: Holds the state of the application.
  • Action: The source information for the store.
  • Reducer: Specifies how the application’s state changes in response to actions sent to the store.
action

Q. What is the Flux?

  • Flux is the application architecture that Facebook uses for building web applications. It is a method of handling complex data inside a client-side application and manages how data flows in a React application.
  • There is a single source of data (the store) and triggering certain actions is the only way way to update them.The actions call the dispatcher, and then the store is triggered and updated with their own data accordingly.
  • When a dispatch has been triggered, and the store updates, it will emit a change event that the views can rerender accordingly.
action

Q. How is Redux different from Flux?

SNReduxFlux
1.Redux is an open-source JavaScript library used to manage application StateFlux is an architecture and not a framework or library
2.Store’s state is immutableStore’s state is mutable
3.Can only have a single-storeCan have multiple stores
4.Uses the concept of reducerUses the concept of the dispatcher

So far, if you have any doubts about these React interview questions and answers, please leave your questions in the section below.

ReactJS Router Questions

Here are some ReactJS Interview Questions on React Router concepts.

Q. What is React Router?

React Router is a routing library built on top of React, which is used to create routes in a React application. 

Q. Why do we need to React Router?

  • It maintains consistent structure and behavior and is used to develop single-page web applications. 
  • Enables multiple views in a single application by defining multiple routes in the React application.

Q. How is React routing different from conventional routing?

SNReact RoutingConventional routing
1.Single HTML pageEach view is a new HTML file
2.The user navigates multiple views in the same fileThe user navigates multiple files for each view
3.The page does not refresh since it is a single fileThe page refreshes every time user navigates
4.Improved performanceSlower performance

Q. How do you implement React routing?

We can implement routing in our React application using this method:

Considering we have the components AppAbout, and Contact in our application:

routing.

Hope you have no doubts about this ReactJS interview questions article, in case of any difficulty, please leave your problems in the section below.

ReactJS Styling Questions

Here are some ReactJS Interview Questions on Styling concept ReactJS.

Q. How do you style React components?

There are several ways in which we can style React components:

  • Inline Styling
class-simple
  • JavaScript Object
hello-simple
  • CSS Stylesheet
stylesheet

Q. 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.
button
Basic level – ReactJS Interview Questions
Show Buttons
Hide Buttons