Taming the State Management Dragon

Rate this content
Bookmark

We spend a lot of time discussing which state library we should use, and fair. There are quite a few, from the common one everyone uses and loves to hate on, to that one quirky alternative, to several up and comers. However, discussing which library is best puts the cart before the horse.

When figuring out how to handle state, we should first ask ourselves: what different categories of state do we need? What are the constraints of each category? How do they relate to each other? How do they relate to the outside world? How do we keep them from becoming a giant, brittle ball of yarn? And more.

This might sound overwhelming, but never fear! In this talk, I'll walk you through how to answer these questions, and how craft an approachable, maintainable, and scalable state system. And yes, I will talk about how to pick a state management library too.

This talk has been presented at React Summit US 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

Reactive data is state that responds to user interactions, such as composing a new post, and involves managing various user inputs and server interactions.

Local state is used by a single component, global state is accessible across the entire application, and regional state is used by multiple components but not the entire application.

Common state management libraries include Redux, Zustand, Recoil, and Jotai.

React context is used to manage regional state by scoping it to a specific part of the component tree, ensuring that only specific components can access the state.

State is defined as data and all of its related mechanisms, including how data is accessed, read, updated, and synchronized.

State management is critical for having a successful frontend code base as it ensures the smooth handling and synchronization of data across the application.

The three categories of state are: 1) Bootstrap Data (created before startup), 2) Lazily Loaded Data (deferred bootstrap data), and 3) Reactive Data (state in response to user interaction).

Bootstrap data is state created before the application startup, often used in server-side rendering to assemble all required data for the initial render.

Lazily loaded data is data not present during the initial rendering but necessary to display the UI as the user interacts with the application.

Brian Hughes is a staff frontend engineer at Patreon, responsible for managing the foundations of the frontend code base, including architecture and state management.

Bryan Hughes
Bryan Hughes
23 min
15 Nov, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This Talk discusses various aspects of state management in software development. It covers different types of state, such as bootstrap data, lazily loaded data, and reactive data. The Talk also explores the concept of locality in state management, including local, global, and regional state. It introduces libraries like Recoil and Jotai that challenge the single global store concept and provide better locality. The Talk emphasizes the importance of setting up state management systems for success and creating reliable systems to focus on user satisfaction.

1. Introduction to State Management

Short description:

Hi, everyone. My name is Brian Hughes, and I'm a staff frontend engineer at Patreon. Today I want to talk about some things I've learned over the years of how to build successful state management solutions inside of applications. State is not just data, it's how we access, read, update, and synchronize data. It's more than just libraries, it's the entire house. When designing a state management solution, one important question to ask is when is state created? There are three categories of state: bootstrap data, pre-interaction state, and dynamic state.

Hi, everyone. My name is Brian Hughes, and I'm a staff frontend engineer at Patreon. At Patreon, I'm on a team called frontend platform, and our team is tasked with managing basically all of the foundations for our frontend code base. And this includes architecture and state management. And today I want to talk about some things I've learned over the years of how to build successful state management solutions inside of applications. Because I think this is a really critical part to having a successful frontend code base. It's also one that tends to be under-invested in.

Let's start off with the definition. What is state? So I define state as data and all of its related mechanisms. We know that intrinsically I think that state isn't just data, right? Data's just a blob of, well, data. It's really how are we accessing that data? How are we reading that data? How are we updating it? How are we synchronizing it? So state is really its data and all of those mechanisms associated with it. The mechanisms are more than just libraries. I think a lot of times when we think of state, we're like, well, we've got this API schema coming from our backend and tells us what data we have. And we pick the state management library, Redux, recoil, Jotie, whatever, and that's it, right? But that's not it. Those are really important parts. The way I like to think of it is that our API schema, what data the backend returns and the libraries that we use to access this data, that's like the foundation of a house. It's really critical, of course, it's the foundation. But we also need walls and a roof and things like that too. And a real state management solution in an front-end application, especially any really reasonably complex application is we got to think about this holistically, we got to think about the entire house.

