React state management and side-effects – A Review of Hooks

Page 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

React state management and side-effects – A Review of Hooks

2

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 andcomponent 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,reacthooks,reactstate,reactside-effects, JavaScript,frontend-frameworks,webdevelopment.

1. INTRODUCTION

Reactversion 16.8 firstintroducedustoHooks.

Thefunctional components can access thestateandother ReactfeaturesusingReactHooks.ReactHooksarefunctions usingwhichwecanintroducestatemanagementandsideeffectlogic,amongothers,inaReactcomponent.TheReact Hooksdonot work withor insideclasses;however,React Hooksletusperformtheseoperationswithoutusingclasses.

2. React Hooks are revolutionary

HookssolvemanyseeminglyunconnectedroadblocksReact developers face in their journey of building many React applications.Letusdiscussafewofthoseproblemsinthe following sections and understand how React Hooks fill thosegapsandmakeReactdevelopmentmoreefficientand fun.

2.1 Reusing stateful logic among components is hard

Reactdoesnotprovideanout-of-the-boxwayto"hook" reusable behavior into components. The react developers duringtheearlydaysofReactusuallypreferredtechniques like higher-order components and render props to achievesuchbehavior.However,thesepatternsrequireusto restructureourcomponentswhenweusethem,whichcan 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.EventhoughwehaveDevToolstohelpusin thisprocess,thisbringsamorepressingproblemtosharp relief:weneedtointroduceabetteralternativetomanage statesinReact

With Hooks, we can reuse the stateful logic without affecting the hierarchy of the components. The state logic canalsobeextractedandtestedoutindependently.

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 componentsgetschallengingasthestatefullogicgetsshared throughouttheapplication.Testingsuchcomponentsisalso tricky,soReactisusuallycombinedwithathird-partystatemanagement library but might introduce too much abstractionmakingthecodereusedifficult.

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

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 strugglewithclassesinJavaScriptsinceclassesarecomplex pieces of logic. The complexity of classes also poses challengestocode-reusabilityandorganization.Duetothese reasonsandthesteeplearningcurve,alackofenthusiasmis noticedamongReactdeveloperstolearnanduseclassesin React.

3. The State hook

Letusstartunderstandingthe useState Hookbycomparing thebelowcodein Figure 1 withanequivalentclassexample. Reactivityisacommontraitofanyuser-friendlyfront-end application. The application can achieve it by maintaining

©
Page133
2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal |

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

the states and updating or rendering the components impactedbythosestates.Acomponent'sstateneedstobe updatedwheneveroneormorevariablesinthecomponent update. It is here that the useState Hook shines. Let us compareastateimplementationinaReactclasscomponent andafunctionalcomponent

Fig -3:SampleReactfunctionalcomponent

Depicted in Figure 4 is another way to declare a functionalcomponentusingtheES5JavaScriptformat.

Fig -4:SampleReactfunctionalcomponentusingES5 JavaScriptformat

Fig -1:SampleReactfunctionalcomponentwith useState Hook

IfwehaveusedReactclassesbefore,thecodebelowin Figure 2 shouldlookfamiliar.

We have previously known these as stateless components. These are also known as functional components sincethesearefunctionswithstatefullogicin them. Hooksdo not work insideclasses.However, we can usetheminsteadofwritingclasses.

Ourexamplestartsbyaddinganamedimportofthesame name,useState, fromthereactlibrary,asdepictedbelowin Figure 5.

Fig -5:Syntaxtoimportthe

“useState”

3.1 When do we use a React state Hook

Hook

During the early React days, we would convert a functional component to a React class component if we neededtoaddstatefullogic.However,wecannowinstead useastatehook.

Fig -2:SampleReactclasscomponentwithstate

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 previousvalueby1

Let us consider the same example using a functional component.Asareminder, Figure 3 depictsanexampleofa functionalcomponent.

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} intheconstructor,asshownin Figure 6

Factor value: 7.529 | ISO 9001:2008

©
Journal | Page134
2022, IRJET | Impact
Certified

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

