SlideShare a Scribd company logo
1 of 44
Mohamed EL AYADI
@incepterr
React
A JavaScript library
React
A JavaScript library
A UI runtime that run components
React
A JavaScript library
A UI runtime that run components
A set of packages and renderers of different hosts
environments
whoami
Mohamed EL AYADI
Senior software engineer with a decade of experience
Java & JavaScript ecosystems
@incepter
@incepterr
Plan
What x Is x State ?
State crimes x And x State police
State x Management x Aspects
Conclusion x And x Takeaways
What x Is x State ?
• It is the internal memory of a react component
• State setter is the only trigger of the update phase in react
• OK, may be useSyncExternalStore also, but not trivial
• Some states need to be shared in a tree
• Shared by prop drilling or wired via context Api.
• Asynchronous states update state later.
State crimes x And x State police
• Cannot update state of unmounted component
• Showing results of earlier request
• No cancellations
• No pending states
• Poor error handling
• Useless useEffects
• Flashing old state
• No sharing
• The list doesn’t end here…
State crimes x And x State police
• Cannot update state of unmounted component
State crimes x And x State police
• Cannot update state of unmounted component
State crimes x And x State police
• Cannot update state of unmounted component
State crimes x And x State police
• Problems with this code
• The loading state isn’t a Boolean
• Three pieces of states working and updated together
• Boolean semaphore lock rather than Counting lock!
• Doesn’t abort the previous call
State crimes x And x State police
• Cannot update state of unmounted component
State crimes x And x State police
• Cannot update state of unmounted component
State crimes x And x State police
• Cannot update state of unmounted component
State crimes x And x State police
• Showing results of earlier request
State crimes x And x State police
• Showing results of earlier request
State crimes x And x State police
• No cancellations
• AbortController
State crimes x And x State police
• No cancellations
State crimes x And x State police
• No cancellations
State crimes x And x State police
• No cancellations
State crimes x And x State police
• No cancellations
State crimes x And x State police
• No pending states
State crimes x And x State police
• No pending states
• Exact status
• The data relative to the status
• The date at which this piece of state was constructed
• The props that led to that state outcome, may be used for optimistic UI.
State crimes x And x State police
• Poor error handlig
State crimes x And x State police
• Useless effects
• Could be done in event handlers
• Only to reset state from props
• Effects are only for synchronization and subscription
State crimes x And x State police
• Useless effects
• Could be done in event handlers
• Only to reset state from props
• Effects are only for synchronization and subscription
State crimes x And x State police
• Flashing old state
• Previous state shows for few Millis and then we start a pending state (if lucky
enough!)
State crimes x And x State police
• Manipulating refs and using state to re-render
• The list doesn’t end here…
State crimes x And x State police
• Linters provide great help to follow the rules of hooks
• Rules of hooks
• Exhaustive deps
• …
• Blog posts and tutorials try their maximum to share good practices
• Dan’s overreacted blog
• Kent’s blogs and learning material
• Community libraries makes our life easier
• UI libraries
• State managers
• XState
• State managers leverage the complexity but create bad habits.
• React Strict Mode
State x Management x Aspects
• Sharing
• Subscriptions
• Asynchronous flows
• Cancellations
• Forks
• Effects: debounce, throttle, delay…
• Caching (with/without persistence)
• React/root independent
• Sharing
State x Management x Aspects
• Subscriptions
State x Management x Aspects
• Subscriptions
State x Management x Aspects
• Asynchronous flows
State x Management x Aspects
• Cancellations
• Generators support
• Async/await support via isAborted
• Abort callbacks registration and invalidation
State x Management x Aspects
• Forks
• Replicate behavior for a new tree
State x Management x Aspects
• Effects: debounce, throttle, delay…
State x Management x Aspects
• Caching (with/without persistence)
• Invalidate and refetch when timed-out
• Only invalidate when requested and state
State x Management x Aspects
• React/root independent
State x Management x Aspects
State x Management x Aspects
State x Management x Aspects
Conclusion x And x Takeaways
• State is the only trigger of updates in react (re-renders). Ok, useSES!
• State setter must be secured from old and stale closures, not only unmount.
• If React.useCallback could just invalidate the previous callback when deps
change!
• Status is mandatory when dealing with asynchronous states
• useEffect should not be abused and events should perform more work
• State managers offers great help dealing with state
• Community resources are a gem that should be considered more
• We are all state criminals
Mohamed EL AYADI
@incepterr

More Related Content

