SlideShare a Scribd company logo
1 of 5
Download to read offline
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072
© 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 133
React state management and side-effects – A Review of Hooks
Krutika Patil1, Sanath Dhananjayamurty Javagal2
1Software Engineer, JP Morgan Chase & Co., Palo Alto, California, USA
2Systems Engineer, Cruise LLC., San Francisco, California, USA
---------------------------------------------------------------------***---------------------------------------------------------------------
Abstract - React is a front-end JavaScript library used to
build User Interfaces (UIs) or UI components. ReactJS is a
flexible, declarative, and efficient JavaScript library for
building reusable UI components. We can also build complex
components by nesting one or more simple components. This
concept is the heart of any React application. One of the
outstanding capabilities of React is Hooks. We can efficiently
manage states and execute side effects using React Hooks
without defining a JavaScript class. It is like taking advantage
of the cleanliness and simplicity of a Pure Component and
state and component lifecycle methods. This clarity, efficiency,
and simplicity are possible because Hooks are regular
JavaScript functions! In this paper, we dive deep into React
Hooks and their capabilities.
Key Words: react, react hooks, react state,reactside-effects,
JavaScript, frontend-frameworks, web development.
1. INTRODUCTION
React version 16.8 first introduced us to Hooks.
The functional components can access the state and other
React features using React Hooks. React Hooks arefunctions
using which we can introduce state management and side-
effect logic, among others, in a React component. The React
Hooks do not work with or inside classes; however, React
Hooks let us perform these operationswithoutusingclasses.
2. React Hooks are revolutionary
Hooks solve many seemingly unconnected roadblocksReact
developers face in their journey of building many React
applications. Let us discuss a few of those problems in the
following sections and understand how React Hooks fill
those gaps and make React development more efficient and
fun.
2.1 Reusing stateful logic among components is
hard
React does not provide an out-of-the-box way to "hook"
reusable behavior into components. The react developers
during the early days of React usually preferred techniques
like higher-order components and render props to
achieve such behavior.However,thesepatternsrequireusto
restructure our components when we use them, which can
complicate the code and reduce its readability. A typical
React class-based application consists of many wrapper
components, making it challenging to analyze and
troubleshoot. Even though we have Dev Tools to help us in
this process, this brings a more pressing problem to sharp
relief: we need to introduce a better alternative to manage
states in React.
With Hooks, we can reuse the stateful logic without
affecting the hierarchy of the components. The state logic
can also be extracted and tested out independently.
2.2 Complex components are challenging to
maintain
We have often dealt with a situation where we used
components that seemed manageable and small to begin
with but, during the development process, grew into
complex pieces that were difficult to maintain and
understand.
In many cases, splitting the application into smaller
components gets challenging as thestateful logicgetsshared
throughout the application. Testing such componentsisalso
tricky, so React is usually combined with a third-party state-
management library but might introduce too much
abstraction making the code reuse difficult.
To mitigate this problem, React Hooks help us break
down a complex component into smaller building blocks
called functions based on relativity rather than lifecycle
methods. We may also use the “useReducer” Hook to
manage the local state of a component.
2.3 Learning classes is a steep learning curve
The concept of JavaScript classes is significantly different
compared to other languages. Developers are known to
struggle with classes in JavaScript since classes are complex
pieces of logic. The complexity of classes also poses
challenges to code-reusabilityandorganization.Duetothese
reasons and the steep learning curve, a lack of enthusiasm is
noticed among React developers to learn and use classes in
React.
3. The State hook
Let us start understanding the useState Hook by comparing
the below code in Figure 1 with anequivalentclassexample.
Reactivity is a common trait of any user-friendly front-end
application. The application can achieve it by maintaining
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072
© 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 134
the states and updating or rendering the components
impacted by those states. A component's state needs to be
updated whenever one or more variables in the component
update. It is here that the useState Hook shines. Let us
compare a state implementation in a React class component
and a functional component.
Fig -1: Sample React functional component with useState
Hook
If we have used React classes before, the code below in
Figure 2 should look familiar.
Fig -2: Sample React class component with state
Initially, when the state is declared, it has the value
{clickCount: 0}, with every click action on the button
this.setState() function gets executed, incrementing the
previous value by 1.
Let us consider the same example using a functional
component. As a reminder, Figure 3 depicts an example of a
functional component.
Fig -3: Sample React functional component
Depicted in Figure 4 is another way to declare a
functional component using the ES 5 JavaScript format.
Fig -4: Sample React functional component using ES5
JavaScript format
We have previously known these as stateless
components. These are also known as functional
components since these are functions with stateful logic in
them. Hooks do not work inside classes. However, we can
use them instead of writing classes.
Our example starts by addinga namedimportofthesame
name, useState, from the react library, as depicted below in
Figure 5.
Fig -5: Syntax to import the “useState” Hook
3.1 When do we use a React state Hook
During the early React days, we would convert a
functional component to a React class component if we
needed to add stateful logic. However, we can now instead
use a state hook.
3.2 Introducing stateful logic in components
Continuing with our class example, let us initialize
clickCount to 0 by setting the value of this.state to
{clickCount: 0} in the constructor, as shown in Figure 6.
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072
© 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 135
Fig -6: Declaring state in a React class
The concept of this object is not supported in functional
components of React, making it impossible to read from
this.state. However, we can directly execute the useState
Hook within the functional component, as depicted belowin
Figure 7.
Fig -7: Functional component state declaration using
useState
3.3 What are the inputs to the useState Hook?
The useState Hook takes in one argument, the initial
state. The state need not be an object, unlike the classes. If
that solves the purpose, it can be as simple as a string or a
number. Like in our example here, we initialize the state of
the variable as 0, which is a number. The useState Hook can
be called as many times as we need to store different states.
We get two values returned by the React useState Hook that
can be retrieved by arrayde-structuring,asdepicted below
in Figure 8.
Fig -8: useState initial value and return values
In the example above, val is the statevariable,andwecan
set the value of val using the setter function setVal.
3.4 What values are returned by useState?
The useState Hook returns two values: the existingorthe
current value and a setter function that sets or updates the
state. Hence, the syntax depicted in Figure 8 relates directly
to the class example shown in Figure 6 with
this.state.clickCount and this.setState. With this
understanding, the example depicted in Figure 7 should
make sense.
When the React application first renders, the App
component function, the parent to all other components in
the project, gets executed first. The App component then
executes its child component functions, and so on. Hence,
when a particular componentvariablechanges,thechangeis
not reflected on the DOM since the component function is
not re-executed. It is here that the useState react Hook
shines.
3.5 Detailed Working
Upon declaring a variable or a state using the useState
Hook, React stores and maintains the state in the JavaScript
memory. To set a value to the variable, use the setter
function and pass in the new value. The setter function
indicates to React that the component function needs to be
re-executed, which then executes the useState function. The
re-execution of the state Hookensuresthestatevariablegets
updated with the latest value since every execution of the
state Hook returns the latest value. As the state updates, it
gets reflected on the DOM courtesy of React's virtual DOM.
Once the component function is re-executed, the updated
value gets reflected on the DOM. The execution of the state
Hook in a component would not affect any other component
except the component where the useState for thisvariable is
initialized or used. Also, when the component function is re-
executed, it would not reset the variable's value to its initial
value since React keeps track of the first initialization of
useState Hook. React also keeps track of the current or the
latest state between rendersandalwaysprovidesuswith the
most current state. So, during every subsequent executionof
the state Hook and except the first execution,theinitial value
is ignored.
The useState Hook helps us separate the state on a
per-component basis. This way, useStatehelpsmaintain
the states of React components.
4. The Side Effect Hook
We can perform side-effect logic in React functional
components using the useEffect Hook.
4.1 What do side-effects mean in React?
We perform a side-effect when interacting outside our
React component to achieve a particular goal. It is
impractical to predict the outcome of side effects since they
are actions performed with elements in the outside world.
Some common side-effects include calling an API to fetch
data, using browser APIs (window or document directly),
and using unpredictable timer functions (setTimeout and
setInternal).
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072
© 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 136
4.2 useEffect – Champion of handling side-effects
We should refrain from using the side effects directly in
the React component functions since those can impact the
component's rendering. For example: If we have a logic to
call an API in the React component's function, the API call
will be executed upon every component render.Moreover,if
the side-effect updates a state in the component function, it
triggers a re-render of the component resulting in the side-
effect's re-execution. This sequence of events maytrigger an
infinite render loop. The side-effects need to be separated
from React’s rendering logic and must consistently execute
once the component renders, which is what the useEffect
Hook gives us.
4.3 Syntax
useEffect is a function that takes two arguments. The
first argument is a function that executes thesideeffectlogic.
The second argument is an optional list of dependencies on
which the side effect function depends, as depicted below in
Figure 9. This list can be empty if we choose not to list any
dependencies. When the list is empty, the useEffect function
gets executed upon every component render.
Fig -9: useEffect declaration
By listing out the dependencies, we inform React thatthe
side-effect function must execute ONLY if one or all the
dependencies in the list change, ensuring that the side-
effect logic executes in specific circumstances unique to
the side-effect. When the react component re-renders,
React compares the values of the dependencies from their
previous values and only runs the useEffect function if a
change is detected. The useEffect Hook does not execute in
the case of no change in the values of the list of
dependencies. This way, we may skip runningtheside-effect
logic in cases where we do not need to.
4.4 Effects needing clean-up
Consider the below useEffect implementationdepictedin
Figure 10. There may be instances where our side effects
include subscribing to an event or a timeout. In this case, for
every execution of the useEffect function, we create a new
subscription without clearing the older ones.
Fig -10: useEffect with a subscription to setInterval
The above logic in Figure 10 might lead to memoryleaks
and unexpected behavior. It is herethattheuseEffectclean-
up function comes to the rescue.
We can have the useEffect Hook return a function, which
essentially executes the clean-up logic as depicted below in
Figure 11.
Fig -11: useEffect with clean-up function
The clean-upfunction executesinthefollowingscenarios:
during every execution of the useEffect function, except the
first component render, and upon the component getting
unmounting from the DOM. In the example above, the clean-
up function does not run during the first render of the
component, but then it runs before every execution of the
useEffect function. Since we save the interval value that was
last created, the clean-up function clears the previously
created interval using clearInterval beforere-executingthe
useEffect function, which then creates a new interval. Since
the clean-up function runs just before the component is
unmounted from the DOM, the last interval alsogetscleared.
5. CONCLUSIONS
We have attempted to highlight React's state management
and the side-effect hooks. The state management hook
useState helps us to efficiently manage React component
updates and show appropriate feedback to the user by
updating the respective components, which ensures a
seamless user experience. The side-effect hook useEffect
lets us perform side-effect operations without interfering
with React's rendering logic or the performance of the React
component. There are more hooks, for example, useRef,
useContext, and useCallback. We also have an opportunity
to build our hooks in React. ThesecapabilitiesofReacthooks
can be used appropriately per the use case, leading to
efficient and user-friendly front-end applications.
REFERENCES
[1] Bhupati Venkat Sai Indla | Yogeshchandra Puranik
"Review on React JS" Published in International Journal
of Trend in Scientific Research and Development
(ijtsrd), ISSN: 2456-6470,Volume-5|Issue-4,June2021,
pp.1137-1139, URL:
https://www.ijtsrd.com/papers/ijtsrd42490.pdf.
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072
© 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 137
[2] Rawat, Prateek, and Archana N. Mahajan. "ReactJS: A
Modern Web Development Framework." International
Journal of Innovative Science and Research Technology
5, no. 11 (2020).
[3] Maratkar, Pratik Sharad, and Pratibha Adkar. "Re act JS-
An Emerging Frontend JavaScript Libr ary." Iconic
Research And Engineering Journal s 4, no. 12 (2021):99-
102.
[4] https://reactjs.org/
[5] https://www.w3schools.com/react/default.asp/
[6] https://en.wikipedia.org/wiki/React_(JavaScript_library
)#React_hooks
[7] https://www.udemy.com/course/react-the-complete-
guide-incl-redux/learn/lecture/25600136#overview
BIOGRAPHIES
Ms. Krutika Patil is a Full-Stack
Senior Software Engineer at JP
Morgan Chase & Co. in Palo Alto,
California, USA. Her interests
include web development, Spring
Boot, JavaScript frameworks
(React, Vue and Angular), and
other Computer Science concepts.
Mr. Sanath Dhananjayamurty
Javagal is a Senior System
Engineer at Cruise LLC in San
Francisco,California,USA.Working
mainly as an Autonomous Vehicle
Network architecture and Systems
Engineer, his interests include
Computer Engineering, AV
Architecture and Design,
Simulation, and Analysis.

