0% found this document useful (0 votes)
812 views

React Questions and Answers Ebook

This document provides an overview and introduction to resources from Dot Net Tricks, an organization that provides online courses and training materials related to software development. It describes Dot Net Tricks' website and blog, which receive over 300k monthly visitors, and their offerings including free study materials, online courses, instructor-led training programs, eBooks, and technical recruiting services. It also includes brief biographies of the author of this book, Manav Pandya, and introduces the topics that will be covered in the book on React interview questions and answers.

Uploaded by

Md Asif Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
812 views

React Questions and Answers Ebook

This document provides an overview and introduction to resources from Dot Net Tricks, an organization that provides online courses and training materials related to software development. It describes Dot Net Tricks' website and blog, which receive over 300k monthly visitors, and their offerings including free study materials, online courses, instructor-led training programs, eBooks, and technical recruiting services. It also includes brief biographies of the author of this book, Manav Pandya, and introduces the topics that will be covered in the book on React interview questions and answers.

Uploaded by

Md Asif Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

React Interview Questions & Answers

All rights reserved. No part of this book can be reproduced or stored in any retrieval system or transmitted in
any form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning
without the prior written permission of the Dot Net Tricks Innovation Pvt. Ltd.

The author of this book has tried their best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author or
Dot Net Tricks Innovation Pvt. Ltd. will not be liable for any damages, incidental or consequential caused directly
or indirectly by this book.

Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.

All other trademarks referred to in this book are the property of their respective owners.

Release History
 Initial Release 1.0 - 3rd Sep 2019

1
Page
About Dot Net Tricks
Dot Net Tricks is founded by Shailendra Chauhan (Microsoft MVP), on Jan 2010. Dot Net Tricks came into
existence in the form of a blog post over various technologies including .NET, C#, SQL Server, ASP.NET, ASP.NET
MVC, JavaScript, Angular, Node.js and Visual Studio, etc.

The company which is currently registered by a name of Dot Net Tricks Innovation Pvt. Ltd. came into the shape
in 2015. Dot Net Tricks website has an average footfall on the tune of 300k+ per month. The site has become a
cornerstone when it comes to getting skilled-up on .NET technologies and we want to gain the same level of
trust in other technologies. This is what we are striving for.

We have a very large number of trainees who have received training from our platforms and immediately got
placement in some of the reputed firms testifying our claims of providing quality training. The website offers you
a variety of free study material in the form of articles.

Dot Net Tricks Courses


Master in-demand job skills with our step by step and project-based courses. Learn to start a new career, with
our curated learning paths tailored to today's developers and technology needs. Learn to code, prepare yourself
for interviews, and get hired!

We offer the eBooks in the following categories:

 .NET Development
 Front-end Development
 Cloud
 DevOps
 Programming Languages
 Database - SQL and NoSQL
 Mobile Development
 ML/AI and many more...

You can start learning free from here: https://www.dotnettricks.com/courses

Dot Net Tricks Pro


DotNetTricks Pro unlocks the access of DotNetTricks premium features like unlimited access to all courses,
source codes, and assessments. Get help over email or phone. Upgrade your skills with curated learning paths
tailored to today's developers and technology needs. Learn new skills and discover the world of possibilities with
step-by-step guidance.
2
Page
Dot Net Tricks Pro Features

Each Pro member will get access to our full-featured learning platform with advanced tools, which is required to
learn new skills and advance his/her career.

Start your journey today to learn coding. Because learning to code is the first step and forward to advance your
career. The detail about Dot Net Tricks Pro can be found here: https://www.dotnettricks.com/pro-membership

Dot Net Tricks Live Training


Instructor-led Training Programs

For a beginner who needs regular guidance, we have a fully packed Master Courses. They are almost equal to
semester courses taught in engineering colleges when it comes to length, breadth of content delivery, the only
difference instead of 5-6 months, they take approx. 6 weeks of live classes.

The detail about Master courses can be found here: https://www.dotnettricks.com/instructor-led-courses

Corporate Training

Dot Net Tricks having a pool of mentors who help the corporate to enhance their employment skills as per
changing the technology landscape. Dot Net Tricks offers customized training programs for new hires and
3

experienced employees through online and classroom mode. As a trusted and resourceful training partner, Dot
Page
Net Tricks helps the corporate to achieve success with its industry-leading instructional design and customer
training initiatives.

Apart from these, we also provide on-demand boot camps and personalized project consultation.

The detail about Corporate Training can be found here: https://www.dotnettricks.com/corporate-training

Dot Net Tricks eBooks


Dot Net Tricks offer a wide range of eBooks on technical interviews Q&A. All eBooks are written by industry
experts and coaches. These eBooks will help you to prepare yourself for your next job within a short time. We
offer the eBooks in the following categories:

 .NET Development
 Front-end Development
 Cloud
 DevOps
 Programming Languages
 Database - SQL and NoSQL
 Mobile Development
 ML/AI and many more….

You can buy other eBooks from here: https://www.dotnettricks.com/books

Technical Recruiting
We provide full technical staffing service which suits our client needs. Our technical recruiters search across the
world to find highly skilled professionals that will fit our clients need. If you are looking for a job change, do
share your resume at [email protected]. Dot Net Tricks will help you to find your dream job in MNCs.

Join us today, learn to code, prepare yourself for interviews, and get hired!

4
Page
Dedication
My mom Kiranben Pandya and my father Prakashbhai Pandya deserve to have their name on the cover as
much as I do for all their support made this possible. I would like to say thanks to all my family
members, friends, the mentors who supported me either directly or indirectly no matter how tough and
easy the situations to achieve my goals.

-Manav Pandya

5
Page
Introduction
What Where Author Qualification to Write This Book
Manav Pandya is an enthusiast Front-end developer having vast experience, working on different technologies
like Angular, React, React-Native, VueJs, TypeScript, NodeJs, MongoDB and other technologies such as Redux,
Angular Material, Material-UI, Bootstrap, HTML, CSS, JQuery, etc.

What This Book Is


React is the most popular UI library developed by Facebook, to create single page application (SPA) as well as
Mobile and Desktop based applications. In this book, we are going to learn about the fundamentals of React like
JSX, Component, State, Props, Routing, Hooks, and many other topics.

What You’ll Learn


This book is for those who want to learn React and also for those who are going to appear for the React
interview to have a bright future in front-end technologies.

 Introducing React
 JSX in Depth
 Components
 State
 Props
 Forms
 Event Handling
 Conditional Rendering
 Routing
 React Hooks

Our best wishes always with you for your learning and growth!

6
Page
About the Author
Manav Pandya - An Author and Front-end developer
Manav Pandya is working as a Front-end engineer with a leading
organization and having vast experience in Front-end technologies. He
is very passionate about the JavaScript, Angular, React and Vue.

He is Author, Blogger, Community contributor, Learner by following


self-learning approach.

He is keen to learn new technologies. His contributions gave him


various recognition including Member of the month September 2018,
Member of the month October 2018.

He always tries to keep updated himself about new technologies and learning new skills and share with other
in simple manner.

He hopes that this e-book helps you to crack interview of Angular. This is the first edition of this book but not
last. Please provide your feedback that helps us to improve this book quality.

7
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.

The e-mail addresses are listed as follows:

[email protected]
[email protected]

We are always happy to hear from our readers. Please provide your valuable feedback and comments!

You can follow us on YouTube, Facebook, Twitter, LinkedIn, andGoogle Plus or subscribe to RSS feed.

8
Page
Table of Contents

React Interview Questions & Answers................................................................................1


Release History....................................................................................................................................................1
About Dot Net Tricks...........................................................................................................................................2
Dot Net Tricks Courses........................................................................................................................................2
Dot Net Tricks Pro............................................................................................................................................... 2
Dot Net Tricks Live Training................................................................................................................................ 3
Dot Net Tricks eBooks......................................................................................................................................... 4
Technical Recruiting............................................................................................................................................ 4
Dedication........................................................................................................................................................... 5
Introduction........................................................................................................................................................ 6
About the Author................................................................................................................................................ 7
How to Contact Us.............................................................................................................................................. 8

Introducing React................................................................................................................ 16
Q1. What is React?.......................................................................................................................................... 16
Q2. Explain the evolution history of React?.................................................................................................... 16
Q3. Why use React?.........................................................................................................................................17
Q4. What are the important features of React?............................................................................................. 17
Q5. What is Virtual DOM in React?................................................................................................................. 17
Q6. What is the difference between Real DOM and Virtual DOM?................................................................18
Q7. What is React Fiber?................................................................................................................................. 18
Q8. What is Reconciliation?.............................................................................................................................19
Q9. What are the key points for considering Reconciliation?.........................................................................19
Q10. What are the important fields of Fiber?...................................................................................................19
Q11. What is Diffing Algorithm?........................................................................................................................19
Q12. Why react getting so popular?..................................................................................................................20
Q13. What’s new in React 16.8?....................................................................................................................... 20
Q14. What are the Hooks in React?.................................................................................................................. 21
Q15. Why we need Hooks in React?................................................................................................................. 21
9
Page

Q16. What are the types of Hooks API?............................................................................................................ 21


Q17. How to use React Hooks?......................................................................................................................... 22
Q18. How to add React in a web application?.................................................................................................. 23
Q19. How to minify React for the production?................................................................................................. 24
Q20. How to add JSX in our React minimal application?.................................................................................. 24
Q21. How to create a new React app?.............................................................................................................. 24
Q22. How to run testing for the current React app?........................................................................................ 25
Q23. How to build React app?...........................................................................................................................25
Q24. Explain the folder structure of a React app?............................................................................................ 25
Q25. How to revoke build configuration of React app?....................................................................................26
Q26. What IDE’s are used to develop a React application?.............................................................................. 26
Q27. How to update build tooling of a React app?........................................................................................... 26
Q28. What are the advantages of using create-react-app?.............................................................................. 27
Q29. What are the disadvantages of using create-react-app?......................................................................... 27
Q30. How to install different dependencies?....................................................................................................27

JSX in Depth......................................................................................................................... 28
Q1. What is JSX?.............................................................................................................................................. 28
Q2. How to write JSX syntax?.......................................................................................................................... 28
Q3. Why we should use JSX?........................................................................................................................... 29
Q4. How to use JavaScript Expression in JSX?.................................................................................................29
Q5. How to write conditional statements using JSX?......................................................................................30
Q6. How to use attributes using JSX?..............................................................................................................30
Q7. How to use comments in JSX?.................................................................................................................. 31
Q8. How JSX contains child elements?............................................................................................................32
Q9. How JSX works behind the scene?............................................................................................................32
Q10. What is React.createElement() method?................................................................................................. 33
Q11. How to use Props using JSX?.....................................................................................................................33
Q12. How to use custom JSX elements?........................................................................................................... 34
Q13. How to send props/state to the child JSX using spread operator?.......................................................... 34
Q14. Why in JSX props default values are true?............................................................................................... 35

Components........................................................................................................................ 37
10

Q1. What is a Component?............................................................................................................................. 37


Page
Q2. What is Component in React?.................................................................................................................. 37
Q3. How to create a Component in React?.....................................................................................................37
Q4. What are different types of Component in React?.................................................................................. 38
Q5. What is stateful or Class-based Component in React?.............................................................................38
Q6. What is Stateless or Functional Component in React?.............................................................................39
Q7. Which component type should we use in React?.................................................................................... 40
Q8. How to do Component Composing in React?...........................................................................................40
Q9. How to do Component Decomposing in React?.......................................................................................42
Q10. How to render a Component in React?.................................................................................................... 44
Q11. What are Pure and Impure Components in React?..................................................................................44
Q12. When to use Pure Components in React?................................................................................................ 44
Q13. Explain React component lifecycle methods............................................................................................45
Q14. Different stages of executing Component lifecycle methods.................................................................. 46
Q15. Do explain commonly used Component lifecycle methods?................................................................... 46
Q16. Do explain other Component lifecycle methods?.................................................................................... 47
Q17. How to use Component lifecycle methods in React?............................................................................... 48
Q18. What are the Class properties in React?.................................................................................................. 49
Q19. Do explain defaultProps in React?............................................................................................................49
Q20. Do explain displayName in React?............................................................................................................50
Q21. What are the instance properties in React?............................................................................................. 50
Q22. What is Controlled Component in React?................................................................................................ 50
Q23. What is Uncontrolled Component in React?............................................................................................ 51
Q24. What is Higher Order Component in React?............................................................................................ 52
Q25. How to create a Higher Order Component (HOC) in React?.................................................................... 52
Q26. Why we should use HOC?......................................................................................................................... 54
Q27. How to render components conditionally?.............................................................................................. 54

State.....................................................................................................................................56
Q1. What is a State in React?.......................................................................................................................... 56
Q2. How to declare State in React?.................................................................................................................56
Q3. What is the alternative approach to use State in a Component?............................................................ 57
11

Q4. How to access State values?..................................................................................................................... 57


Page
Q5. How to update State value?..................................................................................................................... 58
Q6. Why we should not update the State directly in React?.......................................................................... 59
Q7. When to use a callback function with State?........................................................................................... 60
Q8. How to update multiple State values?......................................................................................................60
Q9. What is a getInitialState() in React?..........................................................................................................61
Q10. How to use State with Higher Order Component?...................................................................................61

Props.................................................................................................................................... 62
Q1. What is Props in React?............................................................................................................................ 63
Q2. How to pass Props from parent to child?................................................................................................. 63
Q3. How to access the Props value in Component?....................................................................................... 64
Q4. How to pass Props to the Stateless function?.......................................................................................... 64
Q5. How to pass a complete object as Props to the Component?................................................................. 65
Q6. How to provide default values to the Props in React?............................................................................. 66
Q7. What is an alternative way to use default props?....................................................................................67
Q8. How to provide the default types of Props?.............................................................................................68
Q9. How many prop types are supported in React?....................................................................................... 69
Q10. How to use defaultProps in Stateless/Functional component?............................................................... 70
Q11. What is a render prop in React?............................................................................................................... 70
Q12. What is the Difference between State and Props?.................................................................................. 72

Forms................................................................................................................................... 72
Q1. What are the Forms in React?.................................................................................................................. 72
Q2. How many types of Form input are supported?.......................................................................................73
Q3. What are Controlled inputs in React?.......................................................................................................73
Q4. What is Uncontrolled input in React?.......................................................................................................74
Q5. How to manage file input type using uncontrolled input?.......................................................................75
Q6. What is createRef in React?......................................................................................................................76
Q7. How to access ref in React?...................................................................................................................... 77
Q8. How to pass callback ref between the Components?.............................................................................. 77
Q9. What is the defaultValue attribute in React?........................................................................................... 78
Q10. How to handle multiple inputs in React?................................................................................................. 78
12

Event Handling.................................................................................................................... 80
Page
Q1. What is Event in React?............................................................................................................................ 80
Q2. How to attach an event handler with an element?..................................................................................81
Q3. How to attach an event handler to the button element?........................................................................ 81
Q4. How to prevent default behaviour in React?........................................................................................... 82
Q5. How to use multiple event handlers in React?.........................................................................................82
Q6. How to pass arguments to the event handlers in React?.........................................................................83
Q7. How to pass the event handler function as props?..................................................................................84
Q8. How to access events coming from props in React?................................................................................ 84
Q9. How to assign events using the bind method?.........................................................................................85
Q10. How to assign events using the arrow function?..................................................................................... 86