Similar to Revisiting x State x Management__blablaconf.pptx

FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxEhtesham46
 
Robust UI development with ClojureScript
Robust UI development with ClojureScriptRobust UI development with ClojureScript
Robust UI development with ClojureScriptSandilya Jandhyala
 
Brighttalk high scale low touch and other bedtime stories - final
Brighttalk   high scale low touch and other bedtime stories - finalBrighttalk   high scale low touch and other bedtime stories - final
Brighttalk high scale low touch and other bedtime stories - finalAndrew White
 
Training Slides: 102 - Basics - Tungsten Replicator - How We Move Your Data
Training Slides: 102 - Basics - Tungsten Replicator - How We Move Your DataTraining Slides: 102 - Basics - Tungsten Replicator - How We Move Your Data
Training Slides: 102 - Basics - Tungsten Replicator - How We Move Your DataContinuent
 
Cloud-based Modelling Solutions Empowering Tool Integration
Cloud-based Modelling Solutions Empowering Tool IntegrationCloud-based Modelling Solutions Empowering Tool Integration
Cloud-based Modelling Solutions Empowering Tool IntegrationIstvan Rath
 
Dumb and smart components + redux (1)
Dumb and smart components + redux (1)Dumb and smart components + redux (1)
Dumb and smart components + redux (1)Brecht Billiet
 
Unit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programmingUnit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programmingLeahRachael
 
Rsqrd AI: Zestimates and Zillow AI Platform
Rsqrd AI: Zestimates and Zillow AI PlatformRsqrd AI: Zestimates and Zillow AI Platform
Rsqrd AI: Zestimates and Zillow AI PlatformSanjana Chowdhury
 
Effective Akka v2
Effective Akka v2Effective Akka v2
Effective Akka v2shinolajla
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsFederico Torre
 
Fault Tolerance in Distributed Environment
Fault Tolerance in Distributed EnvironmentFault Tolerance in Distributed Environment
Fault Tolerance in Distributed EnvironmentOrkhan Gasimov
 
Reacting to the Isomorphic Buzz
Reacting to the Isomorphic BuzzReacting to the Isomorphic Buzz
Reacting to the Isomorphic BuzzBruce Coddington
 
Akka.Net Ottawa .NET User Group Meetup
Akka.Net Ottawa .NET User Group Meetup Akka.Net Ottawa .NET User Group Meetup
Akka.Net Ottawa .NET User Group Meetup Taswar Bhatti
 
Transactional Streaming: If you can compute it, you can probably stream it.
Transactional Streaming: If you can compute it, you can probably stream it.Transactional Streaming: If you can compute it, you can probably stream it.
Transactional Streaming: If you can compute it, you can probably stream it.jhugg
 

Similar to Revisiting x State x Management__blablaconf.pptx (20)

FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptx
 
Robust UI development with ClojureScript
Robust UI development with ClojureScriptRobust UI development with ClojureScript
Robust UI development with ClojureScript
 
Brighttalk high scale low touch and other bedtime stories - final
Brighttalk   high scale low touch and other bedtime stories - finalBrighttalk   high scale low touch and other bedtime stories - final
Brighttalk high scale low touch and other bedtime stories - final
 
Rubyslava #70
Rubyslava #70Rubyslava #70
Rubyslava #70
 
Training Slides: 102 - Basics - Tungsten Replicator - How We Move Your Data
Training Slides: 102 - Basics - Tungsten Replicator - How We Move Your DataTraining Slides: 102 - Basics - Tungsten Replicator - How We Move Your Data
Training Slides: 102 - Basics - Tungsten Replicator - How We Move Your Data
 
ReactJS Code Impact
ReactJS Code ImpactReactJS Code Impact
ReactJS Code Impact
 
Cloud-based Modelling Solutions Empowering Tool Integration
Cloud-based Modelling Solutions Empowering Tool IntegrationCloud-based Modelling Solutions Empowering Tool Integration
Cloud-based Modelling Solutions Empowering Tool Integration
 
Dumb and smart components + redux (1)
Dumb and smart components + redux (1)Dumb and smart components + redux (1)
Dumb and smart components + redux (1)
 
Unit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programmingUnit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programming
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
 
Rsqrd AI: Zestimates and Zillow AI Platform
Rsqrd AI: Zestimates and Zillow AI PlatformRsqrd AI: Zestimates and Zillow AI Platform
Rsqrd AI: Zestimates and Zillow AI Platform
 
