React Questions and Answers Ebook
React Questions and Answers Ebook
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.
.NET Development
Front-end Development
Cloud
DevOps
Programming Languages
Database - SQL and NoSQL
Mobile Development
ML/AI and many more...
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
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.
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.
.NET Development
Front-end Development
Cloud
DevOps
Programming Languages
Database - SQL and NoSQL
Mobile Development
ML/AI and many more….
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.
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 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.
[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
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
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
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
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
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
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.
16
Page
Q3. Why use React?
Ans. React is a booming word nowadays due to certain reasons which are listed below.
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.
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.
“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.
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."
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.
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.
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.
“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.
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.
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.
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>
);
}
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.
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.
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>
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.
<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.
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.
But now we can make use of npx, and the command is.
After creating a new React app using the above command, just follow these two commands.
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.
npm test
To build the React, we can use simple npm command like this.
After running above command, we can see that a new folder called ‘build’ created in the root of the application.
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.
By running above npm command, we can remove the single build dependency from our React app.
Some other online web editors are also awesome to develop small React applications.
Stalkblitz
CodeSandBox
Repl.it
We can upgrade it by just using the single line command like this.
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.
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.
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.
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.
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.
var navmenu = (
<ul id="navmenu">
</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 = (
);
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.
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.
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.
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>
);
}
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
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.
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.
While working with JSX, we can pass the properties in different ways which are listed below.
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
render() {
const isVisible = true;
return (
<div>
<Demo
isVisible
/>
</div>
);
}
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.
constructor() {
super();
this.state = {
items: [
"Item 1",
"Item 2",
"Item 3",
]
};
}
render() {
return (
<div>
<Demo
items={...this.state.items}
/>
</div>
);
}
}
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.
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”.
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.
Creating component is a very straight forward thing, for that we just need to create “.js” file and code should
look like this.
37
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.
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.
render() {
return (
<div>
<h1>Hello {this.state.message}</h1>
</div>
);
}
}
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.
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.
We can use the function-based component while we want to use only rendering logic.
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.
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.
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<h1>Component Coposition in React</h1><hr />
<Header />
<Content />
<Footer />
</div>
);
}
}
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.
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
);
}
}
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.
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.
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.
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.
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.
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.
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.
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.
But next question may raise that how to use it in React component, so below is the simple example of some
lifecycle methods.
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>
);
}
}
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 is how we can use different lifecycle methods based on the execution flow.
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.
render() {
return (
<div>
<h1> This is {this.props.name} Component </h1>
</div>
);
}
}
App.defaultProps = {
name: "APP"
}
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.
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.
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.
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.
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>
);
}
}
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.
In Uncontrolled component, for handling forms value, we can use a reference (ref) of the input element rather
than using associated event handler.
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>
);
}
}
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.
“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.
Ans. Higher-Order Component takes the Component name which is wrapped around the HOC name, below is
Page
render() {
return (
<div>
<h4>This is demo component</h4>
<h4>Data coming from HOC is : {this.props.data.componentNeme}</h4>
</div>
);
}
}
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.
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.
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.
Basically, for rendering component, we can make use of && condition or other options as explained below.
render() {
return (
<div>
<h1>Conditional Component rendering in React</h1><hr />
54
{this.state.isSuccess &&
Page
<Success />
}
</div>
);
}
}
By using ternary operator, we can render the component based on if-else condition like this.
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.
render() {
return (
<div>
<h3>Hello World</h3>
</div>
);
}
}
56
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.
render() {
return (
<div>
<h3>Hello World</h3>
</div>
);
}
}
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.
render() {
return (
<div>
<h3>Message : {this.state.message}</h3>
</div>
);
}
}
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.
For that, we can use “setState()” function which accepts the new value and it will be updated into the State
object.
Using setState() along with the new value for the specific object, we can mutate the state value, below is the
simple example for that.
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>
);
}
}
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 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.
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.
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.
componentDidMount() {
Page
this.setState({
greeting: "Updated Message",
employees: [...this.state.employees, { id: '002', name: 'Test' }]
});
}
render() {
return (
<div>
<h3>{this.state.message}</h3>
</div>
);
}
}
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.
But previously, the state value can be accessible using getInitialState() method like this.
Ans. The state can be used independently for the rendering as well as with Higher Order Component (HOC)
Page
render() {
return (
<div>
// Passing state to HOC
<Demo
greeting={this.state.greeting}
/>
</div>
);
}
}
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.
For passing the props to the component, we need to follow camel case standard, and below is the simple
example for that.
render() {
return (
<div>
<h1>Passing props to Child component in React</h1><hr />
<Demo
// Passing "message" as props
message={this.state.message}
/>
</div>
);
}
}
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.
<Demo
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.
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.
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.
Passing object to the child component is not a different thing, it is just like we do with the single value.
render() {
return (
<div>
{/* Passing complete Props object */}
<Employee employeeDetail={this.state.employee} />
</div>
);
}
}
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.
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.
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
}
}
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.
render() {
const { appName, demoName } = this.props;
return (
<div>
<div>Component Name : <strong>{appName}</strong></div>
67
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.
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.
After installing the package, we can import and use it in our react app like this.
render() {
const { appName, demoName } = this.props;
return (
<div>
<div>Component Name : <strong>{appName}</strong></div>
<div>Demo Name : <strong>{demoName}</strong></div>
</div>
);
}
}
68
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.
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
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"
}
Here in Function component, we can use defaultProps just like we do in Stateful component.
70
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.
// Child component
class Demo extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<h3>{this.props.render(this.state)}</h3>
</div>
);
}
}
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.
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.
There are two types of Form input are supported which are listed below.
Controlled form inputs value can be maintained using internal component state, and can be updated using
method setState() to reflect original state value.
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
}
}
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.
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”.
onsubmit(event) {
console.log(this.myinput.current.value);
event.preventDefault();
}
render() {
return (
74
<div>
Page
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.
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.
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.
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.
render() {
return (
<div>
<label ref={this.myLabel}></label>
</div>
);
}
}
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.
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.
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
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>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>
);
}
}
Here in this example, we have simple form controls for the First name, Last name, Email, and password.
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
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
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
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}
In order to perform click event, we can use “onClick” event along with the event handler function like this.
onButtonClick() {
console.log("Button Clicked")
}
render() {
return (
<div>
<button type='button' onClick={(event) => this.onButtonClick(event)}>
Submit
</button>
</div>
);
}
}
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.
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")
}
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.
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.
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.
onBlur(id, event) {
event.preventDefault();
console.log("ID Is :", id)
}
render() {
return (
<div>
<input onBlur={(event) => this.onBlur('001', event)} />
</div>
);
}
}
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.
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.
onButtonClick(event) {
event.preventDefault();
console.log("Button Clicked")
}
render() {
return (
<div>
<EventArguments
onButtonClick={this.onButtonClick}
/>
</div>
);
}
}
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.
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';
render() {
// Accessing event handler from props
const { onButtonClick } = this.props;
return (
<div>
<input onBlur={onButtonClick} />
</div>
);
}
}
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.
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.
}
}
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.
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
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.
For example, we have two different messages and want to show the message based on the state value like this.
renderMessage() {
if (this.state.isVisible) {
else {
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.
renderComponent() {
Page
// Rendering component conditionally
if (!this.state.isSuccess) {
return <SuccessComponent />
}
else {
return <ErrorComponent />
}
}
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>
);
}
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.
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>
);
}
Apart from the above methods, we can use a switch case in order to render the element based on the condition
like this.
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
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 ().
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.
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.
react-router
Reach Router
react-router-component
Backbone
component-router
Aviator
Director
Finch
mvc-router
react-mini-router
react-passage
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.
After installing the above package, now we are good to go with the Routing in React.
Previously it was called “react-router” but now it’s split into the three different packages which are listed below.
react-router-dom
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.
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.
After importing such options, now we can create different navigation links like this with the complete example.
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>
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.
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
<Link
to={{
pathname: “/employees”,
search: “?name=Manav”,
hash: “#first-page”,
state: { isFound: true }
}}
/>
<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.
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.
Here in the above example, we have our root component “App” along with with the path “app”, which initiate
95
<Route component>
<Route children>
<Route render>
These methods are used in different situation for example while implementing nested routing and so on.
<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.
For example, we have three different components like Home, About and Contact than we can provide the route
setting like this.
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.
<Switch>
<Route path=”/” exact component={Home} />
<Route path=”/about/” component={About} />
96
It contains the list of different <Route> which tells which component to be loaded when the URL matches with
the route-prefix.
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.
<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.
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.
For that we can pass the different optional parameters along with the route like this.
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.
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.
params
Contains the list of key-value pair of parameters passed along with the URL
Path
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 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
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.
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.
Below is the simple example using withRouter and the component name, which print the simple props of the
different objects.
render() {
console.log(this.props)
return (
<div>
This is withRouter demo
</div>
);
}
}
// Using withRouter
101
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.
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 :
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() :
To see the complete history object, we can use withRouter like this.
render() {
console.log(this.props.history)
103
return (
<div>
Page
// Using withRouter
export default withRouter(WithRouterDemo);
After running the above example, we can see the complete history object like this.
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’));
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.
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.
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.
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.
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
Available now
Hooks are now available and can be used with the release of v16.8.0.
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.
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.
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.
For that we need to specify the function along with the useState () like this.
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>
);
}
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.
return (
<div>
<p>{message}</p>
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.
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>
);
}
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.
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.
function App() {
const [index, setIndex] = useState(0);
return (
Page
<div>
<h3>Items in cart : {index}</h3>
<button onClick={() => setIndex(index + 1)}>
Add
</button>
</div>
);
}
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(data => {
console.log(data);
});
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”.
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.
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
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.
For that we can import that custom hook function and can use it like this.
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>
);
}
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.
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.
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.
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
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.
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.
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.
Basic Hooks
useContext
useState
114
useEffect
Additional Hooks
Page
useReducer
useCallback
useRef
useMemo
useDebugValue
useLayoutEffect
Thus for the learning purpose or developing something new from scratch then we can use hooks in function
components.
Here we have specified the different state variables by comma (,), this is how we can use different state variable
using the useState hook.
function handleClick() {
forceUpdate();
}
Using the above function, we are using a hook called “useMemo” which executes its body and the result will be
cached after render.
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.
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
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.
After using the above snippet, we will get the output like this.
References