Conditional Rendering.........................................................................................................86
Q1. What is Conditional Rendering in React?................................................................................................. 86
Q2. How to render element based on if-else in React?.................................................................................. 87
Q3. How to render component conditionally using if-else in React?............................................................. 87
Q4. How to use ternary operator for rendering element in React?............................................................... 88
Q5. How to render element or component using && condition in React?.................................................... 89
Q6. How to render the element/content using switch case?......................................................................... 89
Q7. How to use nested conditional rendering in React?................................................................................ 90
Q8. How to prevent component being rendered?..........................................................................................91

Routing.................................................................................................................................91
Q1. What is Routing in React?......................................................................................................................... 91
Q2. What are different libraries available to implement routing in React?................................................... 92
Q3. How to implement Routing in React?.......................................................................................................92
Q4. What is react-router-dom?....................................................................................................................... 92
Q5. How to implement basic routing in React?.............................................................................................. 93
Q6. What is <Link> in React Router?............................................................................................................... 94
Q7. What is <Route> in React Router?............................................................................................................95
Q8. How to configure Route prefix in React?..................................................................................................95
Q9. How many Route render methods are supported?..................................................................................96
Q10. What is <Router> in React Router?.......................................................................................................... 96
13

Q11. What is <Switch> in React Router?...........................................................................................................96


Page
Q12. What is <BrowserRouter> in React Router?............................................................................................. 97
Q13. How to identify activated link in React Router?....................................................................................... 97
Q14. How to provide styles to activated link in React?.....................................................................................97
Q15. How to pass route parameters in React Router?..................................................................................... 98
Q16. What is the Location object in React Router?.......................................................................................... 99
Q17. What is match object in React Router?.................................................................................................... 99
Q18. What is matchPath in React Router?......................................................................................................100
Q19. What is withRouter in React Router?..................................................................................................... 101
Q20. What is the history object in React Router?...........................................................................................102
Q21. How to enable server rendering in React Routing?................................................................................104
Q22. How to redirect to default (404) page in React?.................................................................................... 105

React Hooks.......................................................................................................................105
Q1. What are the Hooks in React?................................................................................................................ 106
Q2. Why Hooks are useful?........................................................................................................................... 106
Q3. What are the features of React Hooks?..................................................................................................106
Q4. How to get started with Hooks?............................................................................................................. 106
Q5. What is the State Hook in React?........................................................................................................... 107
Q6. What is the syntax using useState in React?.......................................................................................... 107
Q7. How to set the initial value using useState?...........................................................................................107
Q8. How to update state value using useState()?.........................................................................................107
Q9. What is a useEffect hook in React?.........................................................................................................109
Q10. How to use useEffect hook?................................................................................................................... 109
Q11. How to call useEffect hook for the specific number of time hook?....................................................... 110
Q12. How to call API using useEffect hook?....................................................................................................110
Q13. What is a custom hook in React?............................................................................................................111
Q14. How to create the custom hook?........................................................................................................... 111
Q15. How to access custom hook in React?....................................................................................................112
Q16. What is a useReducer hook?...................................................................................................................113
Q17. How to use useReducer hook?............................................................................................................... 113
Q18. What are the different hook types in React 16.8?................................................................................. 114
14

Q19. Do we need to convert class component to function component?.......................................................115


Page
Q20. Do all the third-party libraries support the hooks?................................................................................ 115
Q21. Can we use multiple state variables using useState?.............................................................................115
Q22. Can we re-render the function component using forceUpdate()?.........................................................115
Q23. How to remember the cache value between multiple renders?........................................................... 116
Q24. Can we use class and hook together?.....................................................................................................116
Q25. What is the meaning by using square brackets [ ] in hooks?................................................................. 116

References.........................................................................................................................117

15
Page
1
Introducing React
Q1. What is React?
Ans. React is a JavaScript-based library which is used to create a SPA (Single Page Application) and different
User Interfaces. React is developed and maintained by Facebook and other contributors.

By using React, we can develop web and mobile application by just following component-based architecture,
and by using React we can get the robust, scalable and high-performance application.

Q2. Explain the evolution history of React?


Ans. The evolution history of React is given below –

16
Page
Q3. Why use React?
Ans. React is a booming word nowadays due to certain reasons which are listed below.

 The simple and straight forward learning curve


 Component-based architecture
 Maintainable and easy to develop applications
 Getting the high performance of our app to compare to other libraries and frameworks
 Open source and rich toolset
 Can create end-to-end SPA (Single page applications)
 Great support of various Developer tools
 Virtual DOM and modern Ecosystem
 Rich community support

Q4. What are the important features of React?


Ans. React is a front-end development library which is used to create light-weight web and mobile
applications; thus it comes with the various and useful features which make React to fly.

 Virtual DOM
 Learning Curve
 Application Performance
 Data-bindings
 Component-based architecture
 JSX
 Server-side Rendering
 Rich life-cycle hooks
 Props and States
 Rich error reporting

Above all are the important features which are introduced with the React library which makes our development
a lot easier.

Q5. What is Virtual DOM in React?


Ans. DOM plays an important role in terms of web application performance, thus there are tons of
frameworks are available who manipulates the DOM directly by adding, modifying or removing any existing
element.

When we perform any action on a page, at that time content should be updated based on the result of action
and it should be reflected in the DOM.

In React, Virtual DOM plays an important role by updating DOM which marked as a dirty.

Basically, React’s Virtual DOM convert the dirty component into Virtual image of a component and compare it
17

with the existing DOM, and based on the result of the comparison, the new DOM will be replaced by the existing
DOM.
Page
Below is the visualized form of Virtual DOM.

Q6. What is the difference between Real DOM and Virtual DOM?
Ans. When we change any action in an application, at that time real DOM should be updated, in this case, it
would be expected that all that conversion task should be faster to achieve higher performance.

Basically, a DOM or Real DOM is a structured collection of abstracted elements and the Virtual DOM is the
abstraction of HTML DOM.

Real DOM is existing elements structure, whereas Virtual DOM is the virtual tree of our application with the
recent changes we have done.

At the end of the comparison between Real DOM and Virtual DOM, the newly updated DOM will be rendered
into the browser.

Q7. What is React Fiber?


Ans. As per the official definition.

“React Fiber is an ongoing reimplementation of React's core algorithm. It is the culmination of over two
years of research by the React team.”

Basically React Fiber was invented to support some concepts like Animation, Gesture recognition, and some
other advanced rendering mechanisms.

And one of the major use of React Fiber is to enable incremental rendering of the React’s Virtual DOM concept.
18
Page
Q8. What is Reconciliation?
Ans. When we perform any action in a current page of the application, at that time the render () function will
be triggered every time which is called tree of the element.

Now problem is that which tree will be rendered from the updated trees based on the comparison, and it may
also possible that it causes the overall application performance.

Reconciliation is the solution for the above motive to resolve the problem of updating UI while considering
complete rendering efficiency.

In other words, we can say the Reconciliation is an algorithm which determines which UI part needs to be
changed from the differentiate of the trees.

Q9. What are the key points for considering Reconciliation?


Ans. Below is the key point which is normally assumptions while implementing a heuristic algorithm.

 Different component types are assumed to generate substantially different trees. React will not attempt
to diff them, but rather replace the old tree completely.
 Diffing of lists is performed using keys. Keys should be "stable, predictable, and unique."

Q10. What are the important fields of Fiber?


Ans. Below is the list of important fields which are important while considering Fiber and its implementation.

 Type and key


 Return
 Child and siblings
 pendingProps and memoisedProps
 pendingWorkPriority
 alternate
 output

Q11. What is Diffing Algorithm?


Ans. Diffing Algorithm is used to compare different DOM tree, while in this algorithm it compares the two
different root element and based on the difference result, it mounts the new tree and unmounts old one.

For example we have a <img> element inside <div> and below is the old and new version of change.

// Old
<div id="mydiv">
<img src="" />
</div>
19

// New
<div id="mydiv">
Page
<a href="">Click Me</a>
</div>

Here is an above code snippet of two different versions of a <div>, we have changed <img> control to <a>
element, now React will tear down the old tree and build the new tree from the scratch with the updated
changes.

And to keep in mind that the child element of the root element will also be unmounted.

Q12. Why react getting so popular?


Ans. Today, React becomes most popular JavaScript-based library due to its flexibility and durability over a
period of time.

React has the various features like support of JSX syntax, Virtual DOM, declarative syntax, reusable and stateful
component, reconciliation and other tons of features makes it the top choice over other libraries and
frameworks.

Being a JavaScript-based library, we can have the flexibility to use the small piece of code or can include
complete features based on our business requirements.

Below is the Google Trends chart which shows the Comparison between React, Angular, and Vue over the last 5
years searched by the world.

Thus there is no point of comparison between them because three of them are identically different in terms of
implementation, performance, and usage.

Q13. What’s new in React 16.8?


Ans. With the release of React 16.8, now we have few new and few updates on existing feature and below
are the complete list of updates.

 New feature added called “Hooks”


 Improved the useReducer Hook lazy initialization API
20

 Support Hooks in the shallow renderer


Page

 The bailout of rendering on identical values for useState and useReducer Hooks
 It supports synchronous enables passed to React.lazy()

These all the updates in the latest version of React 16.8 and other changes like test runner and unit testing and
ESLint plugin are also updated.

Q14. What are the Hooks in React?


Ans. As per the official definition, React Hooks means.

“Hooks let you use state and other React features without writing a class. You can also build your own Hooks to
share reusable stateful logic between components”

By using Hooks, we can share state using function component which acts as isolated reusable units it means now
we don’t need to use class component for using state.

One of the updates in Hooks is that we can write the state and update it even within a single line of code.

Apart from using state in the function component, we can also access different lifecycle hooks using useEffect.

Q15. Why we need Hooks in React?


Ans. Basically, Hooks in React allow us to write state and various other features into the function component
which is completely a revolutionary step by the React team.

Now next question may raise that, why Hooks introduced in React 16.8.

And one of the strongest reason to use Hooks in React is that we can split the component into a smaller function
and the same function can use different React features.

We can also combine built-in hooks provided by React using “Custom Hooks”.

Other advantages like using lifecycle hooks function without creating or using the class-based component.

Q16. What are the types of Hooks API?


Ans.
 Basic Hooks
 useState
 useEffect
 useContext
 Additional Hooks
 useReducer
 useCallback
 useMemo
 useRef
 useImperativeHandle
 useLayoutEffect
 useDebugValue
21
Page
Q17. How to use React Hooks?
Ans. So far, we have seen the basic details about what hooks, why we need it, is but how to use it in our
React application.

We can simply use the Hooks API which is provided by the React, for example, we are going to use useState API
of the Hooks in below example.

import React, { useState } from "react";


import ReactDOM from "react-dom";

function SimpleHooksExample() {
const [message, putMessage] = useState("This is Hooks Demo");

function setmessage(value) {
putMessage(value);
}

return (
<div>
<p>{message}</p>
<button onClick={() => setmessage("This is Updated Message")}>
Update Message
</button>
</div>
);
}

ReactDOM.render(<SimpleHooksExample />, document.getElementById("root"));

First thing in the above example to be noticed is that we have used a function instead class-based component.

Then another thing is that we have used Hooks API called useState() which is used to return a stateful value
along with the function for updating the state value.

Along with the useState(), we have also provided default state value for the state variable called “message”.

After running the above simple example of Hooks, we can get output like this.

Before updating state value.


22
Page

After updating state value.


As you can see into the example, that our default message text will be updated using Hooks API useState(), and
this is how we can use different Hooks API in order to implement Hooks in react.

But one thing to notice that here in this example, we have just used a single line for the state, wherein class-
based component, we should declare it separately inside the class definition.

Q18. How to add React in a web application?


Ans. Adding react in the web app is a very straight forward process, for that we have a sample page below.

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<p>Adding React in Web Application</p>

<!-- Our React componenet will be loaded in this div -->


<div id="app"></div>

<!-- Load React. -->


<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
crossorigin></script>
</body>
</html>

In this HTML file, we have one div element where our component will be rendered.

Another important tag should be noticed is <script> which loads the React framework into our web application
and another script loads the react-dom package.
23
Page
Q19. How to minify React for the production?
Ans. Deployment to the production is the crucial thing, and for that, we need to load script file for the
production use which is described below.

<script src="https://unpkg.com/react@16/umd/react.production.min.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
crossorigin></script>

We just need to add above two different scripts in order to allow deployment into the production of our React
application.

Q20. How to add JSX in our React minimal application?


Ans. For the minimal React app setup, to enable JSX and work with it, we need to add an additional script
section like this.

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

We have added babel JavaScript package because Babel is responsible for converting JSX code to JavaScript so
that browser can understand the code snippet otherwise browser cannot detect JSX directly.

Q21. How to create a new React app?


Ans. There are two different ways to add React in our web app which are listed below.

 By adding React package script into HTML file


 By creating React app using create-react-app

A create-react-app is one of the easiest ways to get started with React for the initial stage, where we will get the
minimal setup of a React app structure.

Previously, the new React app can be created using the below command.

npm install –g create-react-app

But now we can make use of npx, and the command is.

npx create-react-app app_name

After creating a new React app using the above command, just follow these two commands.

cd app_name // jump to the newly created project

And then run the React app by using this command.

npm start
24
Page
Q22. How to run testing for the current React app?
Ans. Testing is one of the mandatory parts while developing web application, in React, we can easily initiate a
test runner.

React uses JEST test runner which is a kind of node-based runner which runs in Node environment.

JEST runner is faster and provides the high performance in unit testing because it does the testing of component
and its logic rather than DOM.

To start testing in React app, we can use the below command.

npm test

Q23. How to build React app?


Ans. When we create any web application, we need to deploy it for production use.

To build the React, we can use simple npm command like this.

npm run build

After running above command, we can see that a new folder called ‘build’ created in the root of the application.

Q24. Explain the folder structure of a React app?


Ans. After creating a new React app using command create-react-app, our new project is ready to get started
and the folder structure looks like this.

25
Page
Where public/index.html is the template page from where our component will be inside the specific div section
when the app loaded the first time.

And one of the entry points of our React app is src/index.js where we render our root component using
‘ReactDOM’.

App.js is our root component for this React application and related CSS files like App.css and App.test.js contains
design and unit testing specification.

ServiceWorker.js is created by default using create-react-app which is used to allow the cache-friendly
environment and it enhances overall app performance.

Q25. How to revoke build configuration of React app?


Ans. Sometimes we need to revoke the last build configuration due to some issue, so for that, we have an
npm command.

npm run eject

By running above npm command, we can remove the single build dependency from our React app.

Q26. What IDE’s are used to develop a React application?


Ans. To create any web application, we need to have one of the IDE for faster web development, the same
way there are so many IDE’s are available to create and work with the React application which is listed below.

 Visual studio code


 Visual Studio
 WebStorm
 Reactide
 Nuclide
 Atom
 SublimeText

Some other online web editors are also awesome to develop small React applications.

 Stalkblitz
 CodeSandBox
 Repl.it

Q27. How to update build tooling of a React app?


Ans. After creating the React app, we may need to upgrade our app to the latest version of our build tooling.

We can upgrade it by just using the single line command like this.

Npm install react-scripts@latest


26

After executing the above command, our react-scripts from the devDependencies will be updated to the latest
version.
Page
Q28. What are the advantages of using create-react-app?
Ans. Creating a project of React is a very straight forward process and for that, we just need to install create-
react-app package.