Effective Akka v2
Effective Akka v2Effective Akka v2
Effective Akka v2
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic Apps
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
Effective Akka v2.0 - Jamie Allen
Effective Akka v2.0 - Jamie AllenEffective Akka v2.0 - Jamie Allen
Effective Akka v2.0 - Jamie Allen
 
Fault Tolerance in Distributed Environment
Fault Tolerance in Distributed EnvironmentFault Tolerance in Distributed Environment
Fault Tolerance in Distributed Environment
 
Reacting to the Isomorphic Buzz
Reacting to the Isomorphic BuzzReacting to the Isomorphic Buzz
Reacting to the Isomorphic Buzz
 
Akka.Net Ottawa .NET User Group Meetup
Akka.Net Ottawa .NET User Group Meetup Akka.Net Ottawa .NET User Group Meetup
Akka.Net Ottawa .NET User Group Meetup
 
Redux Like Us
Redux Like UsRedux Like Us
Redux Like Us
 
Transactional Streaming: If you can compute it, you can probably stream it.
Transactional Streaming: If you can compute it, you can probably stream it.Transactional Streaming: If you can compute it, you can probably stream it.
Transactional Streaming: If you can compute it, you can probably stream it.
 

Recently uploaded

Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...marcuskenyatta275
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 

Recently uploaded (20)

Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 

Revisiting x State x Management__blablaconf.pptx

  • 3. React A JavaScript library A UI runtime that run components
  • 4. React A JavaScript library A UI runtime that run components A set of packages and renderers of different hosts environments
  • 5. whoami Mohamed EL AYADI Senior software engineer with a decade of experience Java & JavaScript ecosystems @incepter @incepterr
  • 6. Plan What x Is x State ? State crimes x And x State police State x Management x Aspects Conclusion x And x Takeaways
  • 7. What x Is x State ? • It is the internal memory of a react component • State setter is the only trigger of the update phase in react • OK, may be useSyncExternalStore also, but not trivial • Some states need to be shared in a tree • Shared by prop drilling or wired via context Api. • Asynchronous states update state later.
  • 8. State crimes x And x State police • Cannot update state of unmounted component • Showing results of earlier request • No cancellations • No pending states • Poor error handling • Useless useEffects • Flashing old state • No sharing • The list doesn’t end here…
  • 9. State crimes x And x State police • Cannot update state of unmounted component
  • 10. State crimes x And x State police • Cannot update state of unmounted component
  • 11. State crimes x And x State police • Cannot update state of unmounted component
  • 12. State crimes x And x State police • Problems with this code • The loading state isn’t a Boolean • Three pieces of states working and updated together • Boolean semaphore lock rather than Counting lock! • Doesn’t abort the previous call
  • 13. State crimes x And x State police • Cannot update state of unmounted component
  • 14. State crimes x And x State police • Cannot update state of unmounted component
  • 15. State crimes x And x State police • Cannot update state of unmounted component
  • 16. State crimes x And x State police • Showing results of earlier request
  • 17. State crimes x And x State police • Showing results of earlier request
  • 18. State crimes x And x State police • No cancellations • AbortController
  • 19. State crimes x And x State police • No cancellations
  • 20. State crimes x And x State police • No cancellations
  • 21. State crimes x And x State police • No cancellations
  • 22. State crimes x And x State police • No cancellations
  • 23. State crimes x And x State police • No pending states
  • 24. State crimes x And x State police • No pending states • Exact status • The data relative to the status • The date at which this piece of state was constructed • The props that led to that state outcome, may be used for optimistic UI.
  • 25. State crimes x And x State police • Poor error handlig
  • 26. State crimes x And x State police • Useless effects • Could be done in event handlers • Only to reset state from props • Effects are only for synchronization and subscription
  • 27. State crimes x And x State police • Useless effects • Could be done in event handlers • Only to reset state from props • Effects are only for synchronization and subscription
  • 28. State crimes x And x State police • Flashing old state • Previous state shows for few Millis and then we start a pending state (if lucky enough!)
  • 29. State crimes x And x State police • Manipulating refs and using state to re-render • The list doesn’t end here…
  • 30. State crimes x And x State police • Linters provide great help to follow the rules of hooks • Rules of hooks • Exhaustive deps • … • Blog posts and tutorials try their maximum to share good practices • Dan’s overreacted blog • Kent’s blogs and learning material • Community libraries makes our life easier • UI libraries • State managers • XState • State managers leverage the complexity but create bad habits. • React Strict Mode
  • 31. State x Management x Aspects • Sharing • Subscriptions • Asynchronous flows • Cancellations • Forks • Effects: debounce, throttle, delay… • Caching (with/without persistence) • React/root independent
  • 32. • Sharing State x Management x Aspects
  • 33. • Subscriptions State x Management x Aspects
  • 34. • Subscriptions State x Management x Aspects
  • 35. • Asynchronous flows State x Management x Aspects
  • 36. • Cancellations • Generators support • Async/await support via isAborted • Abort callbacks registration and invalidation State x Management x Aspects
  • 37. • Forks • Replicate behavior for a new tree State x Management x Aspects
  • 38. • Effects: debounce, throttle, delay… State x Management x Aspects
  • 39. • Caching (with/without persistence) • Invalidate and refetch when timed-out • Only invalidate when requested and state State x Management x Aspects
  • 40. • React/root independent State x Management x Aspects
  • 41. State x Management x Aspects
  • 42. State x Management x Aspects
  • 43. Conclusion x And x Takeaways • State is the only trigger of updates in react (re-renders). Ok, useSES! • State setter must be secured from old and stale closures, not only unmount. • If React.useCallback could just invalidate the previous callback when deps change! • Status is mandatory when dealing with asynchronous states • useEffect should not be abused and events should perform more work • State managers offers great help dealing with state • Community resources are a gem that should be considered more • We are all state criminals