More Related Content

Similar to React state management and side effects review

Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
Importance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdfImportance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdfNishaadequateinfosof
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfBOSC Tech Labs
 
Pluginkla2019 - React Presentation
Pluginkla2019 - React PresentationPluginkla2019 - React Presentation
Pluginkla2019 - React PresentationAngela Lehru
 
Green Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React HooksGreen Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React HooksGreen Custard
 
30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackioimdurgesh
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...IRJET Journal
 
Top 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptxTop 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptxBOSC Tech Labs
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Interview Questions On React JS.pptx
Interview Questions On React JS.pptxInterview Questions On React JS.pptx
Interview Questions On React JS.pptxDucatNoida1
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptxNavneetKumar111924
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react jsdhanushkacnd
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to ReduxAmin Ashtiani
 

Similar to React state management and side effects review (20)

Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
Importance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdfImportance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdf
 
React
ReactReact
React
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdf
 
ReactJs
ReactJsReactJs
ReactJs
 
Pluginkla2019 - React Presentation
Pluginkla2019 - React PresentationPluginkla2019 - React Presentation
Pluginkla2019 - React Presentation
 
Green Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React HooksGreen Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React Hooks
 
30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...
 
Copy of React_JS_Notes.pdf
Copy of React_JS_Notes.pdfCopy of React_JS_Notes.pdf
Copy of React_JS_Notes.pdf
 