But why we need to use it, there are few advantages to using create-react-app which are listed below.

 One line command to set up React web app.


 No need to mug-up all the configuration, because it provides the way to set up and minifies the
production-ready app.
 Application versioning can be well maintained.
 It comes with the great package support like ESLint, Babel, Webpack and so on.
 Upgrading the existing app to the latest version is less painful

Q29. What are the disadvantages of using create-react-app?


Ans. When we create a React app using create-react-app, it comes with few created file like App component,
their related CSS, index.js is the entry point of application.

We can also call it “boilerplate” project, it means we need to delete those unwanted files because we need to
restructure the app from scratch so it can be painful all the time.

Another disadvantage is that, it does not fulfil all the advanced project structure, so need to wipe out everything
that we got using create-react-app in the long run.

Every time, we need to optimize it against the different business requirements because the project using create-
react-app comes with the minimal project structure.

Q30. How to install different dependencies?


Ans. When we create a React app, few packages are pre-installed like React, React-dom, and React-scripts.

These are the primary packages to get started with React, but we can install other dependencies just like we do
using npm install like this.

npm install react-router-dom

27
Page
2
JSX in Depth
Q1. What is JSX?
Ans. JSX stands for “JavaScript XML”.

Basically, JSX is a syntax extension of the JavaScript, in other words, we can say JSX is a way to use
JavaScript along with the HTML elements.

It can be used as a template engine but it’s not necessary to use it compulsorily thus it has some advantages to
use along with the React which are listed below.

 Faster in rendering and performance


 Can create a reusable component using JSX syntax
 It will be very easy to create HTML structure by using JSX

Q2. How to write JSX syntax?


Ans. JSX is a syntax extension, but it comes with the complete support of JavaScript.

JSX allows us to write JavaScript based expression, variables, and so on inside the HTML template just like we do
normally in the React component.

Below is a simple example of JSX.

var navmenu = (

<ul id="navmenu">

<li><a href="#">Link 1</a></li>

<li><a href="#">Link 2</a></li>

<li><a href="#">Link 3</a></li>

<li><a href="#">Link 4</a></li>

<li><a href="#">Link 5</a></li>

</ul>
28

);
Page

Here in above code, we have navigation menu link with the five different links which is basically a HTML code.
But the difference is that we have used variable “navmenu” which is JavaScript variable, this how this code will
be converted from JSX to JavaScript using Babel.

Same way, we can also use inline expression inside the curly braces { } like this using JSX.

var myelement = (

<h1> My Age is : { 5 * 5 } </h1>

);

Q3. Why we should use JSX?


Ans. Using JavaScript with XML makes it more useful while developing web application using React.

While using React for web development, we need to perform various task along with with the UI like events,
DOM manipulation, changes of states and props, managing reusable component and so on.

By using JSX, we can embed code of JavaScript with HTML easily which allow us to manage errors, inline
expressions, conditions, etc.

Using Component, we can have HTML markup and business logic in a single file so that it can be a more
manageable component in order to update anything.

And of the main advantage is that JSX can be easily used by just using curly braces { } in our JSX file and we are
good to go.

Q4. How to use JavaScript Expression in JSX?


Ans. JSX supports inline JavaScript expression with the template so that we can evaluate any supported
JavaScript expression inside the curly braces.

But to keep in mind that we cannot use if-else statements directly using JSX thus we can use different
conditional statements.

Below is the simple example which shows the use of JavaScript expression using JSX.

render() {
return (
<div>
<h3>Addition is : {25 + 55}</h3>
<h3>Subtraction is : {25 - 55}</h3>
<h3>Multiplication is : {25 * 55}</h3>
<h3>Division is : {25 / 55}</h3>
</div>
);
}
29

In the above example, we can see that there are different numerical expressions like Addition, multiplication
and so on.
Page
For evaluation JavaScript expression, we can provide the values and then it can be converted into pure
JavaScript format using Babel, at last, we will get the result based on the evaluation.

Q5. How to write conditional statements using JSX?


Ans. We can render different DOM elements based on the conditions and for that, we can write different
condition and after the evaluation, the specific element will be added or removed from the DOM.

Let’s render the div element based on the condition like this.

render() {
const isVisible = true;
return (
<div>
{isVisible ?
(
<h3>Hello Im Visible</h3> // true part
) :
(
<h3>Hello Im Not Visible</h3> // false part
)
}
</div>
);
}

In an example, we have one JavaScript constant variable with the true as a Boolean value, now we need to show
specific div based on the value of the variable.

For that, we have used a ternary condition like if we got true as a value of a variable than show true part else
render false part.

This is a very basic example which shows how to use conditions and render the different elements based on the
conditions.

Q6. How to use attributes using JSX?


Ans. Using JSX, we can also make use of attributes just like we use along with the normal HTML elements.

To use attributes, we have some naming conventions to be followed because in JavaScript there is some reserve
keyword like “class” wherein JSX, we should use “className”.

Keep in mind one thing that we need to use camel case for all the attributes, action name and so on.

render() {
return (
30

<div className={myClass}>
<h1>
Page

Hello World
</h1>
</div>
);
}

Here in the above example, we have used attribute className=”” along with the value, this is how we have
accessed the class attribute using JSX.

Same way, we can use other different attributes as explained in the below example.

render() {
return (
<div className={myClass}>
<h1>
Hello World
</h1>
<img src={myImg} alt="Image Not Found" />
<a href={myLink} />
</div>
);
}

Q7. How to use comments in JSX?


Ans. Comments are the useful part when it comes to code readability, in JSX we can also use comments
inside the curly braces { }.

Below is the simplest example of using comments in JSX.

render() {
return (
<div className={myClass}>
<h1>
// Hello World - Single line comment
</h1>
/* <div>
<img src={myImg} alt="Image Not Found" />
<a href={myLink} /> */
</div>

</div>
);
}

As you can see into the above example that we have used both Single line comment (//) and multi-line
31

comments (/* … */).


Page
Q8. How JSX contains child elements?
Ans. JSX can also contain different child element wrapped inside the parent element, for that we need to
wrap it up using any parent element as shown below.

render() {
return (
// Parent element
<div>
<h1>Hello World</h1> // child 1
<h3>Hello World</h3> // child 2
<h5>Hello World</h5> // child 3
</div>
);
}

As you can see into the above example that we have one parent <div> element which is a wrapper for the
component and that we have <h1>, <h3> and <h5> as a child elements.

This is how we can design our template using parent-child elements.

Q9. How JSX works behind the scene?


Ans. JSX syntax is different than JavaScript, but while we write anything in JSX, at last, it will be converted
into JavaScript using Babel.

When we create any component, at that time every element into the component will be transpired into a
React.createElement () call.

It means that every element should be converted into the React element before rendering, for example, we
have a simple <h1> element in our component like this.

render() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}

Here we have <h1> element inside the parent <div> element, but <h1> element will be converted using
React.createElement() like this.

React.createElement("h1", {}, "Hello, World");


32
Page
Q10. What is React.createElement() method?
Ans. When we create an element in React application, at that time React call this method called
“React.createElement ()” which takes three different arguments which are listed below.

 Name: Name of the element to be created


 Props: The list of different properties related to the element in a form of object
 Children: Contains the different list of child elements or content of the same element

Below is the simple example of <div> element converted using React.createElement().

React.createElement("div", null, "Im From DIV element")

Q11. How to use Props using JSX?


Ans. Props in react is a read-only data passed from the parent component to the child component.

While working with JSX, we can pass the properties in different ways which are listed below.

 Pass props as an expression

render() {
return (
<div>
<Demo
// Passing props as expression
simpleInterest={(5000 * 12 * 2) / 100}
/>
</div>
);
}
 Pass props as array/object

render() {
const employeeDetail = {
name: 'Manav Pandya',
email: '[email protected]'
};
return (
<div>
<Demo
myData={employeeDetail}
/>
</div>
);
}
33

 Pass props as variable value


Page

render() {
const isVisible = true;
return (
<div>
<Demo
isVisible
/>
</div>
);
}

Q12. How to use custom JSX elements?


Ans. We can create the component using JSX, same way we can also render reusable JSX element as a child
element into the JSX file.

For that, we just need to import the same component and can use it inside the parent JSX element as explained
in the below example.

render() {
return (
<div>
// JSX Child file 1
<Header />
// JSX Child file 2
<Content />
// JSX Child file 3
<Footer />
</div>
);
}

Here in this example, we have on parent element <div> and inside the parent element, we have three different
elements which is basically a JSX element resides at a different location.

So, when we run our application, our child JSX element will be rendered in a particular order.

Q13. How to send props/state to the child JSX using spread operator?
Ans. Using JSX, we can pass the props or state value to the child component, than we can make use of spread
operator like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';
import Demo from './Demo';
34

class App extends Component {


Page

constructor() {
super();
this.state = {
items: [
"Item 1",
"Item 2",
"Item 3",
]
};
}

render() {
return (
<div>
<Demo
items={...this.state.items}
/>
</div>
);
}
}

render(<App />, document.getElementById('root'));

Here in this example, we have Demo as a child component, and we have some items of the array from the
component state called “items”.

So, if we want to pass the complete state values to the child than we can use the spread operator (…) as we did
in the above example.

Q14. Why in JSX props default values are true?


Ans. In JSX, we can pass props to the child component, but what if we have a Boolean value to pass on to the
child.

Keep in mind always that if we use any Boolean values to be passed to the child than the default value would be
always “true”.

For example.

render() {
return (
<div>
<Demo
isAuthenticated
/>
35

<Demo
Page

isAuthenticated={false}
/>
</div>
);
}

Here in the above example, we have Demo as a child component, from where we are going to pass a property
called “isAuthenticated”.

But it is a boolean property, so if we don’t have any default value to pass, then it always will be true.

36
Page
3
Components
Q1. What is a Component?
Ans. Component nowadays is a booming world, but we may have a question like what is Component.

The component is a reusable, independent piece of code which contains the JavaScript and HTML component
data.

It can be exported from one place to another and using the import statement, we can access its various
functionality developed in the component file.

Basically, the component acts as a part of big application and duty of the component are to serve the specific
functionality wherever it’s being used, and one of the important advantages using component is that we can
create a loosely coupled system by dividing application module as chunk which called as “Component”.

Q2. What is Component in React?


Ans. As we know Component is a kind of reusable class, thus in React, the component is used to serve
specific functionality to the system by updating the browser DOM.

A Component is a backbone of any React application and every React application contains at least one
component to be executed.

It is used to serve component logic and user interface logic, and the combination of both will represent the user
interface to the end-user.

We can develop a complete page or a part of a page as a reusable chunk and can use it into other components
which makes it easy to use.

In React, Component also manages local state which is used to manage component level data for the rendering
purpose, we will discuss state in the upcoming section.

Q3. How to create a Component in React?


Ans. In React, component just returns the JSX code which is used to render something in the DOM.

Creating component is a very straight forward thing, for that we just need to create “.js” file and code should
look like this.
37

import React from 'react';


Page
class Demo extends React.Component {
render() {
return (
<div>
<h1>Component in React</h1>
</div>
);
}
}

export default Demo;

As you can see that we have an import statement where we have used ‘react’ which means we are going to use
react package for this component and its element “Component”.

One thing to be noticed here is that we have used “React. Component” because we are going to use Component
from the React package itself.

We cannot skip “render ()” method which is used to render the JSX/HTML content from the current component.

The last statement is to export the current component so that any component can access the current
component by its class name.

Q4. What are different types of Component in React?


Ans. React primarily supports two types of Component structure which are listed below.

 Stateful/Class based Component


 Stateless/Function-based Component

Q5. What is stateful or Class-based Component in React?


Ans. A Stateful Component or Class-based component can be created using ES6 class which is one of the
features in ES6.

Basically, a stateful component in React contains the internal state object which is used to manage component
level data for the rendering purpose.

Being a Class-based component, we can access different component from each other because there is
communication possible between two components by passing the state from one to another.

So whenever the state of the class will be changed, at that time the render () method also re-render its
JSX/HTML content.

Below is the simple example of a Stateful Component.

import React from 'react';


38

class Demo extends React.Component {


Page
constructor() {
super();
this.state = {
message: "This is Stateful Component !!!"
}
}

render() {
return (
<div>
<h1>Hello {this.state.message}</h1>
</div>
);
}
}

export default Demo;

As you can see into the above example, that we have used a class which is part of ES6, and apart from that we
have a constructor () which is again functionality of an ES6.

One thing to be noticed that inside the constructor, we have used “this.state” which is component-level state
management mechanism to populate data while rendering.

We can manipulate the state object whenever we want for the current component.

Q6. What is Stateless or Functional Component in React?


Ans. A Stateless or Functional component does not contain the state object and it follows purely a functional
approach while creating the component.

It is kind of simple function-based component which contains the “container” part, it means when we want to
show data based on the request but don’t require a data to be changed than function component will be used.

For example, we have data of 10 employees and we just need to show them as a list, then we can create
function component and can return the list of the employee along with the design part.

Keep in mind that functional component cannot maintain internal state object unlike Stateful component, but it
can use props in order to populate data in a webpage.

Below is the simple example of Stateless component.

const functionalComponent = (props) => {


<h1>Hello World !!!</h1>;
}
39

export default functionalComponent;


Page
Here in the above example, we have a simple function called “functional component” along with the props as an
argument, and this function just returns the static message.

We can use the function-based component while we want to use only rendering logic.

Q7. Which component type should we use in React?


Ans. Well, it completely depends on us that which component to be used in which situation.

Functional based classes are generally used for rendering the UI elements for the page.

While Class-based component has many advantages like we can implement component level state, can use
different lifecycle hooks, conditional rendering of different elements, and performing user interactivity via event
handling and so on.

Thus we should always use Functional component for just UI rendering purpose and Class-based component for
the rest of the operations.

Q8. How to do Component Composing in React?


Ans. We know that we can create two different types of component i.e. Stateless and Stateful component
which acts as an independent unit for the application.

But we need to use one component into another for the wrapping multiple components into a single component
then we can have references of the different components.

For example, we have a chat application component which can be divided into three different components like
this.

 Chat component
 Header content
 Chat content
 Footer content

Here we have created Chat as primary component while rest components are the child component which
performs the specific operation based on the instruction provided from the parent component.

By composing such component, we can have the flexibility to adjust the level of abstraction and the child
components can be used elsewhere in the application.

Below is the simple example of Abstraction component.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';
import Header from './Header';
import Content from './Content';
import Footer from './Footer';
40

class App extends Component {


Page

constructor() {
super();
this.state = {
name: 'React'
};
}

render() {
return (
<div>
<h1>Component Coposition in React</h1><hr />
<Header />
<Content />
<Footer />
</div>
);
}
}

render(<App />, document.getElementById('root'));

Here we have one main component is called “App” which is going to render into the ReactDOM.

But inside the render () method, we have one <div> element and from the same div element, we have
composed three different components using import statement which are.

 Header component
 Content component
 Footer component

This is how we can achieve reusability using Component Composition. After running the above example the
output will look like this.

41
Page
Q9. How to do Component Decomposing in React?
Ans. We have seen the example of Component composing, but now let’s learn about Component
Decomposing.

Sometimes we may have some DOM elements in a page where we need to use it repeatedly, so for that, we
don’t need to write the same logic again and again.

