SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PDF
The dream BEAM - A former DevOps perspective
Jeffrey Chan
Ā 
PPTX
ŠžŃŠ½Š¾Š²Ń‹ Ń„ŃƒŠ½ŠŗŃ†ŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ JS
Анна Š›ŃƒŃ†ŃŒ
Ā 
PDF
Automating and Testing a REST API
Alan Richardson
Ā 
PPTX
Introduction to Python Programming
Md. Shafiuzzaman Hira
Ā 
PPTX
Function in Python
Md. Shafiuzzaman Hira
Ā 
ODP
Life after Calc core change
Kohei Yoshida
Ā 
PDF
Server side story
Simone Deponti
Ā 
PPTX
How To Write a Testable Code
OPIN Software Inc.
Ā 
PDF
Intro to javascript (6:19)
Thinkful
Ā 
PDF
Data consistency: Analyse, understand and decide
Louis Jacomet
Ā 
PPTX
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
Ā 
ODP
Accelerate Quality with Postman - Basics
Knoldus Inc.
Ā 
PPTX
Flow control in Python
Md. Shafiuzzaman Hira
Ā 
PDF
Immutable, performance and components communication
Hsuan Fu Lien
Ā 
PDF
Reactive Programming or Reactive Systems? (spoiler: both)
Fabio Tiriticco
Ā 
PPTX
Water Boy, my robotic co-worker
Sean Walberg
Ā 
PDF
2020-Feb: Testing: Cables and Chains
Mark Windholtz
Ā 
PPTX
Generating unit tests based on user logs
Rick Wicker
Ā 
PDF
Design & Prototype an API
Postman
Ā 
PDF
Actor Patterns and NATS - Boulder Meetup
Apcera
Ā 
The dream BEAM - A former DevOps perspective
Jeffrey Chan
Ā 
ŠžŃŠ½Š¾Š²Ń‹ Ń„ŃƒŠ½ŠŗŃ†ŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ JS
Анна Š›ŃƒŃ†ŃŒ
Ā 
Automating and Testing a REST API
Alan Richardson
Ā 
Introduction to Python Programming
Md. Shafiuzzaman Hira
Ā 
Function in Python
Md. Shafiuzzaman Hira
Ā 
Life after Calc core change
Kohei Yoshida
Ā 
Server side story
Simone Deponti
Ā 
How To Write a Testable Code
OPIN Software Inc.
Ā 
Intro to javascript (6:19)
Thinkful
Ā 
Data consistency: Analyse, understand and decide
Louis Jacomet
Ā 
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
Ā 
Accelerate Quality with Postman - Basics
Knoldus Inc.
Ā 
Flow control in Python
Md. Shafiuzzaman Hira
Ā 
Immutable, performance and components communication
Hsuan Fu Lien
Ā 
Reactive Programming or Reactive Systems? (spoiler: both)
Fabio Tiriticco
Ā 
Water Boy, my robotic co-worker
Sean Walberg
Ā 
2020-Feb: Testing: Cables and Chains
Mark Windholtz
Ā 
Generating unit tests based on user logs
Rick Wicker
Ā 
Design & Prototype an API
Postman
Ā 
Actor Patterns and NATS - Boulder Meetup
Apcera
Ā 

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

PPTX
STATE MANAGEMENT IN REACT [Autosaved].pptx
siddheshjadhav919123
Ā 
PPTX
React workshop
Imran Sayed
Ā 
PPTX
Redux
Maulik Shah
Ā 
PPTX
Introduction to react and redux
Cuong Ho
Ā 
PPTX
React Workshop: Core concepts of react
Imran Sayed
Ā 
PDF
Handling State in React: Context API vs. Redux
Uncodemy
Ā 
PDF
A Blog About Using State in Next.js: Valuable Insights
Shiv Technolabs Pvt. Ltd.
Ā 
PDF
Building React Applications with Redux
FITC
Ā 
PDF
A React Journey
LinkMe Srl
Ā 
PPTX
React + Flux = Joy
John Need
Ā 
PDF
2018 02-22 React, Redux & Building Applications that Scale | React
Codifly
Ā 
PPTX
Getting started with react & redux
Girish Talekar
Ā 
PDF
The Road To Redux
Jeffrey Sanchez
Ā 
PDF
React Interview Question & Answers PDF By ScholarHat
Scholarhat
Ā 
PDF
Learning React js Learn React JS From Scratch with Hands On Projects 2nd Edit...
bandmvh3697
Ā 
DOCX
React Components and Its Importance.docx
React Masters
Ā 
PDF
React
Amitai Barnea
Ā 
DOCX
React JS Components & Its Importance.docx
React Masters
Ā 
PDF
React JS and why it's awesome
Andrew Hull
Ā 
PPSX
React introduction
Kashyap Parmar
Ā 
STATE MANAGEMENT IN REACT [Autosaved].pptx
siddheshjadhav919123
Ā 
React workshop
Imran Sayed
Ā 
Redux
Maulik Shah
Ā 
Introduction to react and redux
Cuong Ho
Ā 
React Workshop: Core concepts of react
Imran Sayed
Ā 
Handling State in React: Context API vs. Redux
Uncodemy
Ā 
A Blog About Using State in Next.js: Valuable Insights
Shiv Technolabs Pvt. Ltd.
Ā 
Building React Applications with Redux
FITC
Ā 
A React Journey
LinkMe Srl
Ā 
React + Flux = Joy
John Need
Ā 
2018 02-22 React, Redux & Building Applications that Scale | React
Codifly
Ā 
Getting started with react & redux
Girish Talekar
Ā 
The Road To Redux
Jeffrey Sanchez
Ā 
React Interview Question & Answers PDF By ScholarHat
Scholarhat
Ā 
Learning React js Learn React JS From Scratch with Hands On Projects 2nd Edit...
bandmvh3697
Ā 
React Components and Its Importance.docx
React Masters
Ā 
React
Amitai Barnea
Ā 
React JS Components & Its Importance.docx
React Masters
Ā 
React JS and why it's awesome
Andrew Hull
Ā 
React introduction
Kashyap Parmar
Ā 
Ad

Recently uploaded (20)

PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
Ā 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
Ā 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
Ā 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
Ā 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
Ā 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
Ā 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
Ā 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
Ā 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
Ā 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
Ā 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
Ā 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
Ā 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
Ā 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
Ā 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
Ā 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
Ā 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
Ā 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
Ā 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
Ā 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
Ā 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
Ā 
Import Data Form Excel to Tally Services
Tally xperts
Ā 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
Ā 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
Ā 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
Ā 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
Ā 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
Ā 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
Ā 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
Ā 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
Ā 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
Ā 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
Ā 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
Ā 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
Ā 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
Ā 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
Ā 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
Ā 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
Ā 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
Ā 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
Ā 
Ad

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: [email protected] (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: [email protected]

Editor's Notes

  • #5: State is what makes your application interesting.
  • #6: 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.
  • #7: 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.
  • #8: 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.
  • #10: 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.
  • #12: 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.
  • #14: 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.