Top 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptxTop 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptx
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Interview Questions On React JS.pptx
Interview Questions On React JS.pptxInterview Questions On React JS.pptx
Interview Questions On React JS.pptx
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
 
React
ReactReact
React
 

More from IRJET Journal

TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...IRJET Journal
 
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURESTUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTUREIRJET Journal
 
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...IRJET Journal
 
Effect of Camber and Angles of Attack on Airfoil Characteristics
Effect of Camber and Angles of Attack on Airfoil CharacteristicsEffect of Camber and Angles of Attack on Airfoil Characteristics
Effect of Camber and Angles of Attack on Airfoil CharacteristicsIRJET Journal
 
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...IRJET Journal
 
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...IRJET Journal
 
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...IRJET Journal
 
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...IRJET Journal
 
A REVIEW ON MACHINE LEARNING IN ADAS
A REVIEW ON MACHINE LEARNING IN ADASA REVIEW ON MACHINE LEARNING IN ADAS
A REVIEW ON MACHINE LEARNING IN ADASIRJET Journal
 
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...IRJET Journal
 
P.E.B. Framed Structure Design and Analysis Using STAAD Pro
P.E.B. Framed Structure Design and Analysis Using STAAD ProP.E.B. Framed Structure Design and Analysis Using STAAD Pro
P.E.B. Framed Structure Design and Analysis Using STAAD ProIRJET Journal
 
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...IRJET Journal
 