For example, we need to use link repeatedly for the navigation menu or another usage, so for that, it’s not
necessary to write the same logic again and again.

Below is the simple example.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {

renderLink() {
return (
<div>
<a href="www.dotnettricks.com">DotNetTricks Link</a>
</div>
)
}

renderContent() {
return (
<div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
)
}

render() {
return (
<div>
<h1>Component Decomposing in React</h1><hr />
{this.renderLink()}<hr />
{this.renderContent()}<hr />
42

</div>
Page

);
}
}

render(<App />, document.getElementById('root'));

In this example, we have App as a root component, where we are going to decomposing our component
element.

For that, we have created two different methods which return the content.

 renderLink()
 renderContent()

These two method returns the HTML content, it means whenever we need such content in this page, then we
just need to call it into render() and we are good to go.

render() {
return (
<div>
<h1>Component Decomposing in React</h1><hr />
{this.renderLink()}<hr />
{this.renderContent()}<hr />
</div>
);
}

This is how we can achieve component decomposing effectively, after running the above example the output
will look like this.

43
Page
Q10. How to render a Component in React?
Ans. While creating a project of React using create-react-app, the main entry point of application is an
index.js file where we render our root component like this.

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

// REndering App in ReactDOM


ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

Notice the line “ReactDOM.render()” from where we are actually rendering a <App/> component which is root
for our boilerplate application.

After importing root component, we should render it into the HTML DOM and here in index.js, we have used the
statement like this.
document.getElementById('root')

It will find the element by id “root” which is presented into the file name called “index.html”.

And after finding the element, the root component will be rendered and our application will be up and running.

Q11. What are Pure and Impure Components in React?


Ans. We have seen the different methods to create a component in React like Stateless and Stateful
component.

But people also talking about Pure and Impure component as well, but it not a new thing react, but it’s just a
different name of Component to be created which are listed below.

The pure component is the same as Stateful/Class based component but the difference is that Pure component
manages shouldComponentUpdate () lifecycle hooks.

It means whenever new changes are detected, at that time componentShouldUpdate() hook will be triggered by
default will every render() call.

And the Stateless component follows the same approach as an impure component so there is no such difference.

Q12. When to use Pure Components in React?


Ans. One of the main reason to use Pure Component is that it provides the ability to use
shouldComponentUpdate () hook which results in better optimization of the component.
44

Whenever any props or state value changed then at that time Pure component compares its latest values with
Page

the old values, and at last the Component will be re-render whenever shouldComponentUpdate() will be called.
So it is advisable to use such a component when we are mutating a data lot and the values of state and props
are almost the same every time.

More importantly, it gives you the performance boost because our Component will not be re-render again and
again without the DOM changes.

Q13. Explain React component lifecycle methods


Ans. Each and every Component in react follows the different lifecycle methods for the particular point of
time.

Each single lifecycle method has some intent in order to perform a specific action based on the situation while
rendering.

Below is the cheat sheet for the all commonly used lifecycle methods.

Below is the list of commonly used and less commonly used lifecycle methods of a component.

 Commonly used methods


o Constructor()
o Render()
o componentDidMount()
o componentDidUpdate()
o componentWillUnmount()
 Less commonly used methods
o Static getDerivedStateFromProps()
o shouldComponentUpdate()
o componentDidCatch()
45
Page
Q14. Different stages of executing Component lifecycle methods
Ans. Every React Component follows the number of lifecycle methods which follows a few stages in which
every lifecycle methods will be executed which are listed below.

 Initialization

This is the primary stage where the component will be constructed with the given Props and default
state values.

Every Stateful/Class based component can have a constructor in order to use state with the default
initial value.

 Mounting

Mounting is the second stage of the rendering process where the JSX returned by the render method
itself.

 Updating

Updating is the third stage and it will be executed when the state of a component is updated and the
application is repainted/re-rendered against props or state values.

 Unmounting:

As the name suggests, The Unmounting is the last step of the component lifecycle where the component
is removed from the page and will be destroyed completely.

Q15. Do explain commonly used Component lifecycle methods?


Ans. A Component in React comes with the different lifecycle methods which are used to perform some
actions.

But some of the methods are used commonly while using component which is listed below.

 Constructor()

A constructor is used to initializing and define the initial state for the component and it can also be used
to bind the different methods.

 Render()

Render is a kind of separate method and it is responsible for rendering the JSX/HTML by returning its
elements to the component instance.

But keep in mind that every component should have to render () method because it is a required
method while working with the component.
46
Page
 componentDidMount()

This method of the Component lifecycle is one of the most used methods which invokes immediately
whenever the component will be added into the DOM tree.

The developer used such a method to render something with the help of API endpoint in order to render
the initial data.

 componentDidUpdate()

Whenever any changes detected into the existing DOM, at that time this lifecycle method triggers and
we can update the DOM elements if required by using this method.
 componentWillUnmount()

This method of the lifecycle will be triggered when the component going to unmount.

Most of the time, this method is used to clear the states, unsubscribing the subscribed events, wiping
the different endpoint calls and so on.

Q16. Do explain other Component lifecycle methods?


Ans. There are few methods which are less used by the developer while working with a component which is
listed below.

 Static getDerivedStateFromProps()

This lifecycle method called before the render () method which is used to update the state which
sometimes depends on the props over time.

 shouldComponentUpdate()

This method invokes when the DOM changes need to re-render a component by comparing old state
and props value to the latest.

It is one of the methods used by the pure component which results in batter app performance by
ignoring the unused re-rendering process.

 componentDidCatch()

This is one of the methods for Error handling whenever we get an error for the unhandled JavaScript
errors.

Basically, it receives the two different parameters while the error will be thrown by the component
which are.

 Error: The type of error


 Info: The complete object which contains the information regarding the error thrown
47
Page
Q17. How to use Component lifecycle methods in React?
Ans. In React, we have different Component lifecycle methods which are used to perform any action based
on any period of time.

But next question may raise that how to use it in React component, so below is the simple example of some
lifecycle methods.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {


constructor() {
super();
this.state = {
name: 'Component lifecycle methods in React'
};
}

componentDidMount() {
this.setState({ name: "Component Going to Mount" });
}

componentwillUnmount() {
this.setState({ name: "Component Going to Unmount" });
}

render() {
return (
<div>
<h3>{this.state.name}</h3>
</div>
);
}
}

render(<App />, document.getElementById('root'));

Here in the above example, we have one component called “App”, in which we are going to use the state value.

If you have noticed that there are two lifecycle methods are implemented in which we have written the
setState() statement like this.

this.setState({ name: "Component Going to Mount" });


48
Page
When our component will be ready for the rendering at that time componentDidMount() will be triggered and
then componentWillUnmount() called.

This is how we can use different lifecycle methods based on the execution flow.

Q18. What are the Class properties in React?


Ans. Each component in React comes with the two different types of class properties which are listed below.

 Defaultprops
 DisplayName

Class properties are used to define the static properties to the class which is available on the class but not with
the instance of the class.

And basically, we can use such class properties to define the static value because it may possible that every
method does not have the proper context to return a value at the initial mounting process.

Q19. Do explain defaultProps in React?


Ans. This class property is used to define the default properties for the class, below is the simple example
which shows the usage of defaultProps.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {

render() {
return (
<div>
<h1> This is {this.props.name} Component </h1>
</div>
);
}
}

App.defaultProps = {
name: "APP"
}

render(<App />, document.getElementById('root'));

Here in this above example, we have App as a component, and we want to show component name from the
49

props.
Page
For the same, we have defined the component name as “defaultProps” so that we can make use of default
properties of the class like this.

Q20. Do explain displayName in React?


Ans. The displayName property is used for the debugging messages. Usually, we don’t need to set it explicitly
because it’s inferred from the name of the function or class that defines the component.

We might want to set it explicitly if we want to display a different name for debugging purposes or when you
create a higher-order component.

Q21. What are the instance properties in React?


Ans. Instance properties in React Component are used to provide the initial data to the component and it
also helps us to manage component level data for the rendering purpose.

There are two different types of instance properties are supported.

 Props

Props are the read-only data which can be defined by the parent component when calling the
component.

It can be passed from parent to child component as a property so that child can make use of them for
the rendering purpose.

 State

The state is a mutating data, and each Stateful component maintains its own state for the rendering
purpose which can help to maintain JSX code snippets based on the actual data.

The state is mutating it means we can update it whenever any action happens in a component and it can
be passed from child to parent as well.

Q22. What is Controlled Component in React?


Ans. In React, the different input controls such as <input>, <select> and other maintain its own state in order
to maintain its value.

Thus the values will be updated when user do the modification its value.

Basically, the values of such input elements maintain the event object which contains every information
regarding input like value, DOM parent, child, id and so on.

Whenever we change the value of an input, the value can be set the component state and it can be updated
using the setState() component’s API.

Below is the simple example to update the input value to the component state.

import React, { Component } from 'react';


50

import { render } from 'react-dom';


import './style.css';
Page
class App extends Component {
constructor() {
super();
this.state = {
inputVal: ''
};
}

inputChange(event) {
this.setState({ inputVal: event.target.value })
}

render() {
return (
<div>
<h1>Controlled Component in React</h1><hr />
Enter Name : <input type='text' onChange={(event) => this.inputChange(event)}
value={this.state.inputVal} />
</div>
);
}
}

render(<App />, document.getElementById('root'));

As you can see that we have <input> element which manages the onChange event, and on every keystroke by
the user, it gets the value of the input and the value will be updated into the state using setState().

By using this approach we can easily mutate the input values by just modifying the state value using the
associated function.

Q23. What is Uncontrolled Component in React?


Ans. We know about Controlled Component which is used to maintain the internal state data for the forms,
but there is an alternative option which is called Uncontrolled Component.

In Uncontrolled component, for handling forms value, we can use a reference (ref) of the input element rather
than using associated event handler.

Below is the example for getting the input value.

import React, { Component } from 'react';


import { render } from 'react-dom';
51

class Uncontrolled extends Component {


Page

constructor() {
super();
this.myinput = React.createRef();
}

onsubmit(event) {
console.log(this.myinput.current.value);
event.preventDefault();
}

render() {
return (
<div>
<h1>Uncontrolled Component in React</h1><hr />
Enter Name : <input type='text' ref={this.myinput} /><br />
<button onClick={(event) => this.onsubmit(event)}>Submit</button>
</div>
);
}
}

export default Uncontrolled;

For uncontrolled component, we have used “ref” which gets the reference of the input control.

Whenever we submit the form, at that time will get the value of input via ref which is an instance of CreateRef ().

This kind of Uncontrolled Component can be helpful when we do our form quickly and the code snippet takes a
smaller number of lines otherwise Controlled component is a good choice for the standard for implementation.

Q24. What is Higher Order Component in React?


Ans. As per the official definition on HOC is.

“A higher-order component (HOC) is an advanced technique to React for reusing component logic”

In other words, we can say that it accepts the component and returned the new processed component.

Basically, HOC is not a part of React’s Component API, it is kind of third party component where we can use
external component functionality by just importing it.

Syntax of the HOC will look like this.

const newComponent = myhoc(thisComponent);

Q25. How to create a Higher Order Component (HOC) in React?


52

Ans. Higher-Order Component takes the Component name which is wrapped around the HOC name, below is
Page

the simple example for that.


Let’s create Demo.js component to use HOC.

import React, { Component } from 'react';

class Demo extends Component {


constructor(props) {
super(props);
this.state = {
name: 'React'
};
}

render() {
return (
<div>
<h4>This is demo component</h4>
<h4>Data coming from HOC is : {this.props.data.componentNeme}</h4>
</div>
);
}
}

export default (MyHOC(Demo));

If you have noticed, that we have used “MyHOC” with the wrapped component of Demo, it means we are
sending the Demo component as an argument to the higher-order component.

Now let’s create a HOC called “MyHOC” like this.

function MyHOC(Demo) {
return class extends Component {
constructor() {
super();
this.state = {
componentNeme: 'HOC'
};
}

render() {
return <Demo data={this.state} />
}
}
}
53

Here in MyHOC, we have created a simple function and returning the updated component along with the state
Page

property, so that we can access the HOC state into our Demo component.
Thus at the end, the wrapped component will receive the props from the HOC which can be used for the
rendering purpose.

Q26. Why we should use HOC?


Ans. HOC provides the flexibility to manage the components easily, there are various advantages which are
listed below.

 Maintain re-usability
 Can maintain our codebase in an organized way
 Can remove code redundancy

The goal of this HOC pattern is to decompose the logic into simpler and smaller functions that can be reused.

One of the rules of thumb is a function does just one task and does it well. This also avoids side effects (changing
anything that is not owned by the function) and makes debugging and maintenance a whole lot easier than ever.

Q27. How to render components conditionally?


Ans. Sometimes we may need to render the components conditionally with the use of the component
composition.

Basically, for rendering component, we can make use of && condition or other options as explained below.

 Using && condition

Using && operator, we can render the component like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';
import Success from './Success';
import Error from './Error';

class App extends Component {


constructor() {
super();
this.state = {
name: 'React',
isSuccess: true
};
}

render() {
return (
<div>
<h1>Conditional Component rendering in React</h1><hr />
54

{this.state.isSuccess &&
Page

<Success />
}
</div>
);
}
}

render(<App />, document.getElementById('root'));

 Using ternary operator

By using ternary operator, we can render the component based on if-else condition like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';
import Success from './Success';
import Error from './Error';

class App extends Component {


constructor() {
super();
this.state = {
name: 'React',
isSuccess: true
};
}
render() {
return (
<div>
<h1>Conditional Component rendering in React</h1><hr />
{!this.state.isSuccess ?
<Success /> :
<Error />
}
</div>
);
}
}
render(<App />, document.getElementById('root'));

4
55
Page
State
Q1. What is a State in React?
Ans. The State in React is an instance of the React Component Class and it can be defined as an object of a
set of observable properties that control the behaviour of the component by mutating its value.

State in React is a heart of the application, which is used to maintain the component level data as well as the
global state for the whole application.

The object of the State is mutable in nature it means we can update the state value over the period of time.

The important thing to be noted that the values of the State can be passed from the parent component to a
child for the rendering purpose and parent component can update the state of the child.

Q2. How to declare State in React?


Ans. When we create Stateful or Class-based component, at that time we can use create along with the initial
value like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {


constructor() {
super();
// State object
this.state = {
message: 'Component lifecycle methods in React'
};
}

render() {
return (
<div>
<h3>Hello World</h3>
</div>
);
}
}
56

render(<App />, document.getElementById('root'));


Page
In our App component, we have a constructor () and inside the body, there one object we have created called
“this.state” where ‘this’ keyword referencing the constructor of the same class.

It is the standard way to declare and state throughout the component easily. But do not forget that we cannot
create the state object in functional component, but for the functional component, we can use “Hooks” which is
added as a new feature with the release of React 16.8.

Q3. What is the alternative approach to use State in a Component?


Ans. In the above question, we have used State inside the constructor itself but there is another approach to
use State without Constructor.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {


// State without constructor
state = {
message: 'Component lifecycle methods in React'
};

render() {
return (
<div>
<h3>Hello World</h3>
</div>
);
}
}

render(<App />, document.getElementById('root'));

As you can see that we just have used “state” object without declaring inside the class’s constructor, but don’t
get confused because both approaches generate the same result.

Q4. How to access State values?


Ans. After creating the State object into the Component, we can use it throughout the component, but for
that, we should access it like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';
57