understanding, the example depicted in Figure 7 should makesense.

Fig -6:Declaring state inaReactclass

Theconceptof this objectisnotsupportedinfunctional components of React, making it impossible to read from this.state. However, we can directly execute the useState Hookwithinthefunctionalcomponent,asdepictedbelowin Figure 7

When the React application first renders, the App componentfunction,theparenttoallothercomponentsin the project, gets executed first. The App component then executes its child component functions, and so on. Hence, whenaparticularcomponentvariablechanges,thechangeis not reflectedon the DOMsincethecomponentfunction is not re-executed. It is here that the useState react Hook shines

3.5 Detailed Working

3.3 What are the inputs to the useState Hook?

The useState Hook takes in one argument, the initial state.Thestateneednotbeanobject,unliketheclasses.If thatsolvesthepurpose,itcanbeassimpleasastringora number.Likeinourexamplehere,weinitializethestateof thevariableas0,whichisanumber.TheuseStateHookcan becalledasmanytimesasweneedtostoredifferentstates. WegettwovaluesreturnedbytheReactuseStateHookthat canberetrievedby array de-structuring, asdepictedbelow in Figure 8

Upon declaring a variable or a state using the useState Hook,ReactstoresandmaintainsthestateintheJavaScript memory. To set a value to the variable, use the setter function and pass in the new value. The setter function indicatestoReactthatthecomponentfunctionneedstobe re-executed,whichthenexecutestheuseStatefunction.The re-executionofthestateHookensuresthestatevariablegets updated with thelatestvaluesince every execution ofthe stateHookreturnsthelatestvalue.Asthestateupdates,it getsreflectedontheDOMcourtesyofReact'svirtualDOM. Once the component function is re-executed, the updated valuegetsreflectedontheDOM.Theexecutionofthestate Hookinacomponentwouldnotaffectanyothercomponent exceptthecomponentwheretheuseStateforthisvariableis initializedorused.Also,whenthecomponentfunctionisreexecuted,itwouldnotresetthevariable'svaluetoitsinitial value since React keeps track of the first initialization of useStateHook.Reactalsokeepstrackofthecurrentorthe lateststatebetweenrendersandalwaysprovidesuswiththe mostcurrentstate.So,duringeverysubsequentexecutionof thestateHookandexceptthefirstexecution,theinitialvalue isignored.

The useState Hook helps us separate the state on a per-component basis. This way, useState helps maintain the states of React components.

4. The Side Effect Hook

We can perform side-effect logic in React functional componentsusingthe useEffect Hook.

Fig -8: useState initialvalueandreturnvalues

Intheexampleabove, val isthestatevariable,andwecan setthevalueof val usingthesetterfunction setVal

3.4 What values are returned by useState?

TheuseStateHookreturnstwovalues:theexistingorthe currentvalueandasetterfunctionthatsetsorupdatesthe state.Hence,thesyntaxdepictedin Figure 8 relatesdirectly to the class example shown in Figure 6 with this.state.clickCount and this.setState. With this

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 impracticaltopredicttheoutcomeofsideeffectssincethey areactionsperformedwithelementsintheoutsideworld. Some common side-effects include calling an API to fetch data, using browser APIs (window or document directly), andusingunpredictabletimerfunctions(setTimeout and setInternal).

©
Certified Journal | Page135
2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008
Fig -7:Functionalcomponentstatedeclarationusing useState

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

4.2 useEffect – Champion of handling side-effects

Weshouldrefrainfromusingthesideeffectsdirectlyin theReactcomponentfunctionssincethosecan impactthe component'srendering.Forexample:If wehavealogicto callanAPIintheReactcomponent'sfunction,theAPIcall willbeexecuteduponeverycomponentrender.Moreover,if theside-effectupdatesastateinthecomponentfunction,it triggersare-renderofthecomponentresultinginthesideeffect'sre-execution.Thissequenceofeventsmaytriggeran infiniterenderloop. Theside-effectsneedtobeseparated fromReact’srenderinglogicandmustconsistentlyexecute oncethecomponent renders,whichiswhat the useEffect Hookgivesus.