Survey Paper on Cloud-Based Secured Healthcare System
Survey Paper on Cloud-Based Secured Healthcare SystemSurvey Paper on Cloud-Based Secured Healthcare System
Survey Paper on Cloud-Based Secured Healthcare SystemIRJET Journal
 
Review on studies and research on widening of existing concrete bridges
Review on studies and research on widening of existing concrete bridgesReview on studies and research on widening of existing concrete bridges
Review on studies and research on widening of existing concrete bridgesIRJET Journal
 
React based fullstack edtech web application
React based fullstack edtech web applicationReact based fullstack edtech web application
React based fullstack edtech web applicationIRJET Journal
 
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...IRJET Journal
 
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.IRJET Journal
 
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...IRJET Journal
 
Multistoried and Multi Bay Steel Building Frame by using Seismic Design
Multistoried and Multi Bay Steel Building Frame by using Seismic DesignMultistoried and Multi Bay Steel Building Frame by using Seismic Design
Multistoried and Multi Bay Steel Building Frame by using Seismic DesignIRJET Journal
 
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...IRJET Journal
 

More from IRJET Journal (20)

TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
 
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURESTUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
 
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
 
Effect of Camber and Angles of Attack on Airfoil Characteristics
Effect of Camber and Angles of Attack on Airfoil CharacteristicsEffect of Camber and Angles of Attack on Airfoil Characteristics
Effect of Camber and Angles of Attack on Airfoil Characteristics
 
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
 
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
 
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
 
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
 