class App extends Component {


Page

// State without constructor


state = {
message: 'Component lifecycle methods in React'
};

render() {
return (
<div>
<h3>Message : {this.state.message}</h3>
</div>
);
}
}

render(<App />, document.getElementById('root'));

If you notice something that inside the render () method, we have accessed the state value and we are going to
its value like this.

<div>
<h3>Message : {this.state.message}</h3>
</div>

Using this.state along with the key name, we can access its value directly, it’s not just limited to the string value
type, we can even access object, array, boolean and number as well.

Q5. How to update State value?


Ans. We know how to declare and assign an initial value to the state, but we may need to mutate the state
value in order to consume it while rendering process.

For that, we can use “setState()” function which accepts the new value and it will be updated into the State
object.

Syntax would be like this.

this.setState({ key: new _value });

Using setState() along with the new value for the specific object, we can mutate the state value, below is the
simple example for that.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';
58

class App extends Component {


constructor() {
Page

super();
// State object
this.state = {
message: 'Component lifecycle methods in React'
};
}

componentDidMount() {
// Updating initial State
this.setState({ message: "Updated Message" });
}

render() {
return (
<div>
<h3>{this.state.message}</h3>
</div>
);
}
}

render(<App />, document.getElementById('root'));

From the constructor(), we have one key called “message” with the default value, but using lifecycle method
componentDidMount(), we are going to update the state value using the below statement.

this.setState({ message: "Updated Message" });

This is how we can update the stateValue using setState() function, but keep in mind that we cannot use the
assignment operator(=) for assigning new state value.

Q6. Why we should not update the State directly in React?


Ans. React uses the Observable object in the form of State and duty of that Observable is to observe against
any changes and reflect it to the original state values.

For example, we have a “message” key in our state and we are trying to assign values directly like this.

componentDidMount() {
// Updating initial State
this.state.message = "Updated Message";
}
Thus the above example works, but if we try to assign the values to the state like this and it may generate some
odd bugs over a period of time and our component may not be easily manageable.
59

So it is always recommended to use the standard method like setState() to avoid the issues while updating the
state values.
Page
Q7. When to use a callback function with State?
Ans. While updating the values of the state, the page gets re-rendered again to reflect its changes to the
DOM.

Sometimes we need to perform the specific operation after updating the state value, so for that, we can even
use callback function like this.

componentDidMount() {
this.setState({ greeting: "Updated Message" }, () => {
// Callback function body
console.log("State Updated")
});
}

For the callback, we have used arrow function In order to print a static message which confirms that our state
value is updated, this is how we can use callback along with the setState() function.

Q8. How to update multiple State values?


Ans. We can mutate state object using setState () function by providing the latest value, but what if we want
to update the multiple state values at a time.

The solution is pretty simple, and it is the same as we do normally like setState () along with the key and value
pair.

Below is the simple example for updating multiple State object values.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {


constructor() {
super();
this.state = {
greeting: 'Hello Foo !!!',
employees: [
{
id: '001',
name: 'Manav'
}
]
};
}
60

componentDidMount() {
Page

this.setState({
greeting: "Updated Message",
employees: [...this.state.employees, { id: '002', name: 'Test' }]
});
}

render() {
return (
<div>
<h3>{this.state.message}</h3>
</div>
);
}
}

render(<App />, document.getElementById('root'));

If you observe, we have one string as a message and an employee array with the single object as an initial state
value.

But now we want to update both of them at the same time, then we can do this via setState() and can provide
the different values to the different state object in order to manipulate the State.

Q9. What is a getInitialState() in React?


Ans. The current version (at the time of writing) of React is 16.8, so in the latest version of React, we can use
“this.state” In order to access the state values as a part of ES6 syntax.

But previously, the state value can be accessible using getInitialState() method like this.

const App = React.createClass({

// To get initial state


getInitialState() {
return {
name: "Hello",
employee: [
"Test 1",
"Test 2",
"Test 3",
]
}
}
})

Q10. How to use State with Higher Order Component?


61

Ans. The state can be used independently for the rendering as well as with Higher Order Component (HOC)
Page

by just providing state object to the HOC like this.


import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import Demo from './Demo';

class App extends Component {


constructor() {
super();
this.state = {
greeting: 'Hello Foo !!!',
};
}

render() {
return (
<div>
// Passing state to HOC
<Demo
greeting={this.state.greeting}
/>
</div>
);
}
}

render(<App />, document.getElementById('root'));

Here in this example, “Demo” is our Higher Order Component, and along with the component, we are going to
state as props value which can be used by the Demo component to manipulate data.

By using this approach by passing state as props to a child makes the code more manageable and effective while
developing a huge application.

5
Props
62
Page
Q1. What is Props in React?
Ans. In React, Props and State is the heart for every application, and Props is same as State but there is some
difference between them.

Props in React is a way to pass the data to the Component which is exactly like the properties that contain the
single value or object as a value.

One of the important point about the Props is that it is “immutable”, means we cannot update it from the
component anyhow, but we can make use of for the rendering purpose.

Q2. How to pass Props from parent to child?


Ans. Props are kind of immutable data as a form of independent or object values, but props can be passed to
the component just like we use property with any HTML elements.

For passing the props to the component, we need to follow camel case standard, and below is the simple
example for that.

import React, { Component } from 'react';


import { render } from 'react-dom';
import Demo from './Demo';
import './style.css';

class App extends Component {

render() {
return (
<div>
<h1>Passing props to Child component in React</h1><hr />
<Demo
// Passing "message" as props
message={this.state.message}
/>
</div>
);
}
}

render(<App />, document.getElementById('root'));

Here in this example, we have an initial state with the key “message” along with the default value.

Now we want to send it to the child component called “Demo” which is a separate component file, so we just
need to provide the property name as “message” or whatever you want to give and we are good to go.
63

This is how we can pass the props to the child component, but we are not limited to send single props at that
time, we can pass as many props as we want.
Page
Q3. How to access the Props value in Component?
Ans. We can pass the props just like we use with the different HTML elements to the component, but using
the Props value is not a complex task.

Below is a simple example to access the props value.

<Demo

// Passing "message" as props

message={this.state.message}

/>

Here “Demo” is the child component from where we are passing the props value, and below is the Demo.js file
from where we are going to access the Props value.

import React, { Component } from 'react';

class Demo extends Component {


render() {
const { message } = this.props;
return (
<div>
<h3>This is Demo Component : {message}</h3>
</div>
);
}
}

export default Demo;

One thing to keep in mind that if we want to use the props value throughout the component, then there is one
object which maintains all the props coming from the different component which is “this.props”.

And if we want to access any key from the Props object we can use this format.

this.props.props_name

Thus “this.props” can be accessed anywhere in a component, not just the string, number, boolean but we can
also access the methods/function.

Q4. How to pass Props to the Stateless function?


Ans. The stateless function does not support state (Hooks can) but it supports the Props to be used inside the
function body.
64

// Getting props from component


function Demo(props) {
Page

return <div>
<h3>{props.message}</h3>
</div>;
}

The demo is a function along with the props as an argument, so when we try to access the complete props
object and we get to know to about their values and we can use it for the rendering just like we did in above
example.

Q5. How to pass a complete object as Props to the Component?


Ans. Props can be passed to the component in any form like string, number, boolean, array and even whole
object as a value.

Passing object to the child component is not a different thing, it is just like we do with the single value.

Below is the simple example to pass props as object.

import React, { Component } from 'react';


import { render } from 'react-dom';
import Employee from './Employee';
import './style.css';

class App extends Component {


constructor() {
super();
this.state = {
employee: {
name: "Manav Pandya",
qualification: "M.C.A"
}
};
}

render() {
return (
<div>
{/* Passing complete Props object */}
<Employee employeeDetail={this.state.employee} />
</div>
);
}
}

render(<App />, document.getElementById('root'));


65

In State object, we have separate object “employee” which contains the basic detail about the single employee.
Page
And from the App to Employee component, we can pass the object as props just like we did in above example
called “employeeDetail” and the same way we can access it from the child component like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class Employee extends Component {


render() {
const { employeeDetail } = this.props;
return (
<div>
Employee Name : <strong>{employeeDetail.name}</strong><br />
Employee Qualification : <strong>{employeeDetail.qualification}</strong>
</div>
);
}
}

export default Employee;

Q6. How to provide default values to the Props in React?


Ans. Unlike State, props cannot initialize from the constructor, thus we can provide the default props values
in React.

We can provide default values to the Props using “defaultProps” which is just like validation because if we pass
props to the child but it does not contain any value then we may have errors in a form of undefined or null.

Every component can have “defaultProps” to have the initial value as Props, below is the simple example for the
same.

import React, { Component } from 'react';


import { render } from 'react-dom';

class App extends Component {

render() {
// Using defaultProps
const { appName, demoName } = this.props;
return (
<div>
<div>Component Name : <strong>{appName}</strong></div>
<div>Demo Name : <strong>{demoName}</strong></div>
</div>
66

);
Page

}
}

// Defined default props for App component


App.defaultProps = {
appName: "App Component",
demoName: "Default props in React"
}

render(<App />, document.getElementById('root'));

Inside the render() method, we are trying to access “this.props” for the key appName and demoName, but what
are we don’t have values in these properties.

Than defaultProps comes into the picture which allows us to provide default values to the Props like this.

App.defaultProps = {
appName: "App Component",
demoName: "Default props in React"
}

Here “App” is our component name, and inside the defaultProps object, we have a list of Props along with the
default value.

Q7. What is an alternative way to use default props?


Ans. We can provide a default value to the defaultProps outside the class body, but we can also define
defaultProps as a static context just like this.

import React, { Component } from 'react';


import { render } from 'react-dom';

class App extends Component {

// using static context


static defaultProps = {
appName: "App Component",
demoName: "Default props in React"
}

render() {
const { appName, demoName } = this.props;
return (
<div>
<div>Component Name : <strong>{appName}</strong></div>
67

<div>Demo Name : <strong>{demoName}</strong></div>


</div>
Page
);
}
}

render(<App />, document.getElementById('root'));

From the class body of App component, we have defined the defaultProps as the static context, it means our
props values do not hold the initial/default value.

There is no difference between those two approaches, but this example follows the ES6 class syntax to have
static context.

Q8. How to provide the default types of Props?


Ans. Sometimes we may need to validate the type of props being used otherwise we won’t be able to render
it conditionally into the DOM.

Validating these props types called “type-checking” it means we need to validate against its type of data being
used in the component.

For type checking, we can use a third-party library called “prop-types” which contains the different types of
data-types such as string, number, array, object, symbol and so on.

To use the prop-types library, we need to install it using below command.

npm Install prop-types

After installing the package, we can import and use it in our react app like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import PropTypes from 'prop-types';

class App extends Component {

render() {
const { appName, demoName } = this.props;
return (
<div>
<div>Component Name : <strong>{appName}</strong></div>
<div>Demo Name : <strong>{demoName}</strong></div>
</div>
);
}
}
68

// Defined default props for App component


App.defaultProps = {
Page

appName: "App Component",


demoName: "Default props in React"
}

//Defined props type for App component


App.propTypes = {
appName: PropTypes.string,
demoName: PropTypes.string
}

render(<App />, document.getElementById('root'));

In this example, one thing to be noticed is “App.propTypes”.

App.propTypes = {
appName: PropTypes.string,
demoName: PropTypes.string
}

By using the term “propTypes”, we are going to define a type of props going to be used in component, so that
the value should follow the pre-defined type of props.

And if we failed to follow any of them, then we can have error into the console like this.

As you can see we got an error that its invalid prop types because it was expected as a string but got number
from the defaultProps like this.

App.defaultProps = {
appName: 25,
demoName: "Default props in React"
}

This is how prop-types make sure that we are using a valid type of props being passed to the defaultProps.

Q9. How many prop types are supported in React?


Ans. The package called “prop-types” comes with tons of propsTypes, but let’s see the few commonly used
propTypes in React for type-checking.
69

 optionalArray: PropTypes.array
Page

 optionalBool: PropTypes.bool
 optionalFunc: PropTypes.func
 optionalNumber: PropTypes.number
 optionalObject: PropTypes.object
 optionalString: PropTypes.string
 optionalSymbol: PropTypes.symbol
 optionalElement: PropTypes.element
 optionalMessage: PropTypes.instanceOf(Message)
 optionalUnion: PropTypes.oneOfType([

PropTypes.string,

PropTypes.number,

PropTypes.instanceOf(Message)

])

 requiredFunc: PropTypes.func.isRequired

Q10. How to use defaultProps in Stateless/Functional component?


Ans. ES6 class syntax supports the defaultProps to be used, but same way, we can also use defaultProps in
Function component like this.

import React from 'react';

function Employee(props) {

return (
<div>
<div>Component Name : <strong>{props.appName}</strong></div>
<div>Demo Name : <strong>{props.demoName}</strong></div>
</div>
)

Employee.defaultProps = {
appName: "Manav Pandya",
demoName: "Default props in React"
}

export default Employee

Here in Function component, we can use defaultProps just like we do in Stateful component.
70

Q11. What is a render prop in React?


Page

Ans. As per the official definition.


“The term “render prop” refers to a technique for sharing code between React components using a prop whose
value is a function”

In other words, we can say that render props is a function prop that a child component uses to know what to
render.

Let’s see an example in which we will use render props to render the component by using “render” function and
then we will use props to render the data.

import React, { Component } from 'react';


import { render } from 'react-dom';
import Demo from './Demo';
import './style.css';

// Child component
class Demo extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}

render() {
return (
<div>
<h3>{this.props.render(this.state)}</h3>
</div>
);
}
}

class App extends Component {

render() {
return (
<div>
{/* Using render function */}
<Demo render={data => (
<h1>Hello {data.name}</h1>
)} />
</div>
);
}
71

}
Page
render(<App />, document.getElementById('root'));

Here in this example, “Demo” is our child component and inside the render() function, we are getting “render”
as function, and using that function we are passing state as value to the parent component.

From our App component, Demo component uses “render” as a function, which renders the HTML content.

This is also called “child as a function” because it uses render as a function which renders the content of the
child from the parent itself.

So by using such implementation, we can convert our any HOC with the regular component with render props.

Q12. What is the Difference between State and Props?


Ans.

State Props
Mutable in nature Immutable in nature
Can pass props from child to parent, and parent
Can pass state from parent to child component
to child component
The state can initialize in the constructor of the Props cannot initialize in the constructor but can
class do using defaultProps
Props can be created using Stateful and Stateless
It can be created and used in Stateful component
component
The local state will be limited to a single Props can be used and passed to any child
component only component

6
Forms
Q1. What are the Forms in React?
Ans. Getting user input is common while working with the web app development, same way we can use
72

Forms in React but Forms in react can be used differently because input elements act differently.
Page
There is no in-built support for managing forms in React just like we do in Angular, we have to do manually
everything for the form configuration in React.

There are different methods and libraries out there to help with this but if you are like me that hates dependent
on too many libraries, so we can make use of the best library out there in order to work with Forms in React.

Q2. How many types of Form input are supported?


Ans. Forms in React is completely different than other libraries or frameworks, here In React, we need to
manage everything from scratch like creating forms, validations and so on.

There are two types of Form input are supported which are listed below.

 Controlled form inputs


 Uncontrolled form inputs

Q3. What are Controlled inputs in React?


Ans. Controlled component are the suitable type of component which uses internal state to maintain form
inputs like <input>, <select>, <textarea> and so on.

