React DOM/Virtual DOM

RajasreePothula3 81 views 8 slides Jul 17, 2023
Slide 1
Slide 1 of 8
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8

About This Presentation

React, often stylized as React-dom, has taken the world of web development by storm. Recognizing the advantages of React and how it interacts with the Document Object Model (DOM) – a topic that often prompts the question, “what is DOM in React?” – is essential for both aspiring and seasoned ...


Slide Content

ReactDOM/VirtualDOM
TherearehundredsofarticlesfloatingwhichdealwiththecomparisonofDOMand
React-DOM.ButwhatisReact-DOMorwhatisDOMforthatmatter.Let’sunwindthis.
AdvantagesofReact
React,oftenstylizedasReact-dom,hastakentheworldofwebdevelopmentbystorm.
RecognizingtheadvantagesofReactandhowitinteractswiththeDocumentObjectModel
(DOM)–atopicthatoftenpromptsthequestion,“whatisDOMinReact?”–isessentialfor
bothaspiringandseasoneddevelopers.Fromthecomponent-basedapproachandReact
DOMmethodstothevirtualDOMconcept,Reactbringsseveralbenefitstothetable.
OptimizedPerformancewithVirtualDOM
OneoftheforemostadvantagesofReactistheimplementationofthevirtualDOM.React
DOM’sabilitytominimizedirectmanipulationoftheactualDOM–anoperationthat’s
computationallyexpensiveandcanslowdownyourapp–setsitapartfrommanyother
JavaScriptlibrariesandframeworks.
React’svirtualDOMworksbycreatingareplicaoftheactualDOM,allowingReactto
calculatethemostefficientwaytomakechanges.ThisinvolvesusingReactDOMmethods
for‘diffing’(comparingtheoldandnewDOM),and‘reconciliation’(updatingtheactual
DOMtomatchthenewvirtualDOM).Theoverallresult?Faster,moreefficientapplications
thatprovideasmootheruserexperience.
Component-BasedArchitecture
AnothercrucialadvantageofReactisitscomponent-basedarchitecture.Thisapproach
allowsdeveloperstobuildapplicationsusingreusablecomponents,fosteringcode

maintainabilityandreusability.EachcomponentinReacthasitsownstateandlogic,which
makesitself-containedandhelpsinisolatingbugsandmakingtestingeasier.
Evenwhilemanagingthesecomponents,ReactavoidsdirectDOMmanipulation.Incase
youneedtoaccesstheDOMdirectly,Reactprovidesescapehatchessuchasthe
Reactdom.finddomnodemethod,althoughit’sgenerallydiscouraged.
SeamlessIntegrationandBackwardCompatibility
React’sdesignallowsittobegraduallyadopted,meaningyoucanimplementitinsmall
partsofyourprojectwithoutneedingtooverhaultheentirecodebase.ThismakesReacta
flexiblesolutionthatcanbeintroducedintoexistingprojects,makingthetransition
smootherandlessdisruptive.
Also,Reactstrivestobebackward-compatible.Thismeansthatupdatestothelibraryaim
nottobreakyourexistingcode.YoucankeepyourReactprojectsupdatedwiththelatest
featuresandimprovementswithoutworryingaboutsignificantrefactorings.
Server-SideRenderingwithReactdom.hydrate
Reactalsosupportsserver-siderendering(SSR),whichcanimprovetheinitialload
performanceofyourapplicationandmakeitmoreSEO-friendly.SSRworksbyrendering
ReactcomponentsontheserverandsendingtheHTMLtothebrowser.The
Reactdom.hydratefunctionisusedtomaketheserver-renderedmarkupinteractive,
ensuringaseamlessuserexperience.
RichEcosystemandCommunitySupport
ThepopularityofReacthasledtoarichecosystemoflibraries,tools,andresources.From
statemanagementlibrarieslikeReduxandMobX,toroutingsolutionslikeReact-router,
there’sapackageforalmosteveryneed.Moreover,you’rejoiningavibrantcommunityof
developerswhenyoustartworkingwithReact.Thismeansawealthoftutorials,guides,
andthird-partytoolsareatyourdisposal.
ImportantPointstoRememberWhileWorkingwithReact