A REVIEW ON MACHINE LEARNING IN ADAS
A REVIEW ON MACHINE LEARNING IN ADASA REVIEW ON MACHINE LEARNING IN ADAS
A REVIEW ON MACHINE LEARNING IN ADAS
 
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
 
P.E.B. Framed Structure Design and Analysis Using STAAD Pro
P.E.B. Framed Structure Design and Analysis Using STAAD ProP.E.B. Framed Structure Design and Analysis Using STAAD Pro
P.E.B. Framed Structure Design and Analysis Using STAAD Pro
 
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
 
Survey Paper on Cloud-Based Secured Healthcare System
Survey Paper on Cloud-Based Secured Healthcare SystemSurvey Paper on Cloud-Based Secured Healthcare System
Survey Paper on Cloud-Based Secured Healthcare System
 
Review on studies and research on widening of existing concrete bridges
Review on studies and research on widening of existing concrete bridgesReview on studies and research on widening of existing concrete bridges
Review on studies and research on widening of existing concrete bridges
 
React based fullstack edtech web application
React based fullstack edtech web applicationReact based fullstack edtech web application
React based fullstack edtech web application
 
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
 
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
 
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
 
Multistoried and Multi Bay Steel Building Frame by using Seismic Design
Multistoried and Multi Bay Steel Building Frame by using Seismic DesignMultistoried and Multi Bay Steel Building Frame by using Seismic Design
Multistoried and Multi Bay Steel Building Frame by using Seismic Design
 
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
 

Recently uploaded

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 

Recently uploaded (20)

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 