Controlled form inputs value can be maintained using internal component state, and can be updated using
method setState() to reflect original state value.

import React, { Component } from 'react';


import { render } from 'react-dom';
import './style.css';

class App extends Component {


constructor() {
super();
this.state = {
inputVal: ''
};
}

inputChange(event) {
this.setState({ inputVal: event.target.value })
}

render() {
return (
<div>
<h1>Controlled input in React</h1><hr />
Enter Name : <input type='text' onChange={(event) => this.inputChange(event)}
value={this.state.inputVal} />
73

</div>
);
Page
}
}

render(<App />, document.getElementById('root'));

The text input contains the “onChange ()” event and “value” attribute in order to render the value.

Since “this.state.inputVal” is the part of the component state, so whenever the value of the state changes, it will
be reflected in the actual state value.

Input control value will be changed after every keystroke, and the new value will always be set to the state like
this.

inputChange(event) {
this.setState({ inputVal: event.target.value })
}

So that we can have complete control over an input which makes it easy to use and more manageable for the
data validation.

Q4. What is Uncontrolled input in React?


Ans. Uncontrolled input is completely a different approach than Controlled input where we are not using
local component state but using “input ref”.

It is the same what we use normally in HTML form where we need to get the values as user type, but here in
React, we use “ref” in order to get the various inputs value.

Below is the simple example to get the user input using “refs”.

import React, { Component } from 'react';


import { render } from 'react-dom';

class Uncontrolled extends Component {


constructor() {
super();
this.myinput = React.createRef();
}

onsubmit(event) {
console.log(this.myinput.current.value);
event.preventDefault();
}

render() {
return (
74

<div>
Page

<h1>Uncontrolled Component in React</h1><hr />


Enter Name : <input type='text' ref={this.myinput} /><br />
<button onClick={(event) => this.onsubmit(event)}>Submit</button>
</div>
);
}
}
export default Uncontrolled;

If you notice that, with the <input> element, we do not use the “onChange” event and “value” attribute.

But we have used “ref=(this.myinput)” because it allows us to get the reference of the element and manage the
elements value programmatically, for example, doing actions on input like manage focus, blur, change event, etc.

But still, we can manage forms with Uncontrolled input for a quick start, for the better form configuration we
should use controlled input controls.

Q5. How to manage file input type using uncontrolled input?


Ans. File uploading is also essential while working with web app development in order to upload documents
like images, documents and so on.

The input file type will use JavaScript’s FILE API in order to upload the documents to the server easily.

Let’s see a simple example where we upload the file and get the information about the file.

import React, { Component } from 'react';

class FileInput extends Component {


constructor() {
super();
this.myFile = React.createRef();
}

onsubmit(event) {
console.log(this.myFile.current.files[0].name);
console.log(this.myFile.current.files[0].size);
console.log(this.myFile.current.files[0].type);
}

render() {
return (
<div>
<input type="file" ref={this.myFile} />
<button onClick={(event) => this.onsubmit(event)}>Submit</button>
</div>
75

);
}
Page

}
export default FileInput;

Along with the file type, we have used the “ref” attribute which gets the input reference of the file.

When we click on the submit button, the different number of items we are getting are like name of file, size and
the type of document being submitted.

After running the example, we can see output like this.

Q6. What is createRef in React?


Ans. Ref is used to attaching it with the different HTML element as an attribute and it is used to holds the
reference of the element.

Once we create the “ref” of an element inside the constructor, we can use it throughout the component in order
to get the values of the element.

import React, { Component } from 'react';

class SimpleRef extends Component {


constructor() {
super();
this.myLabel = React.createRef();
}

render() {
return (
<div>
<label ref={this.myLabel}></label>
</div>
);
}
}

export default SimpleRef;

In this example, we have label element and using “ref” attribute, we have attached the element with the
reference “this.myLabel”.
76

Now after initializing ref. we can use the same ref anywhere in the existing component.
Page
Q7. How to access ref in React?
Ans. After creating the ref from the constructor, now we may have a question that how to access it.

Accessing the ref is pretty straight forward, and we can access it like this.

this.myRef.current

Here myRef is the name of ref and “current” points to the existing node/element where we have attached our
ref attribute.

This is how we can access the different “ref” of the elements and can perform a various task based on the type
of input being used.

Q8. How to pass callback ref between the Components?


Ans. We can also use ref along with the callback in React, which allow us to manage the ref easily within the
same component in order to get the value of the element.

To provide the callback as ref to the child component, we can use arrow function in order to pass the ref to the
child and the child component will get the ref as props like this.

render() {
return (
<div>
<ChildComponent inputRef={el => this.myInput = el} />
</div>
);
}

As you can see, we have sent the attribute “inputRef” to the child as “this.myInput” which we have created into
the parent component.

But from child component, we will get the ref as props like this.

render() {
return (
<div>
<input type="text" ref={this.props.inputRef} />
</div>
);
}

Using props, we can get the ref object like this, and this is how we can share the “ref” between the components
but keep in mind that it is good to have ref in the parent so that we can access the child node from the parent
component.
77
Page
Q9. What is the defaultValue attribute in React?
Ans. Normally we use the value attribute to provide the default value to the input control of HTML, but here
in React, the value attribute will be overridden in the HTML DOM.

For providing the initial value to the uncontrolled input element, we can use the “defaultValue” attribute like
this.

render() {
return (
<div>
<form onSubmit={this.submitContact}>
<label>
First Name :
<input
defaultValue="Manav"
type="text"
ref={this.fName} />
</label>
<label>
Last Name :
<input
defaultValue="Pandya"
type="text"
ref={this.lName} />
</label>
<input type="submit" value="SUBMIT" />
</form>
</div>
);
}

After using the “defaultValue” attribute, now we will be able to provide initial or default value to the input
controls, and most of the time default value will be based on the component state.

Q10. How to handle multiple inputs in React?


Ans. While working with the controlled input elements, it may possible that we need to use multiple input
controls in a form.

As we know controlled input is based on the component state, then how to manage the state values for the
multiple inputs.

Basically, the controlled inputs must have a “name” attribute to identify every input unique, and based on the
input control name, we can set the state with the dynamic values of the input controls.
78

Below is the simple example for handling multiple form inputs.


Page
import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {

onInputChange(event) {
this.setState({ [event.target.name]: event.target.value });
}

render() {
console.log(this.state)
return (
<div>
<label>First Name :</label>
<input type="text" name="fname" onChange={(event) => this.onInputChange(event)}
/><br />

<label>Last Name :</label>


<input type="text" name="lname" onChange={(event) => this.onInputChange(event)}
/><br />

<label>Email :</label>
<input type="text" name="email" onChange={(event) => this.onInputChange(event)}
/><br />

<label>Password :</label>
<input type="password" name="password" onChange={(event) =>
this.onInputChange(event)} />
</div>
);
}
}

render(<App />, document.getElementById('root'));

Here in this example, we have simple form controls for the First name, Last name, Email, and password.

We should notice two things in form controls like.

 Name attribute
 OnChange() event

It means when we change the text of the input, it continuously calls the action method called “onInputChange()”
which sets the state value based on the name of element and value entered by the end-user.
79

onInputChange(event) {
Page

this.setState({ [event.target.name]: event.target.value });


}

On every keystroke, the value of the input control will be updated into the state and will get the output like this
at the end.

7
Event Handling
Q1. What is Event in React?
Ans. While working on Web development, Event handling is always a crucial part to perform some actions
80

based on user interaction.


Page
Events in React works the same as we do with the HTML controls but there is some difference over HTML DOM
events such as.

 To use event with the element, the name of the event should be in camelCase
 We should pass the event handler rather than function and not in the form of string

Q2. How to attach an event handler with an element?


Ans. We can attach the event handler to the different elements like button, select, radio button, checkbox
and so on.

And for attaching the handler, we can use the name of the event followed by the event handler name like this.

event_name = {this.eventHandlerName}

Q3. How to attach an event handler to the button element?


Ans. The button is the primary way to submit the form or perform some specific operation based on the click
event.

In order to perform click event, we can use “onClick” event along with the event handler function like this.

import React, { Component } from 'react';


import { render } from 'react-dom';

class App extends Component {

onButtonClick() {
console.log("Button Clicked")
}

render() {
return (
<div>
<button type='button' onClick={(event) => this.onButtonClick(event)}>
Submit
</button>
</div>
);
}
}

render(<App />, document.getElementById('root'));

As you can see that we have one <button> element, and based on the click event, we have attached the event
handler function called “onButtonClick()”.
81

So whenever the user clicks on the button, the specific action will be done by the caller function body.
Page
Q4. How to prevent default behaviour in React?
Ans. Sometimes it may happen that some events may behave inappropriately due to certain reason.

In order to prevent such unexpected behaviour, we should call the function.

preventDefault ()

Because unlike JavaScript, we cannot return “false” in order to prevent the default behaviour. Below is the
simple example to preventDefault in React.

onButtonClick(event) {
event.preventDefault();
console.log("Button Clicked")
}

Q5. How to use multiple event handlers in React?


Ans. In React, JSX may contain multiple event handlers in order to perform different events for a specific
purpose.

We need to use multiple handlers if the element requires multiple actions to be taken based on the expected
behaviour, for example, we have one input and needs to manage “onChange()” and “onBlur()” events at a time.

Below example demonstrate the example using multiple event handlers.

import React, { Component } from 'react';

class MultipleEvents extends Component {

onChange(event) {
event.preventDefault();
console.log(event.target.value)
}

onBlur(event) {
event.preventDefault();
console.log(event.target.value)
}

render() {
return (
<div>
<input onChange={this.onChange} onBlur={this.onBlur} />
</div>
);
}
82

}
Page
export default MultipleEvents;

Here in this example, we have one <input> control and we need to manage two different events on a single
input.

 onChange()
 onBlur()

For that, we have attached two different event handler, and when we change the values, it will be reflected in
the browser console with the updated values entered by the user.

Q6. How to pass arguments to the event handlers in React?


Ans. In React, with the different event handlers, we can pass the arguments as well.

Passing arguments to the event handlers is a very common thing in order to play around some pre-defined
values to be compared and used with the external data.

For example, when the user clicks on the edit button, we need to pass the selected user id along with the
handler function.

import React, { Component } from 'react';

class EventArguments extends Component {

onBlur(id, event) {
event.preventDefault();
console.log("ID Is :", id)
}

render() {
return (
<div>
<input onBlur={(event) => this.onBlur('001', event)} />
</div>
);
}
}

export default EventArguments;

Here in this example, along with the <input> control, we have attached the event handler called “onBlur()” but
we have also provided an additional argument as a string which can be passed to the actual event function.

onBlur(id, event) {
83

event.preventDefault();
console.log("ID Is :", id)
Page

}
This is how we can pass and get the value of arguments into the event handler function.

Q7. How to pass the event handler function as props?


Ans. After creating the event handler function, if we want to use the same event handler function into our
child component then we can pass it as props to the child component.

In order to pass the function, we can just create the argument with the child component and can assign it to the
existing event handler like this.

import React, { Component } from 'react';


import { render } from 'react-dom';
import EventArguments from './EventArguments';

class App extends Component {

onButtonClick(event) {
event.preventDefault();
console.log("Button Clicked")
}

render() {
return (
<div>
<EventArguments
onButtonClick={this.onButtonClick}
/>
</div>
);
}
}

render(<App />, document.getElementById('root'));

The event handler function called “onButtonClick()” is passed to the child component by using the attribute
“onButtonClick” and after declaring the attribute, we can assign our function to it.

By using this approach, we can easily manage parent-child communication via event handling.

Q8. How to access events coming from props in React?


Ans. As we know, we can pass the event handler function to the child via attribute and it can be accessible to
the child as a form of props like this.

this.props.event_name();
84

Just like we access different props coming from the parent component, we can easily access the event handler
Page

function from the parent component into the child like this.
import React, { Component } from 'react';

class EventArguments extends Component {

render() {
// Accessing event handler from props
const { onButtonClick } = this.props;

return (
<div>
<input onBlur={onButtonClick} />
</div>
);
}
}

export default EventArguments;

This is how we have accessed the event handler function coming from the parent component, and when we blur
from the input control, the event handler function will be executed from the parent component.

Q9. How to assign events using the bind method?


Ans. We can assign an event handler to the element using bind() method which is used to call a function with
this value set explicitly. In other words, bind () allows us to easily set which specific object will be bound
to this when a function or method is invoked at a time.

The need for bind usually occurs when we use the “this” keyword in a method and we call that method from a
receiver object in order to assign or call a function.

import React, { Component } from 'react';

class EventArguments extends Component {


onBlur(id, event) {
event.preventDefault();
console.log("ID Is :", id)
}
render() {
return (
<div>
<input onBlur={this.onBlur.bind(this, '001', event)} />
</div>
);
85

}
}
Page
export default EventArguments;

Using onBlur event type, we have attached the event handler function called “onBlur()” but we have also
provided the additional argument “this” which keeps the reference of the component handler function.

Q10. How to assign events using the arrow function?


Ans. An arrow function is introduced in ES6 and it is a great alternative for the bind() method to attach the
event handler.

import React, { Component } from 'react';

class EventArguments extends Component {


onBlur(id, event) {
event.preventDefault();
console.log("ID Is :", id)
}
render() {
return (
<div>
<input onBlur={(event) => this.onBlur('001', event)} />
</div>
);
}
}
export default EventArguments;

As you can see into the above example, we have used arrow function, and by using this function it will attach the
event handler only if we have used “babel” with the property initializing syntax.

8
Conditional Rendering
Q1. What is Conditional Rendering in React?
Ans. Conditional Rendering is an important part while working with the web application because conditional
86

rendering decides which component or element to be rendered based on several conditions.


Page
It’s always handy when we load the different components and DOM elements based on the specific condition so
if the condition fails then we can load the default element to show the specific message to the end-user.

In React, conditional rendering works the same as we do in JavaScript, but here in React, we can make use of
state and props value in order to load the elements conditionally and render the UI.

Q2. How to render element based on if-else in React?


Ans. To rendering element conditionally based on if-else, we can just provide the appropriate condition and
then can return element based on condition result.

For example, we have two different messages and want to show the message based on the state value like this.