So whenever I'm going through and I'm designing a state management solution, either if it's for a whole new application, rewriting an old one, or even if it's just adding a new page to an already existing system, there's a handful of questions that I really like to ask myself. And we only have so much time today, so I'm just going to stick to two of the really important ones, or at least that I think are important, and I also think aren't talked about as much as I wish they were. So the first question is, when is state created? If we think about a front-end application, it's not a snapshot in time, right? It exists over time and it changes and reacts to user input, right? And so when is the state coming into being? Understanding that really informs what kind of a testing strategy do we need for it, what kinds of safeguards do we need for accessing and just all sorts of things. And it really depends on the answer to this question. And I think there are roughly three categories of state when it comes to this temporal nature. The first category is state that is created before startup, otherwise known as bootstrap data. And when we think about this, we'll take, for example, a social media site. We'll use that as an example through this talk. On a social media site, we load the page, the first thing we do is we see a bunch of posts. That is something that exists before we can even begin interacting. And so this happens, or at least one way it can be done is we can do this as part of bootstrap data in a modern server-side rendering type setup.

2. Data Assembly and Gotchas

Short description:

In Next.js, data for the first render is assembled by calling multiple back-end API endpoints and then starting the application. However, the creation and consumption of data are decoupled, and we need to keep them in sync. The data goes through multiple steps and is funneled along, passing through different places before being accessed. While implementing this is not complicated, it still requires writing and maintaining code, which comes with a cost.

Say with Next.js. And in this world, the idea is that we first, we assemble all of the data needed to do that first render. You know, we call our back-end, usually multiple back-end API endpoints, and we might do some hydration, massaging of data. We assemble all that together, and only then once we're done doing that do we start the application and do that first render.

And so there's a couple of gotchas to be aware of with this. And like I mentioned, this data creation and the data consumption, they're pretty decoupled. The way that data looks for example, in Next.js instead of that get-server-side-props function, the way we work with it, the way it looks and everything is usually different than whenever we're reading it from say inside of Redux or something like that. And so we just need to keep in mind that these are decoupled, and thus we need to actually think about keeping them in sync. Now, it's actually not that complicated to do in practice. Usually TypeScript is a great solution to this, but is still something that we have to think about, and thus we also have to maintain.

Another bit of a gotcha with this is this data goes through a couple of steps and it kind of gets funneled along. Like I said, we start off calling multiple endpoints to fetch different, oftentimes unrelated bits of data. We're fetching who is the current user, what is the list of most recent posts, what are the current trending topics, things like that. And we take all the disparate data and we kind of like squeeze it together into one ball. And we pass it along through a couple of different places. It goes into our top level component, we pass it off to our libraries to Redux say whenever we're initializing our store, only then to we break it apart and access it later. And again, this isn't particularly complicated to implement, but it is code. And anytime we implement, we have to write code to do a thing. No matter how simple that code is, it is still code that has to be maintained and is still code that can have a bug in it, and thus it comes with a cost.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
Using useEffect Effectively
React Advanced 2022React Advanced 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
React Query: It’s Time to Break up with your "Global State”!
React Summit Remote Edition 2020React Summit Remote Edition 2020
30 min
React Query: It’s Time to Break up with your "Global State”!
Top Content
Global state management and the challenges of placing server state in global state are discussed. React Query is introduced as a solution for handling asynchronous server state. The Talk demonstrates the process of extracting logic into custom hooks and fixing issues with state and fetching logic. Optimistic updates with mutation are showcased, along with the benefits of using React Query for data fetching and mutations. The future of global state management is discussed, along with user feedback on React Query. The Talk concludes with an invitation to explore React Query for server state management.
Jotai Atoms Are Just Functions
React Day Berlin 2022React Day Berlin 2022
22 min
Jotai Atoms Are Just Functions
Top Content
State management in React is a highly discussed topic with many libraries and solutions. Jotai is a new library based on atoms, which represent pieces of state. Atoms in Jotai are used to define state without holding values and can be used for global, semi-global, or local states. Jotai atoms are reusable definitions that are independent from React and can be used without React in an experimental library called Jotajsx.
Announcing Starbeam: Universal Reactivity
JSNation 2022JSNation 2022
27 min
Announcing Starbeam: Universal Reactivity
Starbeam is a library for building reactive user interfaces with JavaScript, similar to Svelte, Vue, and Ember. It provides a data structure and query feature for filtering and sorting. The useStarBeam function ensures JSX reconciliation only occurs when reactive dependencies change. Starbeam tracks every read and write operation to update the component accordingly. It can be used with React and other frameworks, and offers debugging tools and locale integration.
The Zen of Yarn
DevOps.js Conf 2022DevOps.js Conf 2022
31 min
The Zen of Yarn
Let's talk about React and TypeScript, Yarn's philosophy and long-term relevance, stability and error handling in Yarn, Yarn's behavior and open source sustainability, investing in maintenance and future contributors, contributing to the JavaScript ecosystem, open-source contribution experience, maintaining naming consistency in large projects, version consistency and strictness in Yarn, and Yarn 4 experiments for performance improvement.