React,apowerfulJavaScriptlibrarycreatedbyFacebook,hasbecomeavitaltoolfor
buildinginteractivewebapplications.AsyouembarkonyourReactdevelopmentjourney,
thereareseveralkeypointstoremember.Notably,understandingReactDOM,
Reactdom.finddomnode,andReactdom.hydrate,alongwithotherimportantReactDOM
methods,iscriticaltoyoursuccess.
Component-BasedApproach
AttheheartofanyReactapplicationliesacomponent-basedapproach.Thismeansthata
Reactappisbuiltusingnumerousindividualpieces,orcomponents,eachresponsiblefora
distinctpartoftheuserinterface.Thismodularapproachhasseveraladvantages:
●Itpromotescodereuse,ascomponentscanbeusedinmultipleplacesthroughout
anapplication.
●Itmakescodemoremanageableandeasytotest,aseachcomponenthasitsown
logicandcontrolsitsownrendering.
●Itsimplifiesthedebuggingprocess,asdeveloperscanisolateissuestospecific
components.
Whileworkingwithcomponents,you’lloftenencounterReactDOMmanipulation.It’s
importanttonotethatthedirectmanipulationoftheDOMisgenerallyavoidedinReact.
Instead,thestateofcomponentsisupdated,leadingtoachangeinthevirtualDOM,and
eventually,anefficientupdateoftheactualDOM.
Furthermore,ReactprovidesseveralmethodstohelpmanipulatetheDOMwhen
necessary.Reactdom.finddomnodeisonesuchmethod,allowingyoutodirectlyaccessa
DOMnode.However,it’sconsideredanescapehatchanditsuseisdiscouragedinmost
cases.
DeclarativeViewsinReact
AnotheressentialpointtorememberwhileworkingwithReactisitsdeclarativenature.
WhenyouwriteaReactcomponent,youdon’ttelltheprogramhowtoupdatetheview
whenyourdatachanges.Instead,youdescribewhattheviewshouldlooklike.

React,withthehelpofitsvirtualDOM,efficientlyupdatesandrenderstheappropriate
componentswhenyourdatachanges.Theprocessinvolvesdiffing(comparingthenew
virtualDOMwiththepreviousone)andreconciliation(updatingtherealDOMtomatchthe
virtualDOM).
Reactdom.hydratecomesintoplaywhenyou’redealingwithserver-renderedapplications.
Itenablestheclient-sideReacttorecognizeandpreservetheserver-renderedmarkup,
makingtheappinteractive.
WhatisDOMinReact?
DOMisshortformofDocumentObjectModelandisactuallyisjustaJavascriptobject
whichislogicalrepresentationofanywebpage.ThisJavascriptobjectorDOMisstructured
intheformoftreeandthistreecontainsalltheelementsanditsproperties.Andthis
elementsaretreatedasnodes.
WheneverduringdevelopmentthereisanychangeinanyoftheelementstheDOMis
requiredtobeupdatedwhichimpliesthatthebrowserhastocalculateandloadallthe
nodes.Andthenloadallthecssfile,technicallyspeakingrepaintthewholewebpageasper
theCSS.Thismakesthereloadofthewebpageveryslowandsowesaythe
DOM-manipulationusedtobecostlybeforereact-dom.
HowVirtualDOMWorksinReact?
React’spowerandefficiencycomefromitsuniqueapproachtohandlingupdatesinaweb
application.AcornerstoneofthisapproachistheusageofavirtualDOM.Let’sbreakdown
howthevirtualDOMworks:
●InitialRender

WhenaReactapplicationisfirstloaded,ReactDOMcreatesalightweightcopyoftheactual
DOM,aprocessknownasthecreationofa“virtualDOM”.Thisisnotthevisiblewebpage
butarepresentationofitinmemory.
●ComponentUpdates
Asusersinteractwiththeapplicationordatachanges,yourcomponentsmayupdate.
Theseupdatescouldbestatechangesorpropupdates.Whenanupdateoccurs,React
createsanewvirtualDOMtoreflectthesechanges.
●Diffing
ReactthencomparesthisnewvirtualDOM(withtheupdates)tothepreviousvirtualDOM.
Thisprocessisknownas“diffing”.Reactidentifieswhichobjectshavechangedinthevirtual
DOMthroughthisprocess.
●Reconciliation
Thefinalstepis“reconciliation”.Here,Reactusestheresultsfromthediffingprocessto
efficientlyupdatetheactualDOM.ItonlyupdatesthepartsoftherealDOMthathave
changedinthevirtualDOM,nottheentirepage.Thisleadstosignificantperformance
improvements,asmanipulatingtherealDOMisacostlyoperation.
●Reactdom.finddomnode
It’sworthnotingthatReactdom.finddomnodeisamethodinReactDOMthatallowsdirect
accesstoaDOMnode.It’softenusedwhenyouneedtointeractwiththeactualDOM,
ratherthanthevirtualone.
●Reactdom.hydrate
AnotherimportantmethodisReactdom.hydrate,whichisusedto“hydrate”acontainer
whoseHTMLcontentswererenderedbyReactDOMServer.Hydrating,inthiscontext,
meansattachingeventlistenerstotheserver-renderedmarkupfunctional,interactive
application.
●Optimization