renderMessage() {

// Rendering element based on if-else

if (this.state.isVisible) {

return (<h3>Hello World is Visible</h3>)

else {

return (<h3>Hello World is Not Visible</h3>)

As you can see that we have used if-else but for the condition, “isVisible” hold the oolean value as true, and
let’s use this function inside render() function like this.

Render() {
return (
<div>
{this.renderMessage()}
</div>
);
}

After using the function renderMessage(), the function triggers the if condition and based on the result the
appropriate element will be rendered.

Q3. How to render component conditionally using if-else in React?


Ans. Same as we render elements conditionally using if-else statement, we can also render component
dynamically using the if-else statement.
87

renderComponent() {
Page
// Rendering component conditionally
if (!this.state.isSuccess) {
return <SuccessComponent />
}
else {
return <ErrorComponent />
}
}

Here we have two different components i.e.:

 Success component
 Error component

So based on the state value “isSuccess”, the component will be rendered inside the return () after calling this
function like this.
Render() {
return (
<div>
{this.renderComponent()}
</div>
);
}

Q4. How to use ternary operator for rendering element in React?


Ans. To render the element or component conditionally, we can use the ternary operator as an alternative to
the if-else statement.

Ternary operator makes easy to use an if-else statement like this.

Render() {
return (
<div>
{this.state.isSuccess ?
<SuccessComponent /> :
<ErrorComponent />
}
</div>
);
88

}
Page
This is how we can use the ternary operator in order to load the component dynamically based on the specific
condition.

Q5. How to render element or component using && condition in React?


Ans. Sometimes it may possible that we want to render the component or element if condition returns to
true or don’t render the element or component.

It uses logical operator && in order to render component if the condition evaluates to the true or matched like
this example.

Render() {
return (
<div>
{this.state.isSuccess &&
<SuccessComponent />
}
</div>
);
}

Q6. How to render the element/content using switch case?


Ans. We can try different conditional rendering mechanism like if-else, ternary condition, using logical &&
operator and so on.

Apart from the above methods, we can use a switch case in order to render the element based on the condition
like this.

Import React, { Component } from ‘react’;

class SwitchCase extends Component {


constructor() {
super();
this.state = {
status: ‘second’
};
}

renderContent() {
switch (this.state.status) {
case ‘first’:
return <h1>You got first class</h1>;
case ‘second’:
return <h1>You got second class</h1>;
case ‘third’:
89

return <h1>You got third class</h1>;


Page

default:
return null;
}
}

render() {
return (
<div>
{this.renderContent()}
</div>
);
}
}
export default SwitchCase;

In the above example, we have simple string value in the state and based on the same value, we want to print
some message into the DOM.

For that, we have used switch case mechanism, so based on the value from the state, it will find the matching
case from the available cases and render the output using render ().

Q7. How to use nested conditional rendering in React?


Ans. Sometimes it may possible that we need to render the element with the nested conditions.

And for implementing such, we can use nesting conditional rendering using a ternary condition like this.
Render() {
return (
<div>
{condition-1
? <Component-1 />
: (condition-2
? <Component-2 />
: (condition-3
? <Component-3 />
: <Component-4 />
)
)
}
90

</div>
Page

);
}

We have used nested ternary condition here in this example, thus it may possible that it becomes more complex
over some period of time and we cannot manage it.

In this case, we can use different other scenarios for the conditional rendering of the element or component.

Q8. How to prevent component being rendered?


Ans. While rendering the component or element, it may possible that we get the null or undefined values
what we get via props or state.

In this case, we can always be strict about their values and can prevent the element for the rendering like this.

Render() {
return (
<div>
{!this.state.isSuccess ?
<SuccessComponent /> :
null
}
</div>
);
}

Here in this example, we are trying to load the component conditionally based on the state value, and if the
state contains the false as value than we should not render the component.

For that we can just return “null” and our component won’t render into the DOM, this is how we can prevent
the element or component being rendered.

9
Routing
Q1. What is Routing in React?
Ans. Routing is one of the key aspects while working in web application development, and using Routing we
can achieve Single Page Application (SPA) at the most.
91

React does not have an internal package for managing Routing, thus there are tons of the libraries are available
in order to implement Routing in React.
Page
Routing makes easier to switch the web pages available in the application and load the appropriate UI.

Q2. What are different libraries available to implement routing in React?


Ans. There are tons of routing libraries are available which are listed below:

 react-router
 Reach Router
 react-router-component
 Backbone
 component-router
 Aviator
 Director
 Finch
 mvc-router
 react-mini-router
 react-passage

Q3. How to implement Routing in React?


Ans. As we discussed earlier, React does not have its own library for managing Routing, thus we have a
different number of libraries are available and using it we can implement end to end routing configuration.

And one of the popular libraries among others is “react-router-dom” which is a widely used library to use
Routing in react.

For that, we need to install the package using below command after creating the React app.

npm install react-router-dom

After installing the above package, now we are good to go with the Routing in React.

Q4. What is react-router-dom?


Ans. The react-router-dom is a library which is used to implement web app based routing functionality.

Previously it was called “react-router” but now it’s split into the three different packages which are listed below.

 react-router-dom

Used for implementing web application based routing

 react-router-native

Used for implementing routing only for mobile application (i.e. React Native)

 react-router-core(deprecated)

It is used to implementing core routing mechanism anywhere for the core React application
92
Page
Q5. How to implement basic routing in React?
Ans. To configure Routing, we need to provide some links and other configuration like the list of routes in
order to switch between the pages.

After installing react-router-dom, now we can implement basic routing like this example where we will create
three different pages like Home, About and Contact page.

Class Home extends Component {


render() {
return <h3>This is Home component</h3>
}
}

class About extends Component {


render() {
return <h3>This is About component</h3>
}
}

class Contact extends Component {


render() {
return <h3>This is Contact component</h3>
}
}

We have created three different classes in order to implement Routing and can see that we are switching
between the components.

Next important thing is to import the related options required for Routing from react-router-dom like this.

Import { BrowserRouter as Router, Route, Link } from “react-router-dom”;

After importing such options, now we can create different navigation links like this with the complete example.

Class App extends Component {

render() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to=”/”>Home</Link>
93

</li>
<li>
Page

<Link to=”/about/”>About</Link>
</li>
<li>
<Link to=”/contact/”>Contact</Link>
</li>
</ul>
</nav>

<Route path=”/” exact component={Home} />


<Route path=”/about/” component={About} />
<Route path=”/contact/” component={Contact} />
</div>
</Router>
);
}
}

render(<App />, document.getElementById(‘root’));

Here we have created three different links for the navigation for all the components Home, About and Contact.

Along with the navigation links, we have also configured Routes for the component, and the matching Route will
be loaded with the appropriate component as we did in the above example.

Q6. What is <Link> in React Router?


Ans. As per the official definition.

“Provides declarative, accessible navigation around your application”

The link provides the easiest approach to configure navigation link based on the route prefix, and the matched
component will be rendered.

Link contains a number of attributes to simplify the link configuration like this.

 to

Represent the string, which is used to locate the link to where we are going to relocate from an existing
location

 pathname

The string which represents the exact route prefix/value of the link

 search

Used to specify the different search parameters along with the link

 hash
94

If we need to use a hash parameter than we can use it over here


Page
 state

Value of state for persisting the location

Below is the simple example for the <Link>.

<Link
to={{
pathname: “/employees”,
search: “?name=Manav”,
hash: “#first-page”,
state: { isFound: true }
}}
/>

Q7. What is <Route> in React Router?


Ans. The route is the separate collection of routes which contains the value for the route prefix and if
matches with the link then it will render the Component provided with the Route configuration.

Below is a simple example that shows how to create <Route>.

<Route
path=”/” // string path value
exact // to match the exact string prefix
component={Home} // Load the component if matches route
/>

This is the basic configuration for the <Route>, thus we can provide the options we want like we can ignore the
“exact” attribute if we don’t want to match the exact route.

Q8. How to configure Route prefix in React?


Ans. Route prefix plays an important role when we have the initial prefix in API endpoint collection like this.

Localhost:4000/api/employee

In that case, we have “app” as a prefix when we call the API all the time, so for that, we can configure the route
prefix like this.

<Route component={App} path=”app”>


<Route path=”/” exact component={Home} />
<Route path=”/about/” component={About} />
<Route path=”/contact/” component={Contact} />
</Route>

Here in the above example, we have our root component “App” along with with the path “app”, which initiate
95

the parent-child nested routing.


Page
Q9. How many Route render methods are supported?
Ans. Primarily, there are three types of Route render methods are supported which are listed below.

 <Route component>
 <Route children>
 <Route render>

These methods are used in different situation for example while implementing nested routing and so on.

Q10. What is <Router> in React Router?


Ans. The <Router> is parent API which contains the implementation of other high-level router components
which are listed below.

 <BrowserRouter>
 <StaticRouter>
 <MemoryRouter>
 <NativeRouter>
 <HashRouter>

The <Router> contains the list of Route to be rendered based on the matching route-prefix string, and allow us
to switch between the pages.

Q11. What is <Switch> in React Router?


Ans. The <Switch> is used to load the different Routes exclusively because if we have the Routes defined
without <Switch> then other routes may render due to various reason.

For example, we have three different components like Home, About and Contact than we can provide the route
setting like this.

<Route path=”/” exact component={Home} />


<Route path=”/about/” component={About} />
<Route path=”/contact/” component={Contact} />

But the problem with the above configuration is that it renders all the component however because it matches
with the path, thus alternatively we can use <Switch> to avoid this confusion.

Import the switch from react-router-dom like this.

Import { BrowserRouter as Router, Route, Link, Switch } from “react-router-dom”;

And the Route configuration will look like this.

<Switch>
<Route path=”/” exact component={Home} />
<Route path=”/about/” component={About} />
96

<Route path=”/contact/” component={Contact} />


</Switch>
Page
After this configuration, the Router only render the single page which matches with the route-prefix and ignores
other components being rendered incorrectly.

Q12. What is <BrowserRouter> in React Router?


Ans. The <BrowserRouter> is usually given an alias of ‘Router’ and this is the parent component that is used
to store the all of your <Route> components

It contains the list of different <Route> which tells which component to be loaded when the URL matches with
the route-prefix.

Below is a simple example of that.

Import { BrowserRouter as Router, Route } from “react-router-dom”;

<Route component={App} path=”app”>


<Route path=”/” exact component={Home} />
<Route path=”/about/” component={About} />
<Route path=”/contact/” component={Contact} />
</Route>

Q13. How to identify activated link in React Router?


Ans. Sometimes we need to show the user that which link they have clicked, and for that, we need to make it
unique amongst other links.

For that, we can use additional <NavLink> which is a special version of <Link> which allow us to configure styling
attribute for the navigational links.

Below is a simple example to give a class name to the activated link.

<ul>
<li>
<NavLink activeClassName=”activeLink” to=”/”>Home</NavLink>
</li>
<li>
<NavLink activeClassName=”activeLink” to=”/about/”>About</NavLink>
</li>
<li>
<NavLink activeClassName=”activeLink” to=”/contact/”>Contact</NavLink>
</li>
</ul>

Now when we click on any link, we can see that the activated link’s color has changed now.

Q14. How to provide styles to activated link in React?


97

Ans. Using <NavLink> we can provide the style class and also it supports the inline styles as well like this.
Page

<ul>
<li>
<NavLink activeStyle={{
fontWeight: “bold”,
color: “red”
}} to=”/”>Home</NavLink>
</li>
<li>
<NavLink activeStyle={{
fontWeight: “bold”,
color: “red”
}} to=”/about/”>About</NavLink>
</li>
<li>
<NavLink activeStyle={{
fontWeight: “bold”,
color: “red”
}} to=”/contact/”>Contact</NavLink>
</li>
</ul>

As you can see that we have provided inbuilt style attribute called “activeStyle” which provides the styles to the
activated links.

Q15. How to pass route parameters in React Router?


Ans. We often need to pass the different numbers of router parameter with the primary route for a different
reason.

For that we can pass the different optional parameters along with the route like this.

<Route path=”/” exact component={Home} />


<Route path=”/about/” component={About} />
<Route path=”/contact/:id” component={Contact} />

We have used optional parameter “: id” it means the Contact component may contain the additional argument
along with the URL.

After providing the route parameter, we can get the parameter from the component like this.

Class Contact extends Component {


render() {
console.log(this.props.match.params)
return <h3>This is Contact component</h3>
}
}
98
Page
Q16. What is the Location object in React Router?
Ans. Location Object contains complete information about the existing page like where you are and where to
go.

The location object holds a different value which looks like this.

pathname: ‘/your_path’

search: ‘?id=001’,

hash: ‘#page-first’,

state: {

[isSuccess]: true

This object contains different information like the pathname for the existing page location, the search string, the
hash part, and the state for the location.

Q17. What is match object in React Router?


Ans. Match object in React Router contains the information about the matching Route with the current URL
being used.

It contains the number of properties which are listed below.

 params

Contains the list of key-value pair of parameters passed along with the URL

 Path

It is the path what we have used to match the route pattern

 url

Contains the whole matched route path for the existing route

 isExact

It is a boolean value that compares the current URL and actual route and returns the result.

The complete match object can look like this.


99
Page
Q18. What is matchPath in React Router?
Ans. A match object contains the basic details about the matched path information like params, URL, isExact
in order to get the matching properties, the same way “matchPath” is used to compare the path for the exact
path comparison.

The matchPath return the same match object, but it is the special form of match object which allows us to
compare the URL and gathering information before rendering on the server.

For example, we have below URL and we are matching the URL with the correct route.

Localhost:4000/contact/25

And our matchPath condition is.

Const match = matchPath(“/contact/25”, {

path: “/contact/:id”,

exact: true,

strict: false

});

This is how we have used matchPath () method, and along with the method, we have provided some properties
to compare the existing URL with the expected route URL.

So after running the above example, we can see the match object like this.
100
Page
The output shows that our existing URL matches with the expected URL like localhost: 4000/contact/25, thus it
returns “isExact” to true.

Q19. What is withRouter in React Router?


Ans. The withRouter is a Higher Order Component (HOC) which is used to access the history object and other
information like this.

 History object
 Match object
 Location object

To get all above object information, we just need to surround withRouter followed by the component name like
this.

Export default withRouter(component_name);

Below is the simple example using withRouter and the component name, which print the simple props of the
different objects.

Import React, { Component } from ‘react’;


import { withRouter } from “react-router-dom”;

class WithRouterDemo extends Component {

render() {
console.log(this.props)
return (
<div>
This is withRouter demo
</div>
);
}
}

// Using withRouter
101

export default withRouter(WithRouterDemo);


Page

And after running this example, we can get the complete object information like this.
Q20. What is the history object in React Router?
Ans. While working with the web app, we often create the history which uses HTML5 History API to contain
the information about the history what user have created.

The history also refers to other terms like.

 Memory history
 Browser history
 Hash history

History object contains the different properties and methods which are listed below.

 length :

It returns the total count of entries created into the history stack
 action :

This is the string which represents the action type i.e. Push, Pop or Replace
 location :
102

Contains the object which represents location properties like Hash, PathName, State, and Searches
Page

parameters
 pathname :

Returns the current path of the URL


 search :

Returns the search parameters along with the URL


 hash :

Returns the hash fragment attached to the URL


 state :

Contains the location-specific state that was provided to e.g. push (path, state) when this location was
pushed onto the stack.
 push(path, [state]) :

This is the method which pushes a new entry into the existing history stack
 replace(path, [state]) :

This is the method which replaces the current entry on the existing history stack
 go(n) :

This is the method which moves the pointer in the history stack by n entries
 goBack() :

Used to move the backward page


 goForward() :

Used to move forward to the next page


 block(prompt) :

This method used to prevent navigation

To see the complete history object, we can use withRouter like this.

Import React, { Component } from ‘react’;


import { withRouter } from “react-router-dom”;

class WithRouterDemo extends Component {

render() {
console.log(this.props.history)
103

return (
<div>
Page

This is withRouter demo


</div>
);
}
}

// Using withRouter
export default withRouter(WithRouterDemo);

After running the above example, we can see the complete history object like this.

Q21. How to enable server rendering in React Routing?


Ans. The <BrowserRouter> is used to render the routing configuration client-side, but what if we need to
render to routing server-side.
104

For that, we have another API called <StaticRouter> which enable us to configure server rendering like this.
Page

Instead of:
render(
<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById(‘root’));

Replace with this:

render(
<StaticRouter>
<App />
</StaticRouter>, document.getElementById(‘root’));

Well, it’s not enough to put just <StaticRouter>, but we need to allow server-side rendering mechanism.

Q22. How to redirect to default (404) page in React?


Ans. Sometimes it may happen that people trying to access the URL which is not the part of route
configuration, in this case, we can redirect the user to the default page.

In order to redirect in default page, we can create a separate route along with the default component name like
this.

<Switch>
<Route path=”/” exact component={Home} />
<Route path=”/about/” component={About} />
<Route path=”/contact/” component={Contact} />
{/* Default redirect page */}
<Route component={NotFound} />
</Switch>

So whenever a user tries to access the page other than “/”, “/about” and “/contact”, then they should be
redirected to the default page.

Here “NotFound” is the default component in order to show some static message to the end-user.

Class NotFound extends Component {


render() {
return <h3>404 !! Page not found</h3>
}
}

10
105

React Hooks
Page
Q1. What are the Hooks in React?
Ans. Hooks are a newly added feature in version 16.8, and it is introduced to allow us to use different react
component features in functional-based components like state and props.

Hooks are used at the top of level for the react function and it cannot be used inside the conditions, expressions,
loops and other nested functions used by the existing function.

Hooks are first released at the React Conf OCT 2018 in order to use state and other side-effects into the
function-based component.

Q2. Why Hooks are useful?


Ans. Before learning the Hooks, we should know that why people should use the Hooks in our React app and
what are the advantages by using it compare to class-based components.

Primarily, Hooks are introduced to simplify the accessing the different concepts of the component from the
function-based component like state, different lifecycle hooks and so on.

By using Hooks, we can easily develop complete React app using Hooks only.

Previously, the class-based component was used in order to use different concepts like state, props, lifecycle
hooks, and so on, but now we will be able to use it for most of the all concepts of React into the function
component.

Q3. What are the features of React Hooks?


Ans. Hooks come with the various features and it includes following.

 Completely opt-in

We can try the Hooks in a few components without rewriting any existing code. If you want to use then
you can start using by updating the React version.

 100% backward-compatible

Hooks don’t contain any breaking changes for now.

 Available now

Hooks are now available and can be used with the release of v16.8.0.

Q4. How to get started with Hooks?


Ans. As we discussed that React Hooks are available by the version 16.8.0, so if we want to use Hooks In our
app than need to update below packages using npm like this.

npm install --save [email protected]


106

npm install --save [email protected]


Page

By installing the above packages, now we will be able to use Hooks in our application.
Q5. What is the State Hook in React?
Ans. State Hooks is one of the important hooks which allows us to use state functionality into a functional
component.

For that, we can use a hook called “useState” in order to use the state for the function.

Basically, “useState” allows us to use local state in function and it returns current state and function which allow
us to update the state value.

The “useState” is pretty much the same as we do use “this.state” in class-based component, but here we cannot
merge the old state values to the new state values.

Q6. What is the syntax using useState in React?


Ans. The useState hook allows us to use the local state for the function, and along with the state, we can also
have a function which allows us to update the state values.

Below is the basic syntax using useState.

const [state_variable, function()] = useState(default_value);

Here in this example, we can see there are two things are specified which are listed below.

 State_variable which holds the current state value, and we can use it for the rendering purpose
 A function which modifies the state value by calling using event handler or another different way in
order to modify existing state value

And apart from these two things, we can also provide the initial value for providing a default value to the state
values.

Q7. How to set the initial value using useState?


Ans. Using useState, we can provide the initial value for the state, and below is the simple example of that.

const [message, putMessage] = useState("This is Hooks Demo");

In this example, we have message and putMessage to hold and update the state value, but if you notice inside
the useState (), we have provided a string as a message.

The string we have provided is an initial value which can be helpful to specify default value whenever we use
“message” into our template/view.

Q8. How to update state value using useState()?


Ans. The useState () hook allows us to declare and provide the initial value to the state, but same way, we can
also modify the state value.
107

For that we need to specify the function along with the useState () like this.

const [message, putMessage] = useState("This is Hooks Demo");


Page
Here the message is state variable, and apart from that “putMessage” is a function which allows us to update
the state value, we just need to call this and the state value will be updated.

import React, { useState } from "react";


import ReactDOM from "react-dom";

function SimpleHooksExample() {
const [message, putMessage] = useState("This is Hooks Demo");

function setmessage(value) {
putMessage(value);
}

return (
<div>
<p>{message}</p>
<button onClick={() => setmessage("This is Updated Message")}>
Update Message
</button>
</div>
);
}

ReactDOM.render(<SimpleHooksExample />, document.getElementById("root"));

We have one button, and on click event of a button, we need to update the message value.

So whenever we click on the button, it will trigger the function called “setMessage”, and from the function body,
the putMessage function called which allow us to change the state value.

We can also call the function directly like this.

return (

<div>

<p>{message}</p>

<button onClick={() => putMessage("This is Updated Message")}>

Update Message

</button>

</div>

);
108
Page
Q9. What is a useEffect hook in React?
Ans. The useEffect is used to work with different side-effects like browser API, DOM API, fetching API’s from
the third party and so on.

We need to use this hook “useEffect” in functional component because the functional component does not
allow mutation, logging, lifecycle hooks, and other features.

The “useEffect” hook accept the function, and it is the combined version of below lifecycle hooks.

 componentDidMount()
 componentWillUnmount()
 componentDidUpdate()

Important things are that useEffect calls after every render of the view and eventually, we can also call the third-
party API to render the respective data.

Q10. How to use useEffect hook?


Ans. The useEffect accept the function and it will be executed after every rendering cycle, below is the simple
example which shows the value of the state will be updated after every render.

import React, { useState, useEffect } from 'react';


import { render } from 'react-dom';

function App() {
const [index, setIndex] = useState(0);

useEffect(() => {
document.title = `Item purchased ${index}`;
});

return (
<div>
<h3>Items in cart : {index}</h3>
<button onClick={() => setIndex(index + 1)}>
Add
</button>
</div>
);
}

render(<App />, document.getElementById('root'));

We have a button, and on click on the button every time the state value should be updated.
109

So for that, there is a hook called “useEffect()” which accepts the function and from the function body, we are
updating the title of the document whenever we change the index.
Page
The useEffect will persist the value of the index and after first render, and every updated change, useEffect will
be triggered.

Q11. How to call useEffect hook for the specific number of time hook?
Ans. As we know, useEffect() hooks call after every render, so the content inside the function will be executed
every time, but what if we want to call it for the specific number of times.

We can decide it by providing the additional argument along with the function like this.

useEffect(() => {

// function body
},
[value]);

Here we have an additional argument as an array where we can specify how many time function should be
executed and this value can be a state value declared using useState.

This is how we can limit the useEffect to be executed repeatedly.

Q12. How to call API using useEffect hook?


Ans. Using the hook “useEffect”, we can execute the function repeatedly and also limit the function to be
executed based on the state value.

But at the same time, we can call the API in order to render the data into the template, just like we do use
“componentDidMount” which calls after rendering of the component at once.

Same way, we can achieve the same behavior using “useEffect” by providing null as an additional argument
along with the useEffect hook like this.

import React, { useState, useEffect } from 'react';


import { render } from 'react-dom';

function App() {
const [index, setIndex] = useState(0);

// Called only once because argument is null


useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(data => {
console.log(data);
});
}, []); // empty, calls only once
110

return (
Page

<div>
<h3>Items in cart : {index}</h3>
<button onClick={() => setIndex(index + 1)}>
Add
</button>
</div>
);
}