React state management and side effects review

  • 1. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072 © 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 133 React state management and side-effects – A Review of Hooks Krutika Patil1, Sanath Dhananjayamurty Javagal2 1Software Engineer, JP Morgan Chase & Co., Palo Alto, California, USA 2Systems Engineer, Cruise LLC., San Francisco, California, USA ---------------------------------------------------------------------***--------------------------------------------------------------------- Abstract - React is a front-end JavaScript library used to build User Interfaces (UIs) or UI components. ReactJS is a flexible, declarative, and efficient JavaScript library for building reusable UI components. We can also build complex components by nesting one or more simple components. This concept is the heart of any React application. One of the outstanding capabilities of React is Hooks. We can efficiently manage states and execute side effects using React Hooks without defining a JavaScript class. It is like taking advantage of the cleanliness and simplicity of a Pure Component and state and component lifecycle methods. This clarity, efficiency, and simplicity are possible because Hooks are regular JavaScript functions! In this paper, we dive deep into React Hooks and their capabilities. Key Words: react, react hooks, react state,reactside-effects, JavaScript, frontend-frameworks, web development. 1. INTRODUCTION React version 16.8 first introduced us to Hooks. The functional components can access the state and other React features using React Hooks. React Hooks arefunctions using which we can introduce state management and side- effect logic, among others, in a React component. The React Hooks do not work with or inside classes; however, React Hooks let us perform these operationswithoutusingclasses. 2. React Hooks are revolutionary Hooks solve many seemingly unconnected roadblocksReact developers face in their journey of building many React applications. Let us discuss a few of those problems in the following sections and understand how React Hooks fill those gaps and make React development more efficient and fun. 2.1 Reusing stateful logic among components is hard React does not provide an out-of-the-box way to "hook" reusable behavior into components. The react developers during the early days of React usually preferred techniques like higher-order components and render props to achieve such behavior.However,thesepatternsrequireusto restructure our components when we use them, which can complicate the code and reduce its readability. A typical React class-based application consists of many wrapper components, making it challenging to analyze and troubleshoot. Even though we have Dev Tools to help us in this process, this brings a more pressing problem to sharp relief: we need to introduce a better alternative to manage states in React. With Hooks, we can reuse the stateful logic without affecting the hierarchy of the components. The state logic can also be extracted and tested out independently. 2.2 Complex components are challenging to maintain We have often dealt with a situation where we used components that seemed manageable and small to begin with but, during the development process, grew into complex pieces that were difficult to maintain and understand. In many cases, splitting the application into smaller components gets challenging as thestateful logicgetsshared throughout the application. Testing such componentsisalso tricky, so React is usually combined with a third-party state- management library but might introduce too much abstraction making the code reuse difficult. To mitigate this problem, React Hooks help us break down a complex component into smaller building blocks called functions based on relativity rather than lifecycle methods. We may also use the “useReducer” Hook to manage the local state of a component. 2.3 Learning classes is a steep learning curve The concept of JavaScript classes is significantly different compared to other languages. Developers are known to struggle with classes in JavaScript since classes are complex pieces of logic. The complexity of classes also poses challenges to code-reusabilityandorganization.Duetothese reasons and the steep learning curve, a lack of enthusiasm is noticed among React developers to learn and use classes in React. 3. The State hook Let us start understanding the useState Hook by comparing the below code in Figure 1 with anequivalentclassexample. Reactivity is a common trait of any user-friendly front-end application. The application can achieve it by maintaining
  • 2. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072 © 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 134 the states and updating or rendering the components impacted by those states. A component's state needs to be updated whenever one or more variables in the component update. It is here that the useState Hook shines. Let us compare a state implementation in a React class component and a functional component. Fig -1: Sample React functional component with useState Hook If we have used React classes before, the code below in Figure 2 should look familiar. Fig -2: Sample React class component with state Initially, when the state is declared, it has the value {clickCount: 0}, with every click action on the button this.setState() function gets executed, incrementing the previous value by 1. Let us consider the same example using a functional component. As a reminder, Figure 3 depicts an example of a functional component. Fig -3: Sample React functional component Depicted in Figure 4 is another way to declare a functional component using the ES 5 JavaScript format. Fig -4: Sample React functional component using ES5 JavaScript format We have previously known these as stateless components. These are also known as functional components since these are functions with stateful logic in them. Hooks do not work inside classes. However, we can use them instead of writing classes. Our example starts by addinga namedimportofthesame name, useState, from the react library, as depicted below in Figure 5. Fig -5: Syntax to import the “useState” Hook 3.1 When do we use a React state Hook During the early React days, we would convert a functional component to a React class component if we needed to add stateful logic. However, we can now instead use a state hook. 3.2 Introducing stateful logic in components Continuing with our class example, let us initialize clickCount to 0 by setting the value of this.state to {clickCount: 0} in the constructor, as shown in Figure 6.
  • 3. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072 © 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 135 Fig -6: Declaring state in a React class The concept of this object is not supported in functional components of React, making it impossible to read from this.state. However, we can directly execute the useState Hook within the functional component, as depicted belowin Figure 7. Fig -7: Functional component state declaration using useState 3.3 What are the inputs to the useState Hook? The useState Hook takes in one argument, the initial state. The state need not be an object, unlike the classes. If that solves the purpose, it can be as simple as a string or a number. Like in our example here, we initialize the state of the variable as 0, which is a number. The useState Hook can be called as many times as we need to store different states. We get two values returned by the React useState Hook that can be retrieved by arrayde-structuring,asdepicted below in Figure 8. Fig -8: useState initial value and return values In the example above, val is the statevariable,andwecan set the value of val using the setter function setVal. 3.4 What values are returned by useState? The useState Hook returns two values: the existingorthe current value and a setter function that sets or updates the state. Hence, the syntax depicted in Figure 8 relates directly to the class example shown in Figure 6 with this.state.clickCount and this.setState. With this understanding, the example depicted in Figure 7 should make sense. When the React application first renders, the App component function, the parent to all other components in the project, gets executed first. The App component then executes its child component functions, and so on. Hence, when a particular componentvariablechanges,thechangeis not reflected on the DOM since the component function is not re-executed. It is here that the useState react Hook shines. 3.5 Detailed Working Upon declaring a variable or a state using the useState Hook, React stores and maintains the state in the JavaScript memory. To set a value to the variable, use the setter function and pass in the new value. The setter function indicates to React that the component function needs to be re-executed, which then executes the useState function. The re-execution of the state Hookensuresthestatevariablegets updated with the latest value since every execution of the state Hook returns the latest value. As the state updates, it gets reflected on the DOM courtesy of React's virtual DOM. Once the component function is re-executed, the updated value gets reflected on the DOM. The execution of the state Hook in a component would not affect any other component except the component where the useState for thisvariable is initialized or used. Also, when the component function is re- executed, it would not reset the variable's value to its initial value since React keeps track of the first initialization of useState Hook. React also keeps track of the current or the latest state between rendersandalwaysprovidesuswith the most current state. So, during every subsequent executionof the state Hook and except the first execution,theinitial value is ignored. The useState Hook helps us separate the state on a per-component basis. This way, useStatehelpsmaintain the states of React components. 4. The Side Effect Hook We can perform side-effect logic in React functional components using the useEffect Hook. 4.1 What do side-effects mean in React? We perform a side-effect when interacting outside our React component to achieve a particular goal. It is impractical to predict the outcome of side effects since they are actions performed with elements in the outside world. Some common side-effects include calling an API to fetch data, using browser APIs (window or document directly), and using unpredictable timer functions (setTimeout and setInternal).
  • 4. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072 © 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 136 4.2 useEffect – Champion of handling side-effects We should refrain from using the side effects directly in the React component functions since those can impact the component's rendering. For example: If we have a logic to call an API in the React component's function, the API call will be executed upon every component render.Moreover,if the side-effect updates a state in the component function, it triggers a re-render of the component resulting in the side- effect's re-execution. This sequence of events maytrigger an infinite render loop. The side-effects need to be separated from React’s rendering logic and must consistently execute once the component renders, which is what the useEffect Hook gives us. 4.3 Syntax useEffect is a function that takes two arguments. The first argument is a function that executes thesideeffectlogic. The second argument is an optional list of dependencies on which the side effect function depends, as depicted below in Figure 9. This list can be empty if we choose not to list any dependencies. When the list is empty, the useEffect function gets executed upon every component render. Fig -9: useEffect declaration By listing out the dependencies, we inform React thatthe side-effect function must execute ONLY if one or all the dependencies in the list change, ensuring that the side- effect logic executes in specific circumstances unique to the side-effect. When the react component re-renders, React compares the values of the dependencies from their previous values and only runs the useEffect function if a change is detected. The useEffect Hook does not execute in the case of no change in the values of the list of dependencies. This way, we may skip runningtheside-effect logic in cases where we do not need to. 4.4 Effects needing clean-up Consider the below useEffect implementationdepictedin Figure 10. There may be instances where our side effects include subscribing to an event or a timeout. In this case, for every execution of the useEffect function, we create a new subscription without clearing the older ones. Fig -10: useEffect with a subscription to setInterval The above logic in Figure 10 might lead to memoryleaks and unexpected behavior. It is herethattheuseEffectclean- up function comes to the rescue. We can have the useEffect Hook return a function, which essentially executes the clean-up logic as depicted below in Figure 11. Fig -11: useEffect with clean-up function The clean-upfunction executesinthefollowingscenarios: during every execution of the useEffect function, except the first component render, and upon the component getting unmounting from the DOM. In the example above, the clean- up function does not run during the first render of the component, but then it runs before every execution of the useEffect function. Since we save the interval value that was last created, the clean-up function clears the previously created interval using clearInterval beforere-executingthe useEffect function, which then creates a new interval. Since the clean-up function runs just before the component is unmounted from the DOM, the last interval alsogetscleared. 5. CONCLUSIONS We have attempted to highlight React's state management and the side-effect hooks. The state management hook useState helps us to efficiently manage React component updates and show appropriate feedback to the user by updating the respective components, which ensures a seamless user experience. The side-effect hook useEffect lets us perform side-effect operations without interfering with React's rendering logic or the performance of the React component. There are more hooks, for example, useRef, useContext, and useCallback. We also have an opportunity to build our hooks in React. ThesecapabilitiesofReacthooks can be used appropriately per the use case, leading to efficient and user-friendly front-end applications. REFERENCES [1] Bhupati Venkat Sai Indla | Yogeshchandra Puranik "Review on React JS" Published in International Journal of Trend in Scientific Research and Development (ijtsrd), ISSN: 2456-6470,Volume-5|Issue-4,June2021, pp.1137-1139, URL: https://www.ijtsrd.com/papers/ijtsrd42490.pdf.
  • 5. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 09 Issue: 12 | Dec 2022 www.irjet.net p-ISSN: 2395-0072 © 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page 137 [2] Rawat, Prateek, and Archana N. Mahajan. "ReactJS: A Modern Web Development Framework." International Journal of Innovative Science and Research Technology 5, no. 11 (2020). [3] Maratkar, Pratik Sharad, and Pratibha Adkar. "Re act JS- An Emerging Frontend JavaScript Libr ary." Iconic Research And Engineering Journal s 4, no. 12 (2021):99- 102. [4] https://reactjs.org/ [5] https://www.w3schools.com/react/default.asp/ [6] https://en.wikipedia.org/wiki/React_(JavaScript_library )#React_hooks [7] https://www.udemy.com/course/react-the-complete- guide-incl-redux/learn/lecture/25600136#overview BIOGRAPHIES Ms. Krutika Patil is a Full-Stack Senior Software Engineer at JP Morgan Chase & Co. in Palo Alto, California, USA. Her interests include web development, Spring Boot, JavaScript frameworks (React, Vue and Angular), and other Computer Science concepts. Mr. Sanath Dhananjayamurty Javagal is a Senior System Engineer at Cruise LLC in San Francisco,California,USA.Working mainly as an Autonomous Vehicle Network architecture and Systems Engineer, his interests include Computer Engineering, AV Architecture and Design, Simulation, and Analysis.