XState: the Visual Future of State Management

Rate this content
Bookmark

Learn about state modeling with state machines and statecharts can improve the way you develop your React applications, and get a sneak peek of never-before-seen upcoming visual tools that will take state management to the next level.

This talk has been presented at React Summit Remote Edition 2021, check out the latest edition of this React Conference.

FAQ

The speaker is David Courchide, known online as David K. Piano. He talks about the visual future of state management and how XState is contributing to that vision.

A visual formalism is a diagrammatic and intuitive yet mathematically rigorous language that clearly conveys relationships and logic through visual representations. It includes syntax and semantics to define what is allowed and how allowed things can behave.

XState aims to solve the complexity of state management by providing a way to represent state machines and state charts that are easily visualizable and mathematically rigorous. It helps centralize logic, prevent impossible states and transitions, and makes the application logic easier to understand and manage.

Unlike traditional reducers that mix logic with switch statements or if statements, XState cleanly separates behaviors into finite states and specifies transitions based on events. This approach prevents impossible states and makes the logic easier to visualize and manage.

Key features of XState include state-first management, automatic visualization, integration with various frameworks, utilities like use machine and use interpret for React, and strong TypeScript support. It also supports creating hierarchical state charts to manage complex logic.

Yes, XState is framework-agnostic and can be used with any framework, including React, Vue, Angular, Svelte, and more.

The use interpret hook is used to interpret a machine, create a service, and return that service as a single object. This service can be used within a React context to share state between components without causing unnecessary re-renders.

XState is designed to be efficient and minimize performance overhead. It is built to handle complex logic with ease and provides mechanisms like use selector to limit re-renders and improve application performance.

The vision for the future of XState includes tools that integrate code and diagrams, allowing developers to edit either to generate the other. This approach aims to make state management more intuitive and collaborative, enabling features like automatic test generation, analytics, and documentation.

A developer can get started with XState by reading the article 'You Don't Need a Library for State Machines,' which explains how to use state machines with basic JavaScript constructs. Transitioning to XState from there is straightforward and provides additional benefits like visualization and stronger typing.

David Khourshid
David Khourshid
35 min
14 May, 2021

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This Talk introduces the visual future of state management and how XState is bringing it to reality. It explains the role of reducers in containing application logic and how state machines and state charts provide a visual and mathematically rigorous way to represent behaviors. XState is easily integrable with React and other frameworks, allowing for the management of local, global, and semi-local state. The Talk also highlights new features in XState, such as the use of TypeScript for stronger typing and the introduction of the useSelector hook for improved performance. The future vision includes the combination of diagrams and code, with tools like Stately.ai, and the importance of explicit modeling of application logic using state machines.

1. Introduction to Visual Future of State Management

Short description:

Hey, everyone. My name is David Courchide. I want to talk to you today about the visual future of state management and how XState is going to bring that future vision to reality. State machines and state charts are visually exact diagrams that convey relationships in a visually unambiguous way. They have their own special notations and are mathematically rigorous languages. I recommend reading David Harrell's paper on visual formalisms for more information.

Hey, everyone. My name is David Courchide. I go by David K. Piano online on Twitter, GitHub, whatever. And I want to talk to you today about the visual future of state management and how XState is going to bring that future vision to reality.

So talking about visuals, you probably know what a Venn diagram is. It's a visual and an exact way of representing commonalities between two or more different things. And you might have also used a sequence diagram before to describe how different parts of a system communicate with each other. So, there's also state machines and state charts, of course, which I've been talking about for a while.

And state machines and state charts fall under this visually exact diagram category. Because diagrams like these are really useful in conveying relationships in a visually unambiguous way, and they each have their own special notations for denoting specific things. And so, with state charts, we have the same type of thing. We have arrows and boxes just describing how states and logic can flow over time. David Harrell, who is the inventor of state charts, calls this a visual formalism. And so, he describes that visual formalisms are diagrammatic and intuitive, yet mathematically rigorous languages. Thus, despite their clear visual appearance, they come complete with a syntax that determines what's allowed and the semantics that determine what the allowed things can be. And so, I recommend reading his paper on visual formalisms for more information on this really, really interesting idea of basically these diagrams that are mathematically rigorous and also executable.

2. Coding Logic and the Role of Reducers

Short description:

The way we typically code application logic doesn't lend itself to a visual formalism. The logic is hard to understand and centralize. Reducers provide a way to contain logic in a centralized location, forcing interaction through events. State machines separate behaviors into finite states, representing current states and responses to events.

So, the way that we typically code application logic, whether it's in React or anything else, doesn't really lend itself to a visual formalism or to anything, really. We tend to co-locate data and logic close to the source where it's used, such as in event handlers or sometimes in custom React hooks if we want a little bit more organization.

So, while this may be convenient to code, the problem is that the logic is hard to understand, especially as it changes over time due to events or anything that can happen within the app. The problem is you can't discern what can happen or how an application can respond to any event or signal at any point in time. And so, that connection logic resides in the head of the developer who added the logic, which isn't really useful, and so you end up with things such as ad hoc logic as well, you know, which obviously should be dried up.

But the problem is that when you add that ad hoc logic, the logic, when you dry it up, you might put it in a function or something, and that function may end up, you know, itself being ad hoc logic, just living somewhere else. So you're still not centralizing everything, which, you know, definitely becomes a bit of a problem.

And so enter the reducer, popularized by Flux and state management libraries like Redux, reducers provide a way to contain this logic in a centralized convenient location. So one hugely important beneficial constraint of reducers is that it forces you to interact with the logic by sending events or actions, as they're called in React and Redux. By the way, the naming of actions was sort of a mistake, at least in my opinion. So we're going to be using the term events in this presentation. But here is why dispatching events is actually a really good thing. It forces you to reify what can happen at your app in any given point in time. So the user may click a button, a fetch may resolve or reject, a timer might go off. All of those are events. And thinking about your app in terms of state and events really simplifies the mental model, at least in my opinion.

However, this isn't easily visualized either. Reducers typically contain switch statements or if statements to discern what should happen when an event is received, thus distinguishing how the behavior of your app can change. And this becomes a lot more difficult. It mixes those switch statements and those if statements. And so you have to piece together the logic by navigating through a bunch of these statements and defensive logic just to discern what the behavior of your app can be at any given point in time. It's all in a single function. And it's hard to pull that apart.

So state machines are like reducers. And they can even be written as reducers. But instead of mixing all the logic together, it cleanly separates behaviors into what are known as finite states. A finite state represents a behavior, which is what the current state is of some actor and how it can respond to events. So it might respond to an event by performing an action or by changing its behavior or anything like that. And that's represented by these transition arrows that go from state to state. Or an event might not be handled, in which case the default behavior is to ignore that event.

QnA

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.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced 2023React Advanced 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
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.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
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.
SolidJS: Why All the Suspense?
JSNation 2023JSNation 2023
28 min
SolidJS: Why All the Suspense?
Top Content
Suspense is a mechanism for orchestrating asynchronous state changes in JavaScript frameworks. It ensures async consistency in UIs and helps avoid trust erosion and inconsistencies. Suspense boundaries are used to hoist data fetching and create consistency zones based on the user interface. They can handle loading states of multiple resources and control state loading in applications. Suspense can be used for transitions, providing a smoother user experience and allowing prioritization of important content.

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.
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.