SlideShare una empresa de Scribd logo
1 de 17
Managing state in modern
React web applications
Hello!
• Jon Preece, front-end developer
• Currently specializing in React
• Active on GitHub: jpreecedev
• Email: jonpreece@hotmail.co.uk
(I’m not on social media, sorry!)
Assumptions
• Intermediate knowledge of JavaScript and React
• This is a presentation about React
• React 16.3 or higher
• (This was when the updated version of Context API was first released)
• Feel free to ask questions
What is state?
• Allows you to create components that are
dynamic and interactive
• Allows your application to respond to;
• User actions, network responses, anything else
What tools are at your disposal?
• Local state
• Context API
• Redux
• (And many, many more)
Which one should I choose?
Which one should I choose?
• It’s not quite that simple
• Local state works well with forms
• Context API is hierarchical, helps with
*prop drilling*
• Redux works well when sharing
Demo 1: Local state
• Form gets passed an initial state
• Container/presentation component relationship,
form data is passed up
• Form can be reset after user has made changes
• We call setState instead of mutating state directly
Local state
• State for the form is contained
• Calling setState causes the component to re-
render, can be asynchronous and batched
• There is hidden pain here
Demo 2: Context API
• What do we mean by *prop drilling*?
• What does Context API look like?
• Provider, Consumer
Context API
• Provider exposes state to Consumer
• Provider is a fancy wrapper around setState
• Can dramatically tidy your code, has little
learning curve, easy to conceptualise, is
syntactically fiddly
Demo 3: Redux
• Always has a root level Provider with a default state
• Uses connect function to retrieve state from the
store
• Dispatches an action, triggers a reducer, which
creates a new state, which causes a re-render
Redux
• More complexity
• Actions, reducers, connect, immutable
• Scales well, performant
• Excellent debugging, time travel, unit testing is
straightforward
Best practices / Common Patterns
• Do use the right tool for the job
• Redux is not dead
• Start with Context API, add Redux if/when
needed
• Avoid *prop drilling*
• Generally avoid local state, becomes unwieldly
quickly, increases test complexity
Best practices / Common Patterns
• When working with local state, prefer
container/presentation relationship
• Avoid ref
• Lift the state up
Summary
• Know tools at your disposal
• Finally… this space is still evolving.
• GraphQL and Apollo Client are gaining popularity quickly
Hello!
• Jon Preece, front-end developer
• Currently specializing in React
• Active on GitHub: jpreecedev
• Email: jonpreece@hotmail.co.uk

Más contenido relacionado

La actualidad más candente

Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
Thinkful
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
 

La actualidad más candente (20)

The dream BEAM - A former DevOps perspective
The dream BEAM - A former DevOps perspectiveThe dream BEAM - A former DevOps perspective
The dream BEAM - A former DevOps perspective
 
Основы функционального JS
Основы функционального JSОсновы функционального JS
Основы функционального JS
 
Automating and Testing a REST API
Automating and Testing a REST APIAutomating and Testing a REST API
Automating and Testing a REST API
 
Introduction to Python Programming
Introduction to Python Programming Introduction to Python Programming
Introduction to Python Programming
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Life after Calc core change
Life after Calc core changeLife after Calc core change
Life after Calc core change
 
Server side story
Server side storyServer side story
Server side story
 
How To Write a Testable Code
How To Write a Testable CodeHow To Write a Testable Code
How To Write a Testable Code
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
 
Data consistency: Analyse, understand and decide
Data consistency: Analyse, understand and decideData consistency: Analyse, understand and decide
Data consistency: Analyse, understand and decide
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
 
Accelerate Quality with Postman - Basics
Accelerate Quality with Postman - BasicsAccelerate Quality with Postman - Basics
Accelerate Quality with Postman - Basics
 
Flow control in Python
Flow control in PythonFlow control in Python
Flow control in Python
 
Immutable, performance and components communication
Immutable, performance and components communicationImmutable, performance and components communication
Immutable, performance and components communication
 
Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)
 
Water Boy, my robotic co-worker
Water Boy, my robotic co-workerWater Boy, my robotic co-worker
Water Boy, my robotic co-worker
 
2020-Feb: Testing: Cables and Chains
2020-Feb: Testing: Cables and Chains2020-Feb: Testing: Cables and Chains
2020-Feb: Testing: Cables and Chains
 