4.3 Syntax

useEffect is a function that takes two arguments. The firstargumentisafunctionthatexecutesthesideeffectlogic. Thesecondargumentisanoptionallistofdependencieson whichthesideeffectfunctiondepends,asdepictedbelowin Figure 9 Thislistcanbeemptyifwechoosenottolistany dependencies.Whenthelistisempty,theuseEffectfunction getsexecuteduponeverycomponentrender.

Fig -9: useEffect declaration

Bylistingoutthedependencies,weinformReactthatthe side-effect function must execute ONLY if one or all the dependencies in the list change, ensuring that the sideeffect logic executes in specific circumstances unique to the side-effect When the react component re-renders, Reactcomparesthevaluesofthedependenciesfromtheir previous values and only runs the useEffect function if a changeisdetected.TheuseEffectHookdoesnotexecutein the case of no change in the values of the list of dependencies.Thisway,wemayskiprunningtheside-effect logicincaseswherewedonotneedto.

4.4 Effects needing clean-up

ConsiderthebelowuseEffectimplementationdepictedin Figure 10.There maybeinstanceswhereour sideeffects includesubscribingtoaneventoratimeout.Inthiscase,for everyexecutionoftheuseEffectfunction,wecreateanew subscriptionwithoutclearingtheolderones.

Theabovelogicin Figure 10 mightleadtomemoryleaks andunexpectedbehavior.Itisherethatthe useEffect cleanup function comestotherescue.

WecanhavetheuseEffectHookreturnafunction,which essentiallyexecutestheclean-uplogicasdepictedbelowin Figure 11.

Fig -11: useEffect withclean-upfunction

Theclean-upfunctionexecutesinthefollowingscenarios: duringeveryexecutionoftheuseEffectfunction,exceptthe first component render, and upon the component getting unmountingfromtheDOM.Intheexampleabove,thecleanup function does not run during the first render of the component,butthenitrunsbeforeevery executionofthe useEffectfunction.Sincewesavetheintervalvaluethatwas last created, the clean-up function clears the previously createdintervalusing clearInterval beforere-executingthe useEffectfunction,whichthencreatesanewinterval.Since the clean-up function runs just before the component is unmountedfromtheDOM,thelastintervalalsogetscleared.

5. CONCLUSIONS

WehaveattemptedtohighlightReact'sstatemanagement 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 withReact'srenderinglogicortheperformanceoftheReact component. There are more hooks, for example, useRef, useContext,and useCallback.Wealsohaveanopportunity tobuildourhooksinReact.ThesecapabilitiesofReacthooks can be used appropriately per the use case, leading to efficientanduser-friendlyfront-endapplications.

REFERENCES

[1] Bhupati Venkat Sai Indla | Yogeshchandra Puranik "ReviewonReactJS"PublishedinInternationalJournal 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

© 2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified Journal | Page136
Fig -10: useEffect withasubscriptionto setInterval

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

[2] Rawat, Prateek, and Archana N. Mahajan. "ReactJS: A ModernWebDevelopmentFramework."International JournalofInnovativeScienceandResearchTechnology 5,no.11(2020).

[3] Maratkar,PratikSharad,andPratibhaAdkar."ReactJSAn Emerging Frontend JavaScript Libr ary." Iconic Research AndEngineeringJournal s 4,no.12(2021):99102.

[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-completeguide-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 otherComputerScienceconcepts.

Mr. Sanath Dhananjayamurty Javagal is a Senior System Engineer at Cruise LLC in San Francisco,California,USA.Working mainlyasanAutonomousVehicle NetworkarchitectureandSystems Engineer, his interests include Computer Engineering, AV Architecture and Design, Simulation,andAnalysis.

2022, IRJET | Impact Factor value: 7.529 | ISO 9001:2008 Certified

©
| Page137
Journal

Turn static files into dynamic content formats.

Create a flipbook