Editor's Notes

  1. React defines itself as a javascript library for building user interfaces.
  2. But expert people tend often to call it A ui runtime that runs components or elements of different tags: like function component, class component, memo and simple memo, suspense, suspense list, … and so on.   all the components we write are either class components or functions components, but I think class components became only for error boundaries, which is debatable.
  3. If we take a close look at the react codebase we'll notice that its composed of several packages like react, reconciler, scheduler, react-dom, and so many more… these packages are responsible for the whole logic behind the mechanics of react that allow us to run components inside its work loop and delegate communication with the host environment to the renderer. All of these aspects deserve talks on their own, so may be next time as today is only for state management.
  4. I am mohamed el ayadi, a senior software engineer at xhub. I have a decade of experience around java and javascript ecosystems. You can find me on twitter via incepterr
  5. So today, I ll speak about state, revisit major aspects of it and do a retrospection about all the crimes we've and continue to do with state, then talk briefly about state police. Then, we'll discuss the state management aspects and the challenges to manage state in a scalable and effective way, then finish by a conclusion and some takeaways
  6. React as we said, run components of different tags, these components do not render one time but render thousands of times during runtime, state is the memory they preserve and manipulate during their life.   More technically, it is a piece of memory associated to your component until it unmounts and get garbage collected. Altogether with a function that tells react that the value of the state changed, we call it :the updater, or state setter.     So, Why is state the most important thing in react ? Because your app will remain static until you call a state setter, or in other terms: State setter is the only trigger of the update phase in react. This means, you can't have a dynamic react application without calling a state setter. React has three state setters: the dispatch function from useReducer, setState from useState, and this.setState for class components.   Ok, may be useSES also allows scheduling updates on components, but not trivial to be used and will be highly challenging.   State is created in the component scope, so only accessible to that component. If you want to share it, you will have to drill it down via props or wire it via context.   States often needs to be shared in multiple directions in the app and multiple execution contexts, the common way to do so is to declare it at the nearest common parent of all the pieces that need that state.   Some states change later in time after some work is done, we call them asynchronous states because they emit changes to the component over time through the state setter. And these are the most dangerous ones, and we’ll discover how in a few
  7. So as we said, we must use state to have a dynamic application with logic and behavior, but state usage is often abused and lead to unexpected things, I collected many bad and anti patterns and called them State crimes. We'll be discovering this list today:
  8. The first crime on the list is this warning, the one you will find the most in applications:   Cannot update state of unmounted component   Who did already come across this warning ?   It says "can…..", which means, you sent your state setter somewhere as a callback, then you unmounted without saying that your state setter should do nothing anymore, because you are not here anymore!   Well! What I just said proves that this warning is more general and not only related to unmount but react only warns about it in this case! I think that even dependencies change should emit a warning like this! But I understand that’s it’s hard or impossible to be tracked correctly.
  9. This warning generally comes from patterns like this   where you perform some work, then asynchronously update the state later   or where we subscribe to something that emits updates without unsubscribing!
  10. This pattern is all over our applications, in fact, imagine that you have a button that calls a performSearch function, that set the loading indicator to true, search by the given values, then set data or error, and finally alter the loading indicator.  
  11. This code should only live in demos and not go to production in enterprise application, because here are some of the flaws that it suffers from: The loading isn't a boolean! Declares three pieces of state that works together! The boolean loading should use a counting semaphore lock and not booleans Doesn't abort the previous call or care about it And other issues
  12. This warning also comes from effects like this one   where you execute an async flow when a dep changes then set the state later   now what will happen if your component unmounts or deps change and the order of execution isn't the same as the order of resolve ? You will likely have wrong shown results in the screen.
  13. Effects that subscribe without unsubscribe to external things also are affected by this issue So I just subscribe, without telling that: hey, I don't need this anymore
  14. As a general solution, Im proposing this: where you perform a double cleanup: from the subscription if provided, or else, even if the unsubscribe fn isn't working or buggy or forgotten, my cleanup would mark a closure variable that it is stale and should no longer affect my current state by scheduling stale updates
  15. Now, let's go back to our search example, and add a small ingredient that you may find in real life: the more you add filters, the more likely your request is to respond fast, because may be you are adding a join that would just skip over millions of lines. So let's make our search behave the same: the longer our search term, the faster our response will be.   This code now suffers huge problems: The first request that responds will mark the loading indicator as false, so even if others are still occurring in the background, there will be no loading indicator anymore The second huge flaw is that later search will resolve before the former, sor the results on the screen are totally wrong   There are two easy solutions to this involving closures and capturing variables, and also abort callbacks registration.
  16. I wrote about this problem specifically in a blog post that I encourage you to read if not already to fully grasp this issue and learn easy solutions to it.
  17. Talking of the devil, the next crime is that we don't set cancellations in our asynchronous flows meaning if we send two requests that downloads a file of 5mb each time we never cancel the previous and we still download all that unnecessary data.
  18. Fetch requests either with the fetch api or axios are now cancellable via abort signal, but sometimes it is hard to achieve if not using the right tools, for example, it is so complex to setup with redux and redux saga. The ideal scenario would be being able to register abort callbacks via an onabort api, which the AbortSignal started already to support.
  19. But again, not everything in our beloved language supports cancellations, for example the raw promise chain or the async/await syntax doesn't allow you to stop its execution. If you async await function starts, it cannot be interrupted unless after every await you check if an isAborted() function says yes or no.
  20. But, using generators may allow this, since, with a generator runner, you can decide not to step in the previous yield:
  21. For example, here a small generator runner I wrote back then that allows this.
  22. The next crime on the list is no pending states. Who can relate to this ? When you go rampage clicking on a button and receiving no feedback of what's going on, you don't know whether the request is sent or not
  23. As a simple solution, just set the following shape for all asynchronous states you have: Let's see what you ll need: the status, being an enum of the supported values The data that goes with that status The timestamp at which the state was created And the props that led to that state outcome, if you want to perform some optimistic UI or enhanced UX/UI stuff.
  24. Poor error handling, when you receive a generic error message for every bad thing that happens, and your users need now to call the admin to investigate what's happening, and may be call someone from the devteam to read the logs for them and try to know what happened. So always setup a mechanism that allows you to show the precise exact error definition to the user, and if possible, the error ID that would help the production teams find the error easily
  25. useEffect is probably the most hated hook right now as many people advice to quit using it for many reasons   But one thing we all agree on, is that useEffect was abused.   Quoting these usages from the beta docs where it shows a pattern that was widely used but suffers some errors: For example, this timer get reset everytime I change the increment by which I want to increment it! But In general I should not be resetting it, if I go into a continuous changing of the increment, the counter will never change its value 0.
  26. To fix this, react are introducing a new hook called useEvent
  27. The next crime on the list is when you use a state and you don't reset it at the end when deps change or component unmounts and this state is widely shared     Look at this code, and tell me what will happen if we don't have a cleanup function that disconnects from the chat, there is a typo in the disconnect function, so it isn't working anyways.   If you don't cleanup previous subscriptions or save yourself from them, every incoming message from all previously visited channels, will be shown in the current conversation.
  28. Enough crimes, or may be the last one, the one I should take Guinness record on it may be! It is declaring a ref and mutating it, and reding from it during render, and adding a state variable that only rerenders when you want
  29. Enough crimes. The big challenge about these crimes is being able to identify them and help your teammates deal with them with ease.   Linters also provide a good help, for example eslint react plugin offers plenty of customizable rules that you may consider, rules of hooks and exhaustive deps are a must though.   Blog posts and community efforts are way noticeable and helped us all level up and use better state.   I recommend dan abramov's blog overreacted.io, it contains some really good reading material about react in general, and I am sure you will never look at react the same after you go though it.   Kent c dodds material is also some good stuff that you may consider dedicating yourself to, you will learn basics of react, really basics, with testing and good habits.   The libraries out there offer a great help dealing with all the complexity and repetitive stuff that you find yourself doing all the time, like the ui libraries that hide a lot of states internally with there transitions and give you component ready to use and you only supply the props xState and state managers also provide a great help and leverage the whole complexity, but they create in general bad habits, bad habits of not knowing sufficiently the tools you are using that we start just doing crimes anywhere.   The react strict modes also does everything twice in development mode so it enforces you to write components that are pure functions around state and props. But good luck with that with strict effects with react 18 or later, especially if you ll have to migrate some codebase. Because even effects are fired with their cleanups twice.
  30. Now that we are more aware of the things that we really need to manipulate state, let's talk about state management and its aspects, like sharing, subscriptions, async flows, cancellations etc
  31. The first aspect is that I should be able to share my state across my whole app, or at least at a some scopes It doesn't matter the level at which I am, but I should be able to read and write to some state. That's how a state manager should offer me state.
  32. Subscriptions is being able to be notified by every change that occurs at any point of time, unless I decide to stop via an unsubscribe that the subscribe should return. Subscriptions is being able to be notified by every change that occurs at any point of time, unless I decide to stop via an unsubscribe that the subscribe should return.   The best level of state sharing is to be able to share that piece of memory of the state, the reference of the object it points to, inter-react-rroot, inter-javascript framework, or even with vanilla javascript!  
  33. The following screenshot with the best css in the world is using a subscription from two different react roots and from vanilla javascript to the same piece of state: I was playing the other day and came up with this, where the state is not bound to react, but to javascript. Even react now encourages having your state away of react, and it even provided a second trigger of the update phase for that: useSyncExternalStore, that uses a subscribe function to your state. This is how state should be treated.
  34. Asynchronous flows, so that's the big deal, because your SPA or application will be often interacting with your api server and displaying the results.   So you should be able to use the javascript language API to address asynchrounousy, like Promise, async/await syntax, and pushes to you the status so you can do better ui and better user experience.
  35. Cancellations, So we are now aware of the importance of cleanups and cancellations in general, our state managers should allow us to do them. If your library is only supporting fetch via AbortController and signal APIs, then may be you should ask for an onAbort function that will let you work with any asynchronous flow.
  36. Forks are a feature that is underrated all the time, in fact, it allows you to use the same behavior as something, while having new subscribers and piece of state in memory.
  37. Our state managers should allow us to perform effects on our runs: we may want to throttle them, debounce them, delay them and many more options, ideally they should also offer a way to completely skip the pending state if the requests resolves fast.
  38. Caching is a really good aspect, but it should not be abused because the cache problems are hard to spot And hard to debug and maintain.   Although, it means nothing that I should perform a request to the server at every user click on the search button, I mean, like if he goes rampage on clicking it! It would be a waste if you through all of them at your server.
  39. Like I mentioned before, our state managers should be react independent and allow us to manipulate state from anywhere, even from another app and react to updates. This is not trivial, but if you deeply think about it, it really simple, a piece in memory, a subscribe function and a getState, setState and run functions and you are done! You can manipulate that state from anywhere!
  40. So I gathered these aspects and searched through the popular state managers or state manipulators to see how it s going. Empty redux is nothing and can’t do much, but with the right middlewares it becomes interesting. Recoil was interesting in its early days, but I think it is not something that will have so much success. React query on the other hand has a lot of interesting features, But can be way better.
  41. And here is my little stuff that I ve been working on lately A state manager that defies all the others and supports features like never seen before in the react land. But it is still in early phases since I am the only one working on it and I lack time. But in few words, It is a low level and multi paradigm state management solution for javascript. It started with react but now it is heading towards working in all environments where javascript is, with interleaved capabilities, which means I can subscribe and manipulate my state whenever I am in the v8 engine, from react, angular, vanilla or whatever
  42. Ouf, that's been a lot of information, hope you enjoyed it and you learned a thing or two. So if we want to recapitulate what I've said:
  43. Hello everyone and welcome to my talk So today we are gonna talk about react and state, we’ll go through a long retrospection about state Before we start, I would like to know how many of you already used react ? ok may be more than 2 years ? 4 years ?