Basic ReactJS interview questions and answers
1.
What is React?
Hide Answer
It is an open-source front-end JavaScript library most popular for single-
page web applications. It is helpful when interactive and complex UIs are
built for websites or mobile apps. React.js was released for use in 2015
and since then it has become one of the most trusted and used
technologies of recent time. It has built one of the largest developer
communities around itself.
2.
List some of React.js’ features.
Hide Answer
Important features of React.js include:
Instead of a real DOM, there is Virtual DOM
It completely renders the HTML files on the server into client HTML
pages, in other words, server-side rendering
In React.js, the data can be passed to the other parts of an
application only in one direction. In other words, there is a
unidirectional flow of data.
3.
What are the main advantages of React.js?
Hide Answer
The main advantages of React.js are:
It enhances the performance of the application
It can be used from the client-side as well as the server-side
The readability of code is higher in React.js because of JSX
It offers easy integration with frameworks such as Angular, Meteor,
etc.
It is easy to write UI test cases with React.js
If you can include some practical experience demonstrating the
advantages of React.js in this React.js interview question, you are likely to
impress the recruiter.
4.
What is JSX?
Hide Answer
JSX is the syntax extension for Javascript in React.js. With the help of JSX,
it is easy to define how the user interface should look. Additionally, with
JSX, the file containing the Javascript code can be used to write the HTML
structures as well.
5.
Describe an event in React.js?
Hide Answer
When a user presses a key, clicks the mouse, or performs any action on
the machine or when the machine itself triggers an action, these actions
are registered as events in React.js.
In React.js, we use camelCase to name events, instead of the
lowercase in HTML
In React.js, because of JSX, a function is passed as an event handler,
instead of the string in HTML
6.
How do Lists work in React.js?
Hide Answer
Lists in React.js are created similar to how they are created in regular
Javascript. With lists, data can be displayed in an orderly manner and is
useful in displaying menus on websites. For traversing lists, the map()
function is used. For example,
An array of numbers is taken by the map() function and their value
is multiplied by 5
var numbers = [2,4,6,8,10]
const multiplyNums = numbers.map((number => {
return (number*5);
});
console.log (multiplyNums);
Output: The output in Javascript will be logged in the console. The output
in the above case is [10, 20, 30, 40, 50]
7.
Why are keys used in React.js Lists?
Hide Answer
Keys are used in React.js Lists because:
Key helps in identifying what objects have been altered, moved, or
deleted from lists
With the help of keys, it is easier to determine which objects must
be re-rendered instead of all components being re-rendered all the
time.
React.js interview questions that ask about the use of a certain function or
component in React.js programming are common.
8.
Is HTML used in React?
Hide Answer
No, it uses an HTML-in JavaScript syntax called JSX (JavaScript and XML)
that converts HTML tags to React elements.
9.
What is the release date of React?
Hide Answer
March 2013
10.
Can you tell two downsides of React?
Hide Answer
It is difficult to integrate with an MVC framework like Rails. Also, users
need to have the knowledge about integrating user interface into MVC
framework.
11.
Can you outline the differences between Real DOM and Virtual DOM?
Hide Answer
Real DOM and Virtual DOM differ in following ways:
12.
Explain Flux Concept In React.
Hide Answer
It is a new kind of architecture used for client-side web applications.
Supports the concept of Unidirectional Data Flow.
13.
What is Redux in React?
Hide Answer
An open-source JavaScript library for front-end development and acts as a
container for JavaScript applications that is used for the applications state
management.
14.
Explain the ‘Store’ feature.
Hide Answer
It is a feature of Redux that allows the application to save the entire State
at one place. This allows you to get regular updates from the store
directly.
15.
What is a high order component in React?
Hide Answer
It is an advanced-level technique in React for reusing component logic.
16.
What is the Presentational segment?
Hide Answer
It is a component in React that just renders HTML and its only function is
presentation markup.
17.
Explain Props in ReactJS.
Hide Answer
Props in React mean properties. They act as a communication channel
from parent to child.
18.
What does super keyword mean in React?
Hide Answer
It is used to call super or parent class.
19.
What is yield catchphrase in JavaScript?
Hide Answer
It is used to delay and resume a generator work.
20.
List the two types of React component.
Hide Answer
Two types of React component are as follows:
Function component
Class component
21.
What is a synthetic event in ReactJS?
Hide Answer
It is an object that serves as a cross browser wrapper of the browser’s
native event.
22.
In Redux, what is an action?
Hide Answer
In Redux, an action is an object that contains information about an event
that has occurred in an application.
23.
What are stateless components?
Hide Answer
They are pure functions with no render method.
24.
What is React Router?
Hide Answer
It is a library for routing in React.
25.
Can you list some animation packages in React?
Hide Answer
Some animation packages are as follows:
React Motion
React Transition Group
React Spring
26.
Explain Jest.
Hide Answer
Jest is a JavaScript framework created by Facebook and is based on
Jasmine. Its feature-rich API helps to get results quickly.
27.
What exactly is the dispatcher?
Hide Answer
It is the central hub of data flow in a Flux application that acts as a
directory of callbacks.
28.
Explain the callback function.
Hide Answer
It is called when setState () has finished. A state can be updated in
response to prop changes or server response using setState() method The
main purpose is to prevent a component from re-rendering.
29.
Explain React State.
Hide Answer
It is an object which stores the component’s property values. Also, it
decides how the component renders and behaves.
30.
Can a State be updated in ReactJS?
Hide Answer
Yes, it can be updated directly or indirectly. To implement this one can use
either this. setState function or the updater function.
31.
What is the use of arrow function in React?
Hide Answer
Arrow function helps to create a compact function expression. Also they
help predict bugs when passed as a callback.
32.
List the lifecycle steps of React.
Hide Answer
The steps are as follows:
Initialization
State/Property updates
Destruction
33.
What are React portals?
Hide Answer
They are used to render an element outside its hierarchy using
CreatePortalmethod. Hence they allow developers to render outside the
hierarchy tree.
34.
Explain Context.
Hide Answer
React Context is a way to share data globally between React components.
It achieved this by passing props from parent to child and storing them in
a store. Thus child component(s) can use these props through the store.
35.
What is the use of Webpack?
Hide Answer
Webpack is a command line tool used to bundle different code files and
assets into single large file.. It has been built over Node.js and helps
minimize Javascript, CSS files, images, etc.
36.
What is Babel?
Hide Answer
It is an open-source JavaScript compiler that converts the latest JavaScript
versions to old ones.
37.
How are ReactJS and React Native different?
Hide Answer
Where ReactJS is a front end open-source JavaScript library for UIs, React
Native is an open-source mobile framework for platforms such as Android
and iOS.
Looking for remote developer job at US companies?
Work at Fortune 500 companies and fast-scaling startups from the comfort
of your home
Apply Now
Intermediate ReactJS interview questions and answers
1.
How do browsers read JSX files?
Hide Answer
As JSX is a combination of HTML and JavaScript, browsers are unable to
read it. And hence a transpiler is needed to convert JSX to Javascript so
that browsers can understand.
2.
What is the most advised way for naming components?
Hide Answer
By using reference rather than using displayName because it provides a
clear and concise name for the component.
3.
Mention one difference between Props and State.
Hide Answer
State is mutable while Props are immutable. This means that the state is
internal and managed by the component while props are external and
managed by anything that renders the component.
4.
What are pure components in ReactJS?
Hide Answer
A React component is considered to be pure if it produces the same
output when given the same set of state and props.
5.
What is ‘create-React-app’?
Hide Answer
It provides a development environment for creating React applications
using the JavaScript features as it creats a basic setup for the application
without requiring to configure everything. It is very helpful in building a
single-page application in React.
6.
What does ‘key’ do in React list?
Hide Answer
Keys are used for providing identity to list elements.
7.
Explain children's prop.
Hide Answer
Children prop are used to pass data from the parent component to the
children component.
8.
What are error boundaries?
Hide Answer
They help catch errors in child components, log the error and show
fallback UI.
9.
Why will you use empty tags <> </>?
Hide Answer
To declare fragments
10.
Tell us about strict mode.
Hide Answer
It highlights any potential problems in the application. It achieves this by
encapsulating a section of your application as a component. While it does
not show any visible element in the development mode (does not impact
the performance in the production mode as well), it does give warnings.
11.
What is React Fiber?
Hide Answer
It is the new reconciliation engine in React 16 and is used to enable
incremental rendering of virtual DOM.
12.
Can you differentiate between createElement and cloneElement?
Hide Answer
CreateElement creates a new element and returns it, while CloneElement
clones an existing element and returns a new element.
13.
Explain Lifting State Up in React.
Hide Answer
When multiple components need to share the same data, it is advised to
lift the shared state up to their parent. This means when two child
components share the same data from their parent, the state is lifted up
to the parent instead of the child components.
14.
Explain stateful components.
Hide Answer
If the behavior of the component holds dependency on the state of the
component, we term it as a stateful component.
15.
Tell me, how will you memoize a component in React?
Hide Answer
We can memoize a component in React using memoization libraries.
16.
How to use production mode in React?
Hide Answer
It can be used through Webpack's DefinePlugin method to set NODE_ENV
to production that takes out propType validation and extra warnings.
17.
Explain switching components.
Hide Answer
It is a component that renders one of many components. For this you need
to use object to map prop values to components. Basically, it allows the
user to turn the setting on or off.
18.
How will you update props in React?
Hide Answer
It is not possible as we can’t update props in ReactJS as they are read-
only.
19.
What do you understand by the term ‘Restructuring’ ?
Hide Answer
It is a process by which arrays are extracted.
20.
Can the values of props be updated?
Hide Answer
No, as props are immutable and top-down. This signifies that parent can
transmit prop values to a child but the latter can’t modify them.
21.
Can I use web components in React application?
Hide Answer
Yes, you can. While it is not used by many developers, it is required when
using third-party UI components.
Looking for remote developer job at US companies?
Work at Fortune 500 companies and fast-scaling startups from the comfort
of your home
Apply Now
Advanced ReactJS interview questions and answers
1.
Why is ‘prop-types’ library used?
Hide Answer
Allows for run time checkings for props and other similar objects.
2.
What are React hooks?
Hide Answer
Through React hooks, you don't have to write a class to use State and
some other React features
3.
What do you know about Controlled Components?
Hide Answer
They control the input elements which means the form’s data is managed
by the component's state. It takes its value through props and makes
alterations through callbacks.
4.
What are refs?
Hide Answer
They are an attribute of DOM elements. It is a function provided by React
to access these elements. You might want to use them in case when you
want to change the value of a child component without use of props.
5.
What can you do to spill the reducers?
Hide Answer
We can use event actions.
6.
How do you implement routing in ReactJS?
Hide Answer
React Router is available as an npm package, and can be added to your
application with a single line of code. Once installed, you can define your
routes in your application and use the component to link between them.
7.
Can you attach a JSX element to other JSX components?
Hide Answer
Yes, you can add JSX elements to other JSX components.
8.
With pure components, what is the issue of using render props?
Hide Answer
When creating a function inside the render method, it negates the
performance of the pure component.
9.
Explain the windowing technique.
Hide Answer
It is a technique that furnishes only a small number of rows at any given
time. This reduces the time to re-render not only the elements but also
the DOM nodes.
10.
How can you fetch data with React Hooks?
Hide Answer
We can use useEffect that fetches the data through axios from the API.
11.
What is Formik?
Hide Answer
It is a third-party library that aids in form programming and validation.
12.
Can you list some middleware choices for tackling asynchronous calls in
Redux?
Hide Answer
Redux Promise, Redux Saga Redux Thunk
13.
Can browsers understand JSX code? Explain.
Hide Answer
No. A transpiler is needed to convert JSX to JavaScript. Web browsers are
built to understand and read original JavaScript or JS objects. Since JSX is
not a regular JS object, web browsers are unable to read it. For web
browsers to read JSX, it must be made compatible by first converting it
into regular JS objects. This is achieved by using a transcompiler, such as
Babel. While this may seem like a simple ReactJS interview question,
knowing answers to such questions can be critical.
14.
What is one-way data flow in React?
Hide Answer
React uses unidirectional data flow which means you can transfer data
from parent to child and not the other way around.
15.
Explain Concurrent Rendering.
Hide Answer
Concurrent rendering is a feature of React that enables components to
render, update, and respond to user input simultaneously.
16.
Are concurrent mode and async mode different?
Hide Answer
They both are the same. Earlier concurrent mode was referred to as
"Async Mode".
17.
Can JavaScript urls be used in React 16.9?
Hide Answer
Yes, but it will give a warning in the console.
18.
Tell us about React Server components.
Hide Answer
It is a way to build applications that cover the benefits of both the server
and client side.
19.
What is prop drilling?
Hide Answer
It is a situation where the same data is sent at every interdependent level
until it reaches the final level.
20.
What is virtual DOM?
Hide Answer
DOM is the abbreviated version of the Document Object Model. The DOM
shows the logical tree structure for an HTML document. There is a node at
the end of each tree branch, with every tree node containing one or more
objects.
In ReactJS, a lighter version of real DOM is stored in the memory. It is
called the Virtual DOM. When there are any changes in specific objects,
instead of updating all objects, only those specific changes are updated in
the real DOM. This increases the efficiency and speed of the program. For
a ReactJS interview question like this, if you have the opportunity to
illustrate through a diagram, you must, as it shows the depth of your
understanding.
21.
Why do we use keys in Lists?
Hide Answer
The main reason why we use keys in lists are as follows
It is an identifier to find which items have changed, updated, or
deleted from lists
Find out which items need to be re-rendered
22.
Explain React forms?
Hide Answer
React forms allow users to interact with web applications. They help users
to enter the information when required. They contain buttons, text fields,
checkboxes, etc.
23.
What are the components in React?
Hide Answer
In a React application, they are independent and reusable bits of code that
can be processed separately. A single app may therefore contain multiple
components.
24.
Tell us about MobX.
Hide Answer
It is a simple, scalable, and battle-tested state management solution.It is
based on Reactive programming principles.
To use it, the following packages need to be installed
npm install mobx --save
npm install mobx-React --save
25.
How is an application created using ReactJS?
Hide Answer
We can use the following steps:
Install the ReactJS app on the machine as the ReactJS library
installation requires npm. This is because npm or node package
manager has several JavaScript libraries including ReactJS
Install Sublime text or any text editor similar to it.
Use the command prompt or terminal to install the create-ReactJS-
app package
Start the ReactJS app by going to the newly generated directory (my
app) and running npm start
Set up the component structure and define what components -
functional or classes - you will use for your application
Set up the back-end structure with Ruby-on-Rails API
Define the App component that will contain two child components -
MainContainer and Nav
Set up the Nav component
Set up the CreateCard component in the controlled form to then set
up the MainContainer component as a class component
Create a fetch request to the back-end using ReactJS’s component
lifecycle methods
Set up the ToDoCardContainer component to render all the
ToDoCard components
Render the cards with the ToDoCard component
Create lists using the addList callback function
Render lists for appropriate cards by rendering the ToDoList
component
Click on the list item to check it off once it is completed
Be sure to mention all points in detail for such a ReactJS interview
question.
26.
What is the use of eslint plugin for hooks?
Hide Answer
It enforces the Rules of Hooks. Precisely, it is a static code analysis tool for
finding out faulty patterns in JavaScript code.
27.
What are React Dev Tools?
Hide Answer
It lets you analyze the component hierarchy and includes component
props and state. You can find React Dev Tools both as a standalone app
and as a browser extension.
28.
Why would you do it if DevTools does not load in Chrome for local files?
Hide Answer
On opening a local HTML file in your browser, you must first open Chrome
Extensions and check Allow access to file URLs.
29.
Tell me some advantages of React over VueJS.
Hide Answer
React is better than Vue for following reasons
Easy to test
Suitable for mobile apps
More flexible
30.
What is render hijacking in React?
Hide Answer
It is the ability to control what one component will output from another
component. Here you wrap a component with a higher order component.
31.
How can you pass numbers to the React component?
Hide Answer
You can pass numbers to React components using curly braces({}) where
as strings in quotes
32.
Explain React memo function.
Hide Answer
Using PureComponent or shouldComponentUpdate you can restrict class
components from re-rendering when input properties are the same. You
can do the same with the React memo function.
33.
Tell me some benefits of React Router V4.
Hide Answer
Below are the main benefits of React Router V4 module,
Provides declarative routing using components
No need to manually set history
Reduced application size
34.
How uncaught errors behave in React 16?
Hide Answer
It results in unmounting of the entire React component tree.
35.
What are default props?
Hide Answer
It is a React component property to set default values for the props
argument. They are used for undefined props only and not for null props.
For example, let us take a button prop and create a color default prop
36.
What browser React applications support?
Hide Answer
It supports all popular browsers including Internet Explorer 9 and above.
However, it can support old browsers as well through polyfills.
37.
Is it necessary for keys to be globally unique?
Hide Answer
While you can use the same keys for two different arrays, they don't need
to be globally unique.
38.
What methods are invoked during error handling?
Hide Answer
static getDerivedStateFromError()
componentDidCatch()
39.
Do you know the use of the unmountComponentAtNode method?
Hide Answer
The unmountComponentAtNode method in React is used to unmount a
React component from the DOM and clean up its event handlers and
state. This method is often used when cleaning up the DOM after a React
component has been removed or replaced.
40.
On what condition, do component props defaults to true?
Hide Answer
When you pass no value for a prop.
For example, these two are equivalent,
41.
How will you build a search filter using React?
Hide Answer
You can build a search filter using following steps:
First declare React states for input values.
For entering the search term, create HTML input state
Now, on Change function update state
Add Array filter () to list of items with search term value
42.
How can you create a simple counter using React?
Hide Answer
A simple counter can be created using following steps:
First, create a React state that can store the count value.
Then declare JS functions to increment or decrement the value using
setState().
Finally add HTML buttons with onClick to JSX code.
43.
How can you display a list in React?
Hide Answer
A list can be created by:
First, declare a list of items using JS Array.
Now to access each item use Array.map()
Finally, return JSX code for each item
44.
How will you create an Image Slider using ReactJS?
Hide Answer
Create an array of objects that contain an id and image URL.
To enable pre/next functionality, we decrease or increase the index
value of the currently active image.
Finally update the active image index using the clicked option.
45.
What are the steps to add Font Awesome icons in React?
Hide Answer
Install font-awesome:
Import font-awesome in your index.js file:
Add Font Awesome classes in className:
46.
How will you use TypeScript in create-React-app applications?
Hide Answer
There is built-in support. You just have to pass --typescript option,
npx create-React-app my-app --typescript
47.
Can the statics object work with ES6 classes?
Hide Answer
No, it works only with React.createClass():
48.
How will you make Redux Form initialValues get updated from state?
Hide Answer
For this, we use enableReinitialize : true setting.
General React Interview Questions
1) What is React?
React is a declarative, efficient, flexible open source front-end JavaScript
library developed by Facebook in 2011. It follows the component-based
approach for building reusable UI components, especially for single page
application. It is used for developing interactive view layer of web and
mobile apps. It was created by Jordan Walke, a software engineer at
Facebook. It was initially deployed on Facebook's News Feed section in
2011 and later used in its products like WhatsApp & Instagram.
For More Information, Click here.
2) What are the features of React?
React framework gaining quick popularity as the best framework among
web developers. The main features of React are:
Backward Skip 10sPlay VideoForward Skip 10s
o JSX
o Components
o One-way Data Binding
o Virtual DOM
o Simplicity
o Performance
For More Information, Click here.
3) What are the most crucial advantages of using React?
Following is a list of the most crucial advantages of using React:
React is easy to learn and use
React comes with good availability of documentation, tutorials, and
training resources. It is easy for any developer to switch from JavaScript
background to React and easily understand and start creating web apps
using React. Anyone with little knowledge of JavaScript can start building
web applications using React.
React follows the MVC architecture.
React is the V (view part) in the MVC (Model-View-Controller) architecture
model and is referred to as "one of the JavaScript frameworks." It is not
fully featured but has many advantages of the open-source JavaScript
User Interface (UI) library, which helps execute the task in a better
manner.
Advertisement
React uses Virtual DOM to improve efficiency.
React uses virtual DOM to render the view. The virtual DOM is a virtual
representation of the real DOM. Each time the data changes in a react
app, a new virtual DOM gets created. Creating a virtual DOM is much
faster than rendering the UI inside the browser. Therefore, with the use of
virtual DOM, the efficiency of the app improves. That's why React provides
great efficiency.
Creating dynamic web applications is easy.
In React, creating a dynamic web application is much easier. It requires
less coding and gives more functionality. It uses JSX (JavaScript Extension),
which is a particular syntax letting HTML quotes and HTML tag syntax to
render particular subcomponents.
React is SEO-friendly.
React facilitates a developer to develop an engaging user interface that
can be easily navigated in various search engines. It also allows server-
side rendering, which is also helpful to boost the SEO of your app.
React allows reusable components.
Advertisement
React web applications are made up of multiple components where each
component has its logic and controls. These components provide a small,
reusable piece of HTML code as an output that can be reused wherever
you need them. The code reusability helps developers to make their apps
easier to develop and maintain. It also makes the nesting of the
components easy and allows developers to build complex applications of
simple building blocks. The reuse of components also increases the pace
of development.
Support of handy tools
React provides a lot of handy tools that can make the task of the
developers understandable and easier. Use these tools in Chrome and
Firefox dev extension, allowing us to inspect the React component
hierarchies in the virtual DOM. It also allows us to select the particular
components and examine and edit their current props and state.
Advertisement
React has a rich set of libraries.
React has a huge ecosystem of libraries and provides you the freedom to
choose the tools, libraries, and architecture for developing the best
application based on your requirement.
Scope for testing the codes
React web applications are easy to test. These applications provide a
scope where the developer can test and debug their codes with the help
of native tools.
For More Information, Click here.
4) What are the biggest limitations of React?
Following is the list of the biggest limitations of React:
o React is just a library. It is not a complete framework.
o It has a huge library which takes time to understand.
o It may be difficult for the new programmers to understand and code.
o React uses inline templating and JSX, which may be difficult and act
as a barrier. It also makes the coding complex.
5) What is JSX?
JSX stands for JavaScript XML. It is a React extension which allows writing
JavaScript code that looks similar to HTML. It makes HTML file easy to
understand. The JSX file makes the React application robust and boosts its
performance. JSX provides you to write XML-like syntax in the same file
where you write JavaScript code, and then preprocessor (i.e., transpilers
like Babel) transform these expressions into actual JavaScript code. Just
like XML/HTML, JSX tags have a tag name, attributes, and children.
Example
1. class App extends React.Component {
2. render() {
3. return(
4. <div>
5. <h1>Hello JavaTpoint</h1>
6. </div>
7. )
8. }
9. }
Advertisement
In the above example, text inside <h1> tag return as JavaScript function
to the render function. After compilation, the JSX expression becomes a
normal JavaScript function, as shown below.
1. React.createElement("h1", null, "Hello JavaTpoint");
For More Information, Click here.
6) Why can't browsers read JSX?
Browsers cannot read JSX directly because they can only understand
JavaScript objects, and JSX is not a regular JavaScript object. Thus, we
need to transform the JSX file into a JavaScript object using transpilers like
Babel and then pass it to the browser.
7) Why we use JSX?
o It is faster than regular JavaScript because it performs optimization
while translating the code to JavaScript.
o Instead of separating technologies by putting markup and logic in
separate files, React uses components that contain both.
o t is type-safe, and most of the errors can be found at compilation
time.
o It makes easier to create templates.
8) What do you understand by Virtual DOM?
A Virtual DOM is a lightweight JavaScript object which is an in-memory
representation of real DOM. It is an intermediary step between the render
function being called and the displaying of elements on the screen. It is
similar to a node tree which lists the elements, their attributes, and
content as objects and their properties. The render function creates a
node tree of the React components and then updates this node tree in
response to the mutations in the data model caused by various actions
done by the user or by the system.
9) Explain the working of Virtual DOM.
Virtual DOM works in three steps:
1. Whenever any data changes in the React App, the entire UI is re-
rendered in Virtual DOM representation.
2. Now, the difference between the previous DOM representation and the
new DOM is calculated.
3. Once the calculations are completed, the real DOM updated with only
those things which are changed.
10) How is React different from Angular?
The React is different from Angular in the following ways.
Angular React
Author Google Facebook Commu
Developer Misko Hevery Jordan Walke
Initial Release October 2010 March 2013
Language JavaScript, HTML JSX
Type Open Source MVC Framework Open Source JS F
Rendering Client-Side Server-Side
Data-Binding Bi-directional Uni-directional
DOM Regular DOM Virtual DOM
Testing Unit and Integration Testing Unit Testing
App Architecture MVC Flux
Performance Slow Fast, due to virtu
For More Information, Click here.
11) How React's ES6 syntax is different from ES5 syntax?
The React's ES6 syntax has changed from ES5 syntax in the following
aspects.
require vs. Import
1. // ES5
2. var React = require('react');
3.
4. // ES6
5. import React from 'react';
exports vs. export
1. // ES5
2. module.exports = Component;
3.
4. // ES6
5. export default Component;
component and function
1. // ES5
2. var MyComponent = React.createClass({
3. render: function() {
4. return(
5. <h3>Hello JavaTpoint</h3>
6. );
7. }
8. });
9.
10. // ES6
11. class MyComponent extends React.Component {
12. render() {
13. return(
14. <h3>Hello Javatpoint</h3>
15. );
16. }
17. }
props
1. // ES5
2. var App = React.createClass({
3. propTypes: { name: React.PropTypes.string },
4. render: function() {
5. return(
6. <h3>Hello, {this.props.name}!</h3>
7. );
8. }
9. });
10.
11. // ES6
12. class App extends React.Component {
13. render() {
14. return(
15. <h3>Hello, {this.props.name}!</h3>
16. );
17. }
18. }
state
1. var App = React.createClass({
2. getInitialState: function() {
3. return { name: 'world' };
4. },
5. render: function() {
6. return(
7. <h3>Hello, {this.state.name}!</h3>
8. );
9. }
10. });
11.
12. // ES6
13. class App extends React.Component {
14. constructor() {
15. super();
16. this.state = { name: 'world' };
17. }
18. render() {
19. return(
20. <h3>Hello, {this.state.name}!</h3>
21. );
22. }
23. }
12) What is the difference between ReactJS and React Native?
The main differences between ReactJS and React Native are given below.
SN ReactJS React Native
1. Initial release in 2013. Initial release in 2
It is used for developing web It is used for dev
2.
applications. applications.
It is not platform
It can be executed on all
3. takes more effort
platforms.
executed on all p
It uses a JavaScript library and It comes with bui
4.
CSS for animations. libraries.
It has built-in Nav
It uses React-router for
5. for navigating mo
navigating web pages.
applications.
6. It uses HTML tags. It does not use H
In this, Native us
In this, the Virtual DOM renders
7. render code for m
the browser code.
applications.
For More Information, Click here.
13) What is the difference between Real DOM and Virtual DOM?
The following table specifies the key differences between the Real DOM
and Virtual DOM:
The real DOM creates a new DOM if the element updates.
Real DOM Virtual DOM
The real DOM updates slower. The virtual DOM up
The virtual DOM ca
The real DOM can directly update HTML.
update HTML.
The virtual DOM updates the JSX if the element updates.
In virtual DOM, DO
In real DOM, DOM manipulation is very expensive.
is very easy.
There is no memor
There is a lot of memory wastage in The real DOM.
the virtual DOM.
React Component Interview Questions
14) What do you understand from "In React, everything is a component."
In React, components are the building blocks of React applications. These
components divide the entire React application's UI into small,
independent, and reusable pieces of code. React renders each of these
components independently without affecting the rest of the application UI.
Hence, we can say that, in React, everything is a component.
15) Explain the purpose of render() in React.
It is mandatory for each React component to have a render() function.
Render function is used to return the HTML which you want to display in a
component. If you need to rendered more than one HTML element, you
need to grouped together inside single enclosing tag (parent tag) such as
<div>, <form>, <group> etc. This function returns the same result each
time it is invoked.
Example: If you need to display a heading, you can do this as below.
1. import React from 'react'
2.
3. class App extends React.Component {
4. render (){
5. return (
6. <h1>Hello World</h1>
7. )
8. }
9. }
10. export default App
Points to Note:
o Each render() function contains a return statement.
o The return statement can have only one parent HTML tag.
16) How can you embed two or more components into one?
You can embed two or more components into the following way:
1. import React from 'react'
2.
3. class App extends React.Component {
4. render (){
5. return (
6. <h1>Hello World</h1>
7. )
8. }
9. }
10.
11. class Example extends React.Component {
12. render (){
13. return (
14. <h1>Hello JavaTpoint</h1>
15. )
16. }
17. }
18. export default App
17) What is Props?
Props stand for "Properties" in React. They are read-only inputs to
components. Props are an object which stores the value of attributes of a
tag and work similar to the HTML attributes. It gives a way to pass data
from the parent to the child components throughout the application.
It is similar to function arguments and passed to the component in the
same way as arguments passed in a function.
Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props.
These attributes are available in the component as this.props and can be
used to render dynamic data in our render method.
For More Information, Click here.
18) What is a State in React?
The State is an updatable structure which holds the data and information
about the component. It may be changed over the lifetime of the
component in response to user action or system event. It is the heart of
the react component which determines the behavior of the component
and how it will render. It must be kept as simple as possible.
Let's create a "User" component with "message state."
1. import React from 'react'
2.
3. class User extends React.Component {
4. constructor(props) {
5. super(props)
6.
7. this.state = {
8. message: 'Welcome to JavaTpoint'
9. }
10. }
11.
12. render() {
13. return (
14. <div>
15. <h1>{this.state.message}</h1>
16. </div>
17. )
18. }
19. }
20. export default User
For More Information, Click here.
19) Differentiate between States and Props.
The major differences between States and Props are given below.
SN Props State
State changes ca
1. Props are read-only.
asynchronous.
2. Props are immutable. State is mutable.
Props allow you to pass data
State holds inform
3. from one component to other
the components.
components as an argument.
Props can be accessed by the State cannot be a
4.
child component. child components
States can be use
Props are used to communicate
5. rendering dynam
between components.
with the compon
The stateless component can The stateless com
6.
have Props. cannot have Stat
Props make components The State cannot
7.
reusable. components reus
Props are external and The State is inter
8. controlled by whatever renders controlled by the
the component. itself.
For More Information, Click here.
20) How can you update the State of a component?
We can update the State of a component using this.setState() method.
This method does not always replace the State immediately. Instead, it
only adds changes to the original State. It is a primary method which is
used to update the user interface(UI) in response to event handlers and
server responses.
Example
1. import React, { Component } from 'react';
2. import PropTypes from 'prop-types';
3.
4. class App extends React.Component {
5. constructor() {
6. super();
7. this.state = {
8. msg: "Welcome to JavaTpoint"
9. };
10. this.updateSetState = this.updateSetState.bind(this);
11. }
12. updateSetState() {
13. this.setState({
14. msg:"Its a best ReactJS tutorial"
15. });
16. }
17. render() {
18. return (
19. <div>
20. <h1>{this.state.msg}</h1>
21. <button onClick = {this.updateSetState}>SET STATE
</button>
22. </div>
23. );
24. }
25. }
26. export default App;
For More Information, Click here.
21) Differentiate between stateless and stateful components.
The difference between stateless and stateful components are:
SN Stateless Component Stateful Compo
The stateless components do The stateful com
1.
not hold or manage state. hold or manage s
It does not contain the It can contain the
2. knowledge of past, current, and past, current, and
possible future state changes. future changes in
It is also known as a functional It is also known a
3.
component. component.
It is simple and easy to It is complex as c
4.
understand. the stateless com
It does not work with any It can work with a
5.
lifecycle method of React. method of React.
The stateless components The stateful com
6.
cannot be reused. reused.
22) What is arrow function in React? How is it used?
The Arrow function is the new feature of the ES6 standard. If you need to
use arrow functions, it is not necessary to bind any event to 'this.' Here,
the scope of 'this' is global and not limited to any calling function. So If
you are using Arrow Function, there is no need to bind 'this' inside the
constructor. It is also called 'fat arrow '(=>) functions.
1. //General way
2. render() {
3. return(
4. <MyInput onChange={this.handleChange.bind(this) } />
5. );
6. }
7. //With Arrow Function
8. render() {
9. return(
10. <MyInput onChange={ (e) => this.handleOnChange(e)
} />
11. );
12. }
23) What is an event in React?
An event is an action which triggers as a result of the user action or
system generated event like a mouse click, loading of a web page,
pressing a key, window resizes, etc. In React, the event handling system is
very similar to handling events in DOM elements. The React event
handling system is known as Synthetic Event, which is a cross-browser
wrapper of the browser's native event.
Handling events with React have some syntactical differences, which are:
o React events are named as camelCase instead of lowercase.
o With JSX, a function is passed as the event handler instead of a
string.
For More Information, Click here.
24) How do you create an event in React?
We can create an event as follows.
1. class Display extends React.Component({
2. show(msgEvent) {
3. // code
4. },
5. render() {
6. // Here, we render the div with an onClick prop
7. return (
8. <div onClick={this.show}>Click Me</div>
9. );
10. }
11. });
Example
1. import React, { Component } from 'react';
2. class App extends React.Component {
3. constructor(props) {
4. super(props);
5. this.state = {
6. companyName: ''
7. };
8. }
9. changeText(event) {
10. this.setState({
11. companyName: event.target.value
12. });
13. }
14. render() {
15. return (
16. <div>
17. <h2>Simple Event Example</h2>
18. <label htmlFor="name">Enter company name: </
label>
19. <input type="text" id="companyName" onChange=
{this.changeText.bind(this)}/>
20. <h4>You entered: { this.state.companyName }</
h4>
21. </div>
22. );
23. }
24. }
25. export default App;
For More Information, Click here.
25) What are synthetic events in React?
A synthetic event is an object which acts as a cross-browser wrapper
around the browser's native event. It combines the behavior of different
browser's native event into one API, including stopPropagation() and
preventDefault().
In the given example, e is a Synthetic event.
1. function ActionLink() {
2. function handleClick(e) {
3. e.preventDefault();
4. console.log('You had clicked a Link.');
5. }
6. return (
7. <a href="#" onClick={handleClick}>
8. Click_Me
9. </a>
10. );
11. }
26) what is the difference between controlled and uncontrolled
components?
The difference between controlled and uncontrolled components are:
SN Controlled Uncontrolled
It does not maintain its internal
1. It maintains its in
state.
Here, data is controlled by the Here, data is con
2.
parent component. DOM itself.
It accepts its current value as a It uses a ref for th
3.
prop. values.
It does not allow
4. It allows validation control.
control.
It has better control over the It has limited con
5.
form elements and data. form elements an
For More Information, Click here.
27) Explain the Lists in React.
Lists are used to display data in an ordered format. In React, Lists can be
created in a similar way as we create it in JavaScript. We can traverse the
elements of the list using the map() function.
Example
1. import React from 'react';
2. import ReactDOM from 'react-dom';
3.
4. function NameList(props) {
5. const myLists = props.myLists;
6. const listItems = myLists.map((myList) =>
7. <li>{myList}</li>
8. );
9. return (
10. <div>
11. <h2>Rendering Lists inside component</h2>
12. <ul>{listItems}</ul>
13. </div>
14. );
15. }
16. const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa'];
17. ReactDOM.render(
18. <NameList myLists={myLists} />,
19. document.getElementById('app')
20. );
21. export default App;
For More Information, Click here.
28) What is the significance of keys in React?
A key is a unique identifier. In React, it is used to identify which items
have changed, updated, or deleted from the Lists. It is useful when we
dynamically created components or when the users alter the lists. It also
helps to determine which components in a collection needs to be re-
rendered instead of re-rendering the entire set of components every time.
It increases application performance.
For More Information, Click here.
29) How are forms created in React?
Forms allow the users to interact with the application as well as gather
information from the users. Forms can perform many tasks such as user
authentication, adding user, searching, filtering, etc. A form can contain
text fields, buttons, checkbox, radio button, etc.
React offers a stateful, reactive approach to build a form. The forms in
React are similar to HTML forms. But in React, the state property of the
component is only updated via setState(), and a JavaScript function
handles their submission. This function has full access to the data which is
entered by the user into a form.
1. import React, { Component } from 'react';
2.
3. class App extends React.Component {
4. constructor(props) {
5. super(props);
6. this.state = {value: ''};
7. this.handleChange = this.handleChange.bind(this);
8. this.handleSubmit = this.handleSubmit.bind(this);
9. }
10. handleChange(event) {
11. this.setState({value: event.target.value});
12. }
13. handleSubmit(event) {
14. alert('You have submitted the input successfully: ' + this.s
tate.value);
15. event.preventDefault();
16. }
17. render() {
18. return (
19. <form onSubmit={this.handleSubmit}>
20. <h1>Controlled Form Example</h1>
21. <label>
22. Name:
23. <input type="text" value={this.state.value} onCha
nge={this.handleChange} />
24. </label>
25. <input type="submit" value="Submit" />
26. </form>
27. );
28. }
29. }
30. export default App;
For More Information, Click here.
30) What are the different phases of React component's lifecycle?
The different phases of React component's lifecycle are:
Initial Phase: It is the birth phase of the React lifecycle when the
component starts its journey on a way to the DOM. In this phase, a
component contains the default Props and initial State. These default
properties are done in the constructor of a component.
Mounting Phase: In this phase, the instance of a component is created
and added into the DOM.
Updating Phase: It is the next phase of the React lifecycle. In this phase,
we get new Props and change State. This phase can potentially update
and re-render only when a prop or state change occurs. The main aim of
this phase is to ensure that the component is displaying the latest version
of itself. This phase repeats again and again.
Unmounting Phase: It is the final phase of the React lifecycle, where the
component instance is destroyed and unmounted(removed) from the
DOM.
For More Information, Click here.
31) Explain the lifecycle methods of React components in detail.
The important React lifecycle methods are:
o getInitialState(): It is used to specify the default value of
this.state. It is executed before the creation of the component.
o componentWillMount(): It is executed before a component gets
rendered into the DOM.
o componentDidMount(): It is executed when the component gets
rendered and placed on the DOM. Now, you can do any DOM
querying operations.
o componentWillReceiveProps(): It is invoked when a component
receives new props from the parent class and before another render
is called. If you want to update the State in response to prop
changes, you should compare this.props and nextProps to perform
State transition by using this.setState() method.
o shouldComponentUpdate(): It is invoked when a component
decides any changes/updation to the DOM and returns true or false
value based on certain conditions. If this method returns true, the
component will update. Otherwise, the component will skip the
updating.
o componentWillUpdate(): It is invoked before rendering takes
place in the DOM. Here, you can't change the component State by
invoking this.setState() method. It will not be called, if
shouldComponentUpdate() returns false.
o componentDidUpdate(): It is invoked immediately after rendering
takes place. In this method, you can put any code inside this which
you want to execute once the updating occurs.
o componentWillUnmount(): It is invoked immediately before a
component is destroyed and unmounted permanently. It is used to
clear up the memory spaces such as invalidating timers, event
listener, canceling network requests, or cleaning up DOM elements.
If a component instance is unmounted, you cannot mount it again.
For More Information, Click here.
32) What are Pure Components?
Pure components introduced in React 15.3 version. The React.Component
and React.PureComponent differ in the shouldComponentUpdate() React
lifecycle method. This method decides the re-rendering of the component
by returning a boolean value (true or false). In React.Component,
shouldComponentUpdate() method returns true by default. But in
React.PureComponent, it compares the changes in state or props to re-
render the component. The pure component enhances the simplicity of
the code and performance of the application.
33) What are Higher Order Components(HOC)?
In React, Higher Order Component is an advanced technique for reusing
component logic. It is a function that takes a component and returns a
new component. In other words, it is a function which accepts another
function as an argument. According to the official website, it is not the
feature(part) in React API, but a pattern that emerges from React's
compositional nature.
For More Information, Click here.
34) What can you do with HOC?
You can do many tasks with HOC, some of them are given below:
o Code Reusability
o Props manipulation
o State manipulation
o Render highjacking
35) What is the difference between Element and Component?
The main differences between Elements and Components are:
SN Element Component
A component is t
An element is a plain JavaScript
building block of
object which describes the
1. application. It is a
component state and DOM
function which ac
node, and its desired properties.
and returns a Rea
It only holds information about
It can contain sta
the component type, its
2. and has access to
properties, and any child
lifecycle methods
elements inside it.
3. It is immutable. It is mutable.
We cannot apply any methods We can apply me
4.
on elements. components.
5. Example: Example:
const element = function Button (
React.createElement( return React.crea
'div', 'div',
{id: 'login-btn'}, {id: 'login-btn', o
'Login' onLogin},
) 'Login'
)
}
36) How to write comments in React?
In React, we can write comments as we write comments in JavaScript. It
can be in two ways:
1. Single Line Comments: We can write comments as /* Block
Comments */ with curly braces:
1. {/* Single Line comment */}
2. Multiline Comments: If we want to comment more that one line, we
can do this as
1. { /*
2. Multi
3. line
4. comment
5. */ }
37) Why is it necessary to start component names with a capital letter?
In React, it is necessary to start component names with a capital letter. If
we start the component name with lower case, it will throw an error as an
unrecognized tag. It is because, in JSX, lower case tag names are
considered as HTML tags.
38) What are fragments?
In was introduced in React 16.2 version. In React, Fragments are used for
components to return multiple elements. It allows you to group a list of
multiple children without adding an extra node to the DOM.
Example
1. render() {
2. return (
3. <React.Fragment>
4. <ChildA />
5. <ChildB />
6. <ChildC />
7. </React.Fragment>
8. )
9. }
There is also a shorthand syntax exists for declaring Fragments, but it's
not supported in many tools:
1. render() {
2. return (
3. <>
4. <ChildA />
5. <ChildB />
6. <ChildC />
7. </>
8. )
9. }
For More Information, Click here.
39) Why are fragments better than container divs?
o Fragments are faster and consume less memory because it did not
create an extra DOM node.
o Some CSS styling like CSS Grid and Flexbox have a special parent-
child relationship and add <div> tags in the middle, which makes it
hard to keep the desired layout.
o The DOM Inspector is less cluttered.
40) How to apply validation on props in React?
Props validation is a tool which helps the developers to avoid future bugs
and problems. It makes your code more readable. React components used
special property PropTypes that help you to catch bugs by validating data
types of values passed through props, although it is not necessary to
define components with propTypes.
We can apply validation on props using App.propTypes in React
component. When some of the props are passed with an invalid type, you
will get the warnings on JavaScript console. After specifying the validation
patterns, you need to set the App.defaultProps.
1. class App extends React.Component {
2. render() {}
3. }
4. Component.propTypes = { /*Definition */};
For More Information, Click here.
41) What is create-react-app?
Create React App is a tool introduced by Facebook to build React
applications. It provides you to create single-page React applications. The
create-react-app are preconfigured, which saves you from time-consuming
setup and configuration like Webpack or Babel. You need to run a single
command to start the React project, which is given below.
1. $ npx create-react-app my-app
This command includes everything which we need to build a React app.
Some of them are given below:
o It includes React, JSX, ES6, and Flow syntax support.
o It includes Autoprefixed CSS, so you don't need -webkit- or other
prefixes.
o It includes a fast, interactive unit test runner with built-in support for
coverage reporting.
o It includes a live development server that warns about common
mistakes.
o It includes a build script to bundle JS, CSS, and images for
production, with hashes and source maps.
For More Information, Click here.
Advertisement
42) How can you create a component in React?
There are two possible ways to create a component in React:
Function Components: This is the simplest way to create a component
in React. These are the pure JavaScript functions that accept props object
as the first parameter and return React elements:
1. function Greeting({ message }) {
2. return <h1>{`Hello, ${message}`}</h1>
3. }
Class Components: The class components method facilitates you to use
ES6 class to define a component. The above function component can be
written as:
1. class Greeting extends React.Component {
2. render() {
3. return <h1>{`Hello, ${this.props.message}`}</h1>
4. }
5. }
43) When do we prefer to use a class component over a function
component?
If a component needs state or lifecycle methods, we should use the class
component; otherwise, use the function component. However, after React
16.8, with the addition of Hooks, you could use state, lifecycle methods,
and other features that were only available in the class component right in
your function component.
44) Is it possible for a web browser to read JSX directly?
Web browsers can't read JSX directly. This is because the web browsers
are built to read the regular JS objects only, and JSX is not a regular
JavaScript object.
If you want a web browser to read a JSX file, you must transform the files
into a regular JavaScript object. For this purpose, Babel is used.
45) What do you understand by the state in React?
In react, the state of a component is an object that holds some
information that may change over the component's lifetime. It would be
best to try to make your state as simple as possible and minimize the
number of stateful components.
Let's see how to create a user component with message state:
1. class User extends React.Component {
2. constructor(props) {
3. super(props)
4. this.state = {
5. message: 'Welcome to React world'
6. }
7. }
8. render() {
9. return (
10. <div>
11. <h1>{this.state.message}</h1>
12. </div>
13. )
14. }
15. }
The state is very similar to props, but it is private and fully controlled by
the component. i.e., It is not accessible to any other component till the
owner component decides to pass it.
46) What are the main changes that appear in React's ES6 syntax
compared to ES5 syntax?/How different is React's ES6 syntax compared to
ES5?
Following are the most visible syntax we can see while comparing ES6 and
ES5:
require vs import
Syntax in ES5:
1. var React = require('react');
Syntax in ES6:
1. import React from 'react';
export vs exports
Syntax in ES5:
1. module.exports = Component;
Syntax in ES6:
1. export default Component;
component and function
Syntax in ES5:
1. var MyComponent = React.createClass({
2. render: function() {
3. return
4. <h3>Hello JavaTpoint!</h3>
5. ;
6. }
7. });
Syntax in ES6:
1. class MyComponent extends React.Component {
2. render() {
3. return
4. <h3>Hello JavaTpoint!</h3>
5. ;
6. }
7. }
props
Syntax in ES5:
1. var App = React.createClass({
2. propTypes: { name: React.PropTypes.string },
3. render: function() {
4. return
5. <h3>Hello, {this.props.name}!</h3>
6. ;
7. }
8. });
Syntax in ES6:
1. class App extends React.Component {
2. render() {
3. return
4. <h3>Hello, {this.props.name}!</h3>
5. ;
6. }
7. }
state
Syntax in ES5:
1. var App = React.createClass({
2. getInitialState: function() {
3. return { name: 'world' };
4. },
5. render: function() {
6. return
7. <h3>Hello, {this.state.name}!</h3>
8. ;
9. }
10. });
Syntax in ES6:
1. class App extends React.Component {
2. constructor() {
3. super();
4. this.state = { name: 'world' };
5. }
6. render() {
7. return
8. <h3>Hello, {this.state.name}!</h3>
9. ;
10. }
11. }
47) What do you understand by props in React?
In React, the props are inputs to components. They are single values or
objects containing a set of values passed to components on creation using
a naming convention similar to HTML-tag attributes. They are data passed
down from a parent component to a child component.
The main purpose of props in React is to provide the following
component functionality:
o Pass custom data to your component.
o Trigger state changes.
o Use via this.props.reactProp inside component's render() method.
For example, let us create an element with reactProp property:
1. <Element reactProp={'1'} />
This reactProp name becomes a property attached to React's native props
object, which already exists on all React library components.
1. props.reactProp
React Refs Interview Questions
48) What do you understand by refs in React?
Refs is the shorthand used for references in React. It is an attribute which
helps to store a reference to particular DOM nodes or React elements. It
provides a way to access React DOM nodes or React elements and how to
interact with it. It is used when we want to change the value of a child
component, without making the use of props.
For More Information, Click here.
49) How to create refs?
Refs can be created by using React.createRef() and attached to React
elements via the ref attribute. It is commonly assigned to an instance
property when a component is created, and then can be referenced
throughout the component.
1. class MyComponent extends React.Component {
2. constructor(props) {
3. super(props);
4. this.callRef = React.createRef();
5. }
6. render() {
7. return <div ref={this.callRef} />;
8. }
9. }
50) What are Forward Refs?
Ref forwarding is a feature which is used for passing a ref through a
component to one of its child components. It can be performed by making
use of the React.forwardRef() method. It is particularly useful with higher-
order components and specially used in reusable component libraries.
Example
1. import React, { Component } from 'react';
2. import { render } from 'react-dom';
3.
4. const TextInput = React.forwardRef((props, ref) => (
5. <input type="text" placeholder="Hello World" ref={ref} />
6. ));
7.
8. const inputRef = React.createRef();
9.
10. class CustomTextInput extends React.Component {
11. handleSubmit = e => {
12. e.preventDefault();
13. console.log(inputRef.current.value);
14. };
15. render() {
16. return (
17. <div>
18. <form onSubmit={e => this.handleSubmit(e)}>
19. <TextInput ref={inputRef} />
20. <button>Submit</button>
21. </form>
22. </div>
23. );
24. }
25. }
26. export default App;
For More Information, Click here.
51) Which is the preferred option callback refs or findDOMNode()?
The preferred option is to use callback refs over findDOMNode() API.
Because callback refs give better control when the refs are set and unset
whereas findDOMNode() prevents certain improvements in React in the
future.
1. class MyComponent extends Component {
2. componentDidMount() {
3. findDOMNode(this).scrollIntoView()
4. }
5. render() {
6. return <div />
7. }
8. }
The recommended approach is:
1. class MyComponent extends Component {
2. componentDidMount() {
3. this.node.scrollIntoView()
4. }
5. render() {
6. return <div ref={node => this.node = node} />
7. }
8. }
9. class MyComponent extends Component {
10. componentDidMount() {
11. this.node.scrollIntoView()
12. }
13. render() {
14. return <div ref={node => this.node = node} />
15. }
16. }
52) What is the use of Refs?
The Ref in React is used in the following cases:
o It is used to return a reference to the element.
o It is used when we need DOM measurements such as managing
focus, text selection, or media playback.
o It is used in triggering imperative animations.
o It is used when integrating with third-party DOM libraries.
o It can also use as in callbacks.
For More Information, Click here.
React Router Interview Questions
53) What is React Router?
React Router is a standard routing library system built on top of the React.
It is used to create Routing in the React application using React Router
Package. It helps you to define multiple routes in the app. It provides the
synchronous URL on the browser with data that will be displayed on the
web page. It maintains the standard structure and behavior of the
application and mainly used for developing single page web applications.
For More Information, Click here.
54) Why do we need a Router in React?
React Router plays an important role to display multiple views in a single
page application. It is used to define multiple routes in the app. When a
user types a specific URL into the browser, and if this URL path matches
any 'route' inside the router file, the user will be redirected to that
particular Route. So, we need to add a Router library to the React app,
which allows creating multiple routes with each leading to us a unique
view.
1. <switch>
2. <h1>React Router Example</h1>
3. <Route path="/" component={Home} />
4. <Route path="/about" component={About} />
5. <Route path="/contact" component={Contact} />
6. </switch>
55) List down the advantages of React Router.
The important advantages of React Router are given below:
o In this, it is not necessary to set the browser history manually.
o Link uses to navigate the internal links in the application. It is similar
to the anchor tag.
o It uses Switch feature for rendering.
o The Router needs only a Single Child element.
o In this, every component is specified in <Route>.
o The packages are split into three packages, which are Web, Native,
and Core. It supports the compact size of the React application.
56) How is React Router different from Conventional Routing?
The difference between React Routing and Conventional Routing are:
SN Conventional Routing React Routing
In Conventional Routing, each In React Routing,
1.
view contains a new file. single HTML page
The HTTP request is sent to a
Only the History
2. server to receive the
<BrowserRouter>
corresponding HTML page.
In this, the user navigates In this, the user i
3. across different pages for each navigating across
view. pages, but its an
57) Why you get "Router may have only one child element" warning?
It is because you have not to wrap your Route's in a <Switch> block or
<div> block which renders a route exclusively.
Example
1. render((
2. <Router>
3. <Route {/* ... */} />
4. <Route {/* ... */} />
5. </Router>
6. )
should be
1. render(
2. <Router>
3. <Switch>
4. <Route {/* ... */} />
5. <Route {/* ... */} />
6. </Switch>
7. </Router>
8. )
58) Why switch keyword used in React Router v4?
The 'switch' keyword is used to display only a single Route to rendered
amongst the several defined Routes. The <Switch> component is used to
render components only when the path will be matched. Otherwise, it
returns to the not found component.
React Styling Interview Questions
59) How to use styles in React?
We can use style attribute for styling in React applications, which adds
dynamically-computed styles at render time. It accepts a JavaScript object
in camelCased properties rather than a CSS string. The style attribute is
consistent with accessing the properties on DOM nodes in JavaScript.
Example
1. const divStyle = {
2. color: 'blue',
3. backgroundImage: 'url(' + imgUrl + ')'
4. };
5.
6. function HelloWorldComponent() {
7. return <div style={divStyle}>Hello World!</div>
8. }
60) How many ways can we style the React Component?
We can style React Component in mainly four ways, which are given
below:
o Inline Styling
o CSS Stylesheet
o CSS Module
o Styled Components
For More Information, Click here.
61) Explain CSS Module styling in React.
CSS Module is a CSS file where all class names and animation names are
scoped locally by default. It is available only for the component which
imports it, and without your permission, it cannot be applied to any other
Components. You can create CSS Module file with the .module.css
extension.
For More Information, Click here.
62) What are Styled Components?
Styled-Components is a library for React. It is the successor of CSS
Modules. It uses enhance CSS for styling React component systems in
your application, which is written with a mixture of JavaScript and CSS. It
is scoped to a single component and cannot leak to any other element in
the page.
The styled-components provides:
o Automatic critical CSS
o No class name bugs
o Easier deletion of CSS
o Simple dynamic styling
o Painless maintenance
For More Information, Click here.
63) What are hooks in React?
Hooks are the new feature introduced in React 16.8 version that facilitates
us to use state and other React features without writing a class.
See the following example of useState hook:
1. import { useState } from 'react';
2. function Example() {
3. // Declare a new state variable, which we'll call "count"
4. const [count, setCount] = useState(0);
5. return (
6. <div>
7. <p>You clicked {count} times</p>
8. <button onClick={() => setCount(count + 1)}>
9. Click on this button
10. </button>
11. </div>
12. );
13. }
64) What are the rules you should follow for the hooks in React?
We have to follow the following two rules to use hooks in React:
o You should call hooks only at the top level of your React functions
and not inside the loops, conditions, or nested functions. This is
used to ensure that hooks are called in the same order each time a
component renders, and it also preserves the state of hooks
between multiple useState and useEffect calls.
o You should call hooks from React functions only. Don't call hooks
from regular JavaScript functions.
65) What are forms in React?
In React, forms are used to enable users to interact with web applications.
Following is a list of the most common usage of forms in React:
o Forms facilitate users to interact with the application. By using
forms, the users can communicate with the application and enter
the required information whenever required.
o Forms contain certain elements, such as text fields, buttons,
checkboxes, radio buttons, etc., that can make the application more
interactive and beautiful.
o Forms are the best possible way to take inputs from the users.
o Forms are used for many different tasks such as user authentication,
searching, filtering, indexing, etc.
66) What is an error boundary or error boundaries?
An error boundary is a concept introduced in version 16 of React. Error
boundaries provide a way to find out the errors that occur in the render
phase. Any component which uses one of the following lifecycle methods
is considered an error boundary. Let's see the places where an error
boundary can detect an error:
o Render phase
o Inside a lifecycle method
o Inside the constructor
Let's see an example to understand it better:
Without using error boundaries:
1. class CounterComponent extends React.Component{
2. constructor(props){
3. super(props);
4. this.state = {
5. counterValue: 0
6. }
7. this.incrementCounter = this.incrementCounter.bind(this);
8. }
9. incrementCounter(){
10. this.setState(prevState => counterValue = prevState+1);
11. }
12. render(){
13. if(this.state.counter === 2){
14. throw new Error('Crashed');
15. }
16. return(
17. <div>
18. <button onClick={this.incrementCounter}>Increment Va
lue</button>
19. <p>Value of counter: {this.state.counterValue}</p>
20. </div>
21. )
22. }
23. }
In the above code, you can see that when the counterValue equals 2, it
throws an error inside the render method. We know that any error inside
the render method leads to unmounting of the component so, to display
an error that occurs inside the render method, we use error boundaries.
When we are not using the error boundary, we see a blank page instead of
seeing an error.
With error boundaries:
We have specified earlier that error boundary is a component using one or
both of the following methods:
o static getDerivedStateFromError
o componentDidCatch
See the following code where we create an error boundary to
handle errors in render phase:
1. class ErrorBoundary extends React.Component {
2. constructor(props) {
3. super(props);
4. this.state = { hasError: false };
5. }
6. static getDerivedStateFromError(error) {
7. return { hasError: true };
8. }
9. componentDidCatch(error, errorInfo) {
10. logErrorToMyService(error, errorInfo);
11. }
12. render() {
13. if (this.state.hasError) {
14. return <h4>Something went wrong</h4>
15. }
16. return this.props.children;
17. }
18. }
You can see in the above code the getDerivedStateFromError function
renders the fallback UI interface when the render method has an error.
The componentDidCatch logs the error information to an error tracking
service.
Now with error boundary, we can render the CounterComponent in the
following way:
1. <ErrorBoundary>
2. <CounterComponent/>
3. </ErrorBoundary>
67) In which cases do error boundaries not catch errors?
Following are some cases in which error boundaries don't catch errors:
o Error boundaries don't catch errors inside the event handlers.
o During the server-side rendering.
o In the case when errors are thrown in the error boundary code itself.
o Asynchronous code using setTimeout or requestAnimationFrame
callbacks.
React Redux Interview Questions
68) What were the major problems with MVC framework?
The major problems with the MVC framework are:
o DOM manipulation was very expensive.
o It makes the application slow and inefficient.
o There was a huge memory wastage.
o It makes the application debugging hard.
69) Explain the Flux concept.
Flux is an application architecture that Facebook uses internally for
building the client-side web application with React. It is neither a library
nor a framework. It is a kind of architecture that complements React as
view and follows the concept of Unidirectional Data Flow model. It is useful
when the project has dynamic data, and we need to keep the data
updated in an effective manner.
For More Information, Click here.
70) What is Redux?
Redux is an open-source JavaScript library used to manage application
state. React uses Redux for building the user interface. The Redux
application is easy to test and can run in different environments showing
consistent behavior. It was first introduced by Dan Abramov and Andrew
Clark in 2015.
React Redux is the official React binding for Redux. It allows React
components to read data from a Redux Store, and dispatch Actions to the
Store to update data. Redux helps apps to scale by providing a sensible
way to manage state through a unidirectional data flow model. React
Redux is conceptually simple. It subscribes to the Redux store, checks to
see if the data which your component wants have changed, and re-
renders your component.
For More Information, Click here.
71) What are the three principles that Redux follows?
The three principles that redux follows are:
1. Single source of truth: The State of your entire application is
stored in an object/state tree inside a single Store. The single State
tree makes it easier to keep changes over time. It also makes it
easier to debug or inspect the application.
2. The State is read-only: There is only one way to change the State
is to emit an action, an object describing what happened. This
principle ensures that neither the views nor the network callbacks
can write directly to the State.
3. Changes are made with pure functions: To specify how actions
transform the state tree, you need to write reducers (pure
functions). Pure functions take the previous State and Action as a
parameter and return a new State.
72) List down the components of Redux.
The components of Redux are given below.
o STORE: A Store is a place where the entire State of your application
lists. It is like a brain responsible for all moving parts in Redux.
o ACTION: It is an object which describes what happened.
o REDUCER: It determines how the State will change.
For More Information, Click here.
73) Explain the role of Reducer.
Reducers read the payloads from the actions and then updates the Store
via the State accordingly. It is a pure function which returns a new state
from the initial State. It returns the previous State as it is if no work needs
to be done.
74) What is the significance of Store in Redux?
A Store is an object which holds the application's State and provides
methods to access the State, dispatch Actions and register listeners via
subscribe(listener). The entire State tree of an application is saved in a
single Store which makes the Redux simple and predictable. We can pass
middleware to the Store which handles the processing of data as well as
keep a log of various actions that change the Store's State. All the Actions
return a new state via reducers.
75) How is Redux different from Flux?
The Redux is different from Flux in the following manner.
SN Redux Flux
Flux is neither a l
framework. It is a
Redux is an open-source
architecture that
1. JavaScript library used to
React as view an
manage application State.
concept of Unidir
Flow model.
2. Store's State is immutable. Store's State is m
In this, Store and change logic In this, the Store
3.
are separate. and change logic
4. It has only a single Store. It can have multi
It has single Disp
Redux does not have Dispatcher
5. actions pass thro
concept.
Dispatcher.
76) What are the advantages of Redux?
The main advantages of React Redux are:
o React Redux is the official UI bindings for react Application. It is kept
up-to-date with any API changes to ensure that your React
components behave as expected.
o It encourages good 'React' architecture.
o It implements many performance optimizations internally, which
allows to components re-render only when it actually needs.
o It makes the code maintenance easy.
o Redux's code written as functions which are small, pure, and
isolated, which makes the code testable and independent.
77) How to access the Redux store outside a component?
You need to export the Store from the module where it created with
createStore() method. Also, you need to assure that it will not pollute the
global window space.
1. store = createStore(myReducer)
2. export default store