render(<App />, document.getElementById('root'));

Here in this example, we have provided the array value as null, so that it assumes that we need to call the
useEffect once in a while like this.

useEffect(() => {

fetch('https://jsonplaceholder.typicode.com/todos')

.then(response => response.json())

.then(data => {

console.log(data);

});

}, []); // empty, calls only once

As you can see, the additional argument with useEffect is null “[]” thus our hook function call only once when
the functional component renders the content.

This is how we can achieve “componentDidMount” behaviour in the functional component using a hook called
“useEffect”.

Q13. What is a custom hook in React?


Ans. There are two most popular hooks which are useState and useEffect, apart from that, we can also create
our custom hooks to serve custom behaviour.

A custom hook allows us to combine the core React Hooks into our own function and extract component logic
based on our requirements.

Our custom hooks will be same as other hooks and can be imported and exported just like we do with other
hooks.

The important thing about custom hook is that it starts with the “use” keyword to identify uniquely and it can be
called and used by the other components.

Q14. How to create the custom hook?


111

Ans. The custom hook is just a normal function what we create normally, but the custom hook function
serves a purpose for sharing data between components ideally.
Page
Let’s create a custom hooks function which fetches the data from the third-party API.

// CustomHook.js

import { useState, useEffect } from "react";

export default function CustomHook(url) {


const [data, setData] = useState([]);

useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, []);

return data;
}

Here in this example, we have created a new file called “CustomHook.js” which contains our custom hook
function.

For storing state value, we have a state variable called “data”, and the update function is “setData”.

Along with the useState hook, we have used one additional hook which is called “useEffect” which allow us to
fetch data and it works just like “componentDidMount” which renders only once.

And at the end, we are returning the response of API to the calling function.

This is how we can create the custom hooks function which is used to share the data between the components
and serves another different purpose.

Q15. How to access custom hook in React?


Ans. After creating the custom hook function, the next thing is to use in different function in order to access
the data.

For that we can import that custom hook function and can use it like this.

import React, { useState, useEffect } from 'react';


import { render } from 'react-dom';

// Import custom hook function


import CustomHook from './CustomHook';
112

function App() {
Page
// calling custom hook
const users = CustomHook("https://jsonplaceholder.typicode.com/users");
console.log(users);

return (
<div>
<h3>Using custom hook in React</h3>
</div>
);
}

render(<App />, document.getElementById('root'));

As you can see, before using the custom hook, we need to import it.

After importing the custom hook function, we have provided the argument as the third party API URL like this.

const users = CustomHook("https://jsonplaceholder.typicode.com/users");

It calls the custom hook function along with the argument, and our custom hook will return the appropriate
result based on the API response and we can use the returned response into our function.

Q16. What is a useReducer hook?


Ans. The useReducer is a hook which is used to manage complex state transitions across the function which
is the same as Redux’s reducer if you already have knowledge about Reducer.

You may have used Redux’s Reducer, same way now we can use “useReducer” hook which is powerful when it
comes to state management because it can be used along with the useState and useEffect hooks in order to
manage the state.

The useReducer hook can be used as an alternative to useState because sometimes we may have complex state
logic and it can be based on the previous state.

Q17. How to use useReducer hook?


Ans. The useReducer is pretty easy to just like we have used useState and useEffect, but this hook accepts a
reducer which returns the updated state.

Below is the simple example, where we implement the simple counter example in which we click on the
different button and the value will be updated.

// reducer function
function reducer(state, action) {
switch (action.type) {
case "reset":
113

return initialState;
case "increment":
Page

return { count: state.count + 1 };


case "decrement":
return { count: state.count - 1 };
default:
return "Invalid Option"
}
}

In this function, we have different use cases and based on case fulfillment, the updated state will be returned
from the function.

This is just a function with a use case, but in order to manage the state, we will use useReducer just like this.

const [state, dispatch] = useReducer(reducer, initialState);


Here along with the useReducer hook, we have provided two different arguments which are explained below.

 Reducer

It is the name of our function what we have created along with the switch case and it verifies that which
case it matched from the list of cases and returns the updated state data.

 initialState

We can also provide the initial state along with the reducer and it is just like we do with the Redux’s
Reducer.

We can provide the initial state to useReducer hook like this.

const initialState = { count: 0 };

// using initial state and reducer


const [state, dispatch] = useReducer(reducer, initialState);

This is how we can use the “useReducer” hook in order to use reducer functionality without implementing
Redux’s Reducer functionality into small web applications.

Q18. What are the different hook types in React 16.8?


Ans. Few of the hooks are commonly used which are useState, useEffect and useReducer, but apart from that,
other hooks types are also supported which are listed below.

 Basic Hooks
 useContext
 useState
114

 useEffect
 Additional Hooks
Page

 useReducer
 useCallback
 useRef
 useMemo
 useDebugValue
 useLayoutEffect

Q19. Do we need to convert class component to function component?


Ans. No, because of hooks allow us to use React’s core concepts like state, props, lifecycle hooks and many
more into the functional component, but we don’t need to worry because the class will be there and it will not
replace the class-based component for now.

Thus for the learning purpose or developing something new from scratch then we can use hooks in function
components.

Q20. Do all the third-party libraries support the hooks?


Ans. Hooks are still in progress and team is working hard to make it just like class-based functionality into
function component, thus it may possible that the third-party libraries may not compatible with the hooks.

Q21. Can we use multiple state variables using useState?


Ans. Yes, we can use multiple state variable just like we do in class-based component, but here with useState
hooks, we can do it like this.

const [state, setState] = useState(


{
var1: value1,
var2: value2,
var3: value3
}
);

Here we have specified the different state variables by comma (,), this is how we can use different state variable
using the useState hook.

Q22. Can we re-render the function component using forceUpdate()?


Ans. Yes, the forceUpdate() works same as we do in the class-based component where re-render can depend
on the previous and current state, and the state value will not be mutated if there is no change at all after the
rendering of components.

We can use forceUpdate () in function component like this.


115

const [counter, forceUpdate] = useReducer(5);


Page

function handleClick() {
forceUpdate();
}

Q23. How to remember the cache value between multiple renders?


Ans. During the render of the content, sometimes we need to have cache value between two rendering cycle,
so for that, we have an option called “useMemo” which returns the Memoized (cached) values between the
renders.

We can use “useMemo” hook like this.

const UpperCase = ({ text }) => {


const upperCaseText = useMemo(() => upper(text), []);
return upperCaseText;
};

Using the above function, we are using a hook called “useMemo” which executes its body and the result will be
cached after render.

And the upper () function will look like this.

function upper(text) {
console.log("converting text to upper");
return text.toUpperCase();
}

To call the UpperCase function, we can use the code snippet like this.

function App() {
return (
<>
<UpperCase text="manav pandya" />
</>
);
}

This is how we can use “useMemo” in order to store the results of the render into cache only if the
dependencies did not have any updated values.

Q24. Can we use class and hook together?


Ans. No, hooks cannot be used within a class-based function but we can use the mixed approach of classes
and function component with the Hooks.

It's always recommended to use hooks for the new component from the scratch and should not re-write every
class-based component to hooks.
116

Q25. What is the meaning by using square brackets [ ] in hooks?


Page

Ans. The square brackets using hooks is called “Array De-structuring”.


For example, we are using state like this with useState hook.

const [message, setMessage] = useState('Hello World');

Here the first argument is variable which holds the state value and another function in order to update the state
value but both are not the part of React API.

But using useState, we are going to return an object with state value and function which can be stored into the
state variable “message”.

Keep in mind that first value always will be the state and another is used for updating the state value thus we
can access the values like this.

var mydata = useState("Hello");


console.log("First value :", mydata[0])
console.log("Second value :", mydata[1])

After using the above snippet, we will get the output like this.

References

This book has been written by referring to the following sites:

1. https://reactjs.org/docs/getting-started.html - React official site


2. https://stackoverflow.com/questions/tagged/reactjs - Stack Overflow - ReactJS
3. https://www.dotnettricks.com/learn/react - Dot Net Tricks - React
117
Page

You might also like