ThisentireprocessofdealingwiththevirtualDOMmakesReacthighlyoptimized.Sincethe
realDOMmanipulations,whichareexpensiveoperations,areminimized,theapplication
becomeshighlyefficientandmuchfaster.
●BatchedUpdates
AnotherbenefitofthisprocessisthatReactbatchesmultipleupdatestogethertoavoid
unnecessaryre-renders.Thisfurtherbooststheapplication’sperformance.
Sohowdoesreact-domsolvethisproblem???
React-DOMprovidesaspecificbundleofpackagestoDOMthatcanbeappliedonlytothe
topleveloftheappinsteadofallthecomponents.ReactDOMcomeswithsomemethods.
Wewilldiscussthesemethodslaterbutitisimportanttomentionherethatreact-domor
virtualdomisnothingbutacopyoftheoriginaljavascriptdomobject.
SowheneverthereisanymanipulationinanyoftheelementthevirtualDOMupdates
itself(hereupdatingthevirtualdomcomparativelymuchcheaper)andonlythedifferences
betweenthevirtualdomandrealdomgetsupdatedinrealdom(Forexampleifthe
elementalreadyrenderedintherealdomthenonlychangesaftercomparisonbetween
realdomandvirtualdomwillbere-renderedandthewholeelement).
Soherethereisnodirectmanipulationintherealdomandwhichimpliesfasterloadof
webpage.
Nowlet’shaveadeepdiveintoreact-domandthemethodsprovidedbyitsuchas
render():Thismethodrendersthereactelementtothegivencontainerinthedomand
returnsareferenceofcontainerorelsenullifitsastatelesscontainerandifthereareany

callbacksfunctionspassedtoitthenexecutesthemonlyoncethecomponentis
rendered.Thesyntaxforthesameisasfollows
ReactDOM.render(element,container[,callback])
hydrate():Hydrateworkssameasrendermethodandfollowsthesamesyntaxasfollows
ReactDOM.hydrate(element,container[,callback])
Butitisusedtohydratethecontainerwhosehtmlmarkupsarerenderedbythe
reactDomServer.WhenIsayhydratethecontainerbythatwhatImeanisreacttryto
comparethecontentrenderedattheclientiswhetherthesameastheserverornot.React
generallyignorethemismatchesinthetextcontentbutitdoesn’tworkthesamewayin
caseofmismatcheswiththeattributes.
Ifyouhavesomecontentwhichisrendereddifferentlyatserverandclientthenyoucan
suppressthewarningbyusingsuppressHydrationWarning.Butalwaysguidedtokeepin
mindtoavoidusingthisasitmightleadtosomeunexpectedbug.
unmountComponentAtNode():Asthenameofthismethodisselfexplanatory.It
unmountsthecomponentanditcleansitseventhandlerfromtheDOM.Thesyntaxforthe
sameisasfollows
ReactDOM.unmountComponentAtNode(container)
Alsothismethodreturnsfalseifthereisnocomponenttounmountandreturnstrueithas
successfullyunmountsthecomponent.
findDOMNode():Thismethodisanescapehatchasitwillletyouaccesstheunderlying
DOMnode.Butideallyitispreferableasitpiercesthecomponentabstraction.Youcannot
usethismethodinstrictmodeasithasbeendeprecated.Thesyntaxtousethesameisas
follows:
ReactDOM.findDOMNode(component)

IfthiscomponentismountedintotheDOM,itreturnsnativebrowserDOMelementandit
thecomponentisrenderedtonullorfalsethenfindDOMNode(component)returnsnull
elseincaseoffindDOMNodeisrenderedtostringthenthecomponentwillreturntext
domcontainingtharvalue.
AlsofindDOMNodeonlyworksincaseofthecomponentthathasbeenalreadyrendered.If
youtrytousethisonthecomponentthatdoesnotexistondomorstillhastoberendered
(forexamplethecomponentsinrendermethod)thenfindDOMNOdewillthrowan
exception.