Generating unit tests based on user logs
Generating unit tests based on user logsGenerating unit tests based on user logs
Generating unit tests based on user logs
 
Design & Prototype an API
Design & Prototype an APIDesign & Prototype an API
Design & Prototype an API
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder Meetup
 

Similar a Managing state in modern React web applications

React.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIReact.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UI
Marcin Grzywaczewski
 

Similar a Managing state in modern React web applications (20)

React Native Firebase
React Native FirebaseReact Native Firebase
React Native Firebase
 
Introduction to react native with redux
Introduction to react native with reduxIntroduction to react native with redux
Introduction to react native with redux
 
Meteor + React
Meteor + ReactMeteor + React
Meteor + React
 
React.js at Cortex
React.js at CortexReact.js at Cortex
React.js at Cortex
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - Material
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
React introduction
React introductionReact introduction
React introduction
 
Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)
 
Performance Tuning with XHProf
Performance Tuning with XHProfPerformance Tuning with XHProf
Performance Tuning with XHProf
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
 
OOP -interface and objects.pptx
OOP -interface and objects.pptxOOP -interface and objects.pptx
OOP -interface and objects.pptx
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Testing - How Vital and How Easy to use
Testing - How Vital and How Easy to useTesting - How Vital and How Easy to use
Testing - How Vital and How Easy to use
 
React.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIReact.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UI
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
Redux Tech Talk
Redux Tech TalkRedux Tech Talk
Redux Tech Talk
 
Denver Salesforce Developer User Group dec 2016 lightning components
Denver Salesforce Developer User Group dec 2016 lightning componentsDenver Salesforce Developer User Group dec 2016 lightning components
Denver Salesforce Developer User Group dec 2016 lightning components
 
CPP11 - Function Design
CPP11 - Function DesignCPP11 - Function Design
CPP11 - Function Design
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
 

Último

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Último (20)

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Managing state in modern React web applications

  • 1. Managing state in modern React web applications
  • 2. Hello! • Jon Preece, front-end developer • Currently specializing in React • Active on GitHub: jpreecedev • Email: jonpreece@hotmail.co.uk (I’m not on social media, sorry!)
  • 3. Assumptions • Intermediate knowledge of JavaScript and React • This is a presentation about React • React 16.3 or higher • (This was when the updated version of Context API was first released) • Feel free to ask questions
  • 4. What is state? • Allows you to create components that are dynamic and interactive • Allows your application to respond to; • User actions, network responses, anything else
  • 5. What tools are at your disposal? • Local state • Context API • Redux • (And many, many more)
  • 6. Which one should I choose?
  • 7. Which one should I choose? • It’s not quite that simple • Local state works well with forms • Context API is hierarchical, helps with *prop drilling* • Redux works well when sharing
  • 8. Demo 1: Local state • Form gets passed an initial state • Container/presentation component relationship, form data is passed up • Form can be reset after user has made changes • We call setState instead of mutating state directly
  • 9. Local state • State for the form is contained • Calling setState causes the component to re- render, can be asynchronous and batched • There is hidden pain here
  • 10. Demo 2: Context API • What do we mean by *prop drilling*? • What does Context API look like? • Provider, Consumer
  • 11. Context API • Provider exposes state to Consumer • Provider is a fancy wrapper around setState • Can dramatically tidy your code, has little learning curve, easy to conceptualise, is syntactically fiddly
  • 12. Demo 3: Redux • Always has a root level Provider with a default state • Uses connect function to retrieve state from the store • Dispatches an action, triggers a reducer, which creates a new state, which causes a re-render
  • 13. Redux • More complexity • Actions, reducers, connect, immutable • Scales well, performant • Excellent debugging, time travel, unit testing is straightforward
  • 14. Best practices / Common Patterns • Do use the right tool for the job • Redux is not dead • Start with Context API, add Redux if/when needed • Avoid *prop drilling* • Generally avoid local state, becomes unwieldly quickly, increases test complexity
  • 15. Best practices / Common Patterns • When working with local state, prefer container/presentation relationship • Avoid ref • Lift the state up
  • 16. Summary • Know tools at your disposal • Finally… this space is still evolving. • GraphQL and Apollo Client are gaining popularity quickly
  • 17. Hello! • Jon Preece, front-end developer • Currently specializing in React • Active on GitHub: jpreecedev • Email: jonpreece@hotmail.co.uk