Workshops on related topic

Rethinking Server State with React Query
React Summit 2020React Summit 2020
96 min
Rethinking Server State with React Query
Top Content
Featured Workshop
Tanner Linsley
Tanner Linsley
The distinction between server state and client state in our applications might be a new concept for some, but it is very important to understand when delivering a top-notch user experience. Server state comes with unique problems that often sneak into our applications surprise like:
- Sharing Data across apps- Caching & Persistence- Deduping Requests- Background Updates- Managing “Stale” Data- Pagination & Incremental fetching- Memory & Garbage Collection- Optimistic Updates
Traditional “Global State” managers pretend these challenges don’t exist and this ultimately results in developers building their own on-the-fly attempts to mitigate them.
In this workshop, we will build an application that exposes these issues, allows us to understand them better, and finally turn them from challenges into features using a library designed for managing server-state called React Query.
By the end of the workshop, you will have a better understanding of server state, client state, syncing asynchronous data (mouthful, I know), and React Query.
Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
Top Content
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
State Management in React with Context and Hooks
React Summit Remote Edition 2021React Summit Remote Edition 2021
71 min
State Management in React with Context and Hooks
WorkshopFree
Roy Derks
Roy Derks
A lot has changed in the world of state management in React the last few years. Where Redux used to be the main library for this, the introduction of the React Context and Hook APIs has shaken things up. No longer do you need external libraries to handle both component and global state in your applications. In this workshop you'll learn the different approaches to state management in the post-Redux era of React, all based on Hooks! And as a bonus, we'll explore two upcoming state management libraries in the React ecosystem.
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
 
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
 
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
 
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
From Idea to Production: React Development with a Visual Twist
React Summit 2023React Summit 2023
31 min
From Idea to Production: React Development with a Visual Twist
WorkshopFree
Omer Kenet
Omer Kenet
Join us for a 3-hour workshop that dives into the world of creative React development using Codux. Participants will explore how a visually-driven approach can unlock creativity, streamline workflows, and enhance their development velocity. Dive into the features that make Codux a game-changer for React developers. The session will include hands-on exercises that demonstrate the power of real-time rendering, visual code manipulation, and component isolation all in your source code.
Table of the contents: - Download & Setup: Getting Codux Ready for the Workshop- Project Picker: Cloning and Installing a Demo Project- Introduction to Codux Core Concepts and Its UI- Exercise 1: Finding our Feet- Break- Exercise 2: Making Changes While Staying Effective- Exercise 3: Reusability and Edge Case Validation- Summary, Wrap-Up, and Q&A