Notas del editor

  1. State is what makes your application interesting.
  2. When discussing, ”Many, many more” be sure to mention that there is a list of the most popular libraries on a Hackernoon post called ‘The React State Museum” (https://hackernoon.com/the-react-state-museum-a278c726315) What do I mean when I talk about Local State? I’m specifically talking about using the function `setState`, which comes out of the box with React Local state refers to state which is contained inside a single component, usually in a container/dumb component relationship Local state has been a part of React *forever* Context API was experimental until 16.3 when a new revised version was released. React-Redux is a thin wrapper over the legacy Context API. Context API is hierarchical by design, so only applies to a component and all its children. You can put Context API at the root of the application, but if you have multiple applications running on the same page they wont be able to share stata. And also, for everything more than the most basic applications, I see this becoming un-wiedly very quickly. Redux keeps the state of your application in a single place, called the store. The store is immutable and cannot be updated directly. To update the store, you call a function (called a reducer) which makes the changes, which updates the store, which causes your application to re-render. State is the data, store is where the data is kept.
  3. One does not simply choose a state management tool Know your API’s / libraries There is no reason why you can’t have local state, Redux & Context API all working together in a single application You probably wouldn’t want to choose multiple tools such as Redux, MobX and Unstated in a single React application, because that would add several paradigms and increase complexitity.
  4. One does not simply choose a state management tool. Know your tools Local State is perfect for normal forms such as log in forms, registration forms, your e-commerce sites checkout, etc. I like to use local state when I’m handling data that isn’t final yet. Context API has a Provider/Consumer pattern. At the root of a component hierarchy (or the root of your application) sits a provider component which contains the state and functions to change the state. The consumer is used on a component anywhere in the same hierarchy, meaning that state doesn’t have to be passed down the tree (called prop drilling) Redux is strikingly similar to Context API in that it effectively has a Provider/Consumer pattern, although its less obvious. The main difference is that instead of having potentially many different states, there is a single state contained within a global store, that can be accessed using a function called `connect`, which can be used to access the state and pass that state through to the component.
  5. setState is only asynchronous when passed a function, which returns the current state. When called with an object, the function call is executed synchronously. In the interest of future proofing your code (I’m thinking about React Fiber here), you should write your code to work asynchronously. What is the hidden pain? This is a fairly contrived example where we are passing an initial state object to the registration form. What happens, if, after the form has been rendered the first time, the initialState object gets changed, causing a re-rendering? Answer: The registration form will not be reflect the changes, because the local state never gets updated. We used to have a component lifecycle method called ComponentWillReceiveProps, which would pass you the local state and the updated props so you could update your component accordingly, but this lifecycle method has recently been deprecated and will be removed entirely from React in the next major version release.
  6. Context API to me is really just a wrapper around setState. To use Context API, I wrap the Provider up in a React component, which also carries the state and functions to update the state. Then I use a Consumer to acess the state and those functions to change the state when there is some kind of interaction from the user. Can tidy the code because you don’t have calls to setState all over the place, you get given a state object, which you can deconstruct off you state manipulation functions. No need to say ‘this.state.myProp’ either, just ‘myProp’., which reduces noise. This pattern is easy to conceptualise and reason about, making it approachable to developers of all levels. I have a few complaints. Almost all examples will show usages of the Conumer with ES6 arrow functions and destructuring. Also because of JSX we have to throw in an extra set of curly braces. This makes it syntactically fiddly, even with editor tools such as ‘Indent Rainbow’ and ‘Bracket Pair Colorizer’ I still find myself awkwardly trying to get my brackets to match up. Mention that Enzyme test framework has poor support for Context API currently, although there are workarounds, and this will likely improve in upcoming major releases.
  7. Why is unit testing straight forward? Your component is often just a stateless functional component, which takes props and has no other external dependencies. In short, your component is a function that takes input and returns output in a simple way. Usually your component will have a default export that connects your component to the Redux store. However, for the sake of unit testing you can simply export your function as-is, avoiding any complete set up, mocking of stores, providers etc, resulting in smaller, cleaner test suite.