Xstate: State machines and statecharts for the modern web
github.com
github.com
Just want to mention that we're very close to releasing XState v5 beta, which brings even more features to the state machines & statecharts you can create, and greatly improves the developer experience, but also makes it more usable as a general-purpose state management library (or orchestration "framework" if you want to consider it that), whether on the frontend or backend.
Are you sure you need to bring “even more features”, or rather, what are your thoughts on how feature-rich a state machine library needs to be?
The entire kiosk device could be repurposed on the fly and Xstate + JSON schema form allowed for completely customizable & swappable UI.
Shame the project died.
(we pushed to open source the guts, but to no avail)
Both of us reminisce about it though. We literally retooled the fleet of devices in a weekend to adapt to COVID and it worked. We interfaced with tons of hardware and even ran a customized debian image, all powered by RPis. Truly a nerd's dream project.
My use case involves implementing various user flows in my app and I'm currently weighing the benefits of using xstate versus react-router.
Also, I'm curious about how you integrated graphql into this project. Could you share some details on that?
Lastly, I wanted to ask if you stored all the different configurations on a database or on git? If you used a database, how did you manage different schema versions?
We used Xstate over react-router by using a parallel machine:
- One for application state - One for view state
We had to hack the innards of the events a bit to get the two machines to communicate. This allowed the view to re-render the jsonschema form at the exact right time, and not flicker on multiple state transitions.
In hindsight, graphql wasn’t as necessary as we initially thought. The important part was storing the mutation as a string as an xstate transition parameter. We used federation, so it did help us deal with multiple backends.
All database. Versions were handled by having a core machine that pulled the kiosk’s workflow from the server and ran it as a submachine. So the code on the device (core machine) could switch sub machine workflows on the fly between runs.
Found xstates desire too control everything made a simple embedding use case really awkward. The hoops to jump through for good typescript support while breaking the config down into reusable components...
Really wanted to like xstates but it felt like it was trying to own the entire app and was sacrificing usability for some version of academic purity. Also, feels like a huge marketing effort is under way to over fit it as a solution to any problem containing the word "state"; ie as a React state management solution..
We're not trying to force state machines as the solution for any state-related problem; they're not a panacea, but instead a useful tool for the appropriate use-cases.
And we're definitely making a huge effort to improve the types.
I ended up writing my own in about 80 lines of typescript in less time than it would have taken to finish going through the Xstate docs. Doubtless Xstate is exactly what's needed for some projects, but I suspect it's unnecessarily adding to the complexity of many more.
https://gist.github.com/andymatuschak/d5f0a8730ad601bcccae97...
It doesn't require a library, it binds states and effects together, it is completely pure, and it can be implemented in most any language, preferably one with sum types and exhaustiveness checking. It works equally well with both complex, time-dependent business logic as well as code that controls UI states.
I love state machines for help in writing robust code. The act of laying them out this way forces you to consider lots of intermediate states that are ignore or forget. Plus, the logic stays away from all the gunk of the platform, state machines are trivial to test, and, once you get used to them, are easy to read.
StateCharts are the "Strucured Programming" version of State Machines.
StateCharts use parental authority instead of inheritance (my words).
A child state machine cannot override the operation of a parent. A parent can yank children out of their current states back to some known state.
OOP and FP don't encourage this kind of thinking.
The Big Deal concerning state machines is the "state explosion problem". Harel's StateChart notation conquers this problem.
My reading of the original paper is here: https://guitarvydas.github.io/2020/12/09/StateCharts.html
The serializability of your state itself has nothing to do with how events are bound to callback functions. If you serialize a string name of a function and not the source code of that function this buys you nothing. The source code itself is all text, so its serializable no matter whether the code is suitable for being statically analyzed
Fair enough, but what's a rudimentary usecase for 'the modern web'?
What everyday UI thing is better done with this than other methods? Why is it better?
Why? Can you give an example?
It’s the same situation as redux though but with more formality and it’ll draw you a nice diagram too.
“Hey ChatGPT, can you show me an example of using XState typescript library to separate business logic from UI code in a computer program and discuss why XState might be useful for this purpose?”
The example it gives is really incredible… and obviously you can refine what it’s doing in context for your own understanding.
Another example is sending and receiving state changes from anywhere other than the UI, such as via WebSockets in a collaborative editing environment.
Not trying to be pedantic I promise, I really want to see the value of this, but not sure I can without an example clearly comparing this against just a few if statements or something in pure JS, for something 'everyday'.
State machines make sense to me in a theoretical sense for something with a pretty complex tree of state transitions like a game but for the 99% run of the mill UI work you get in building web products I am not sure I see anything that brings value worth the tradeoff of having to learn yet another library.
Its original value prop was one way data flow and pure functional UI based on passed in props. It allows for side effects, to get certain things done pragmatically, but in my view does not encourage them in any way.
And it's true that this separation of state and UI is just a general design pattern, which can be implemented with a plain object and switch statement, or a small class with a few methods - it doesn't have to be state machines.
So I'm with you in your conclusion, or skepticism perhaps - I prefer to apply the minimal pattern that achieves the same thing, rather than having to learn another state management library like Xstate or even Redux. But then again, I can see the value of such a library in a group/company environment, where you want everyone to learn and follow certain ways of organizing things, where new members can read the documentation, and understand how to add and change existing code in a predictable pattern.
IMO the JSON was hard to read, but we had a plan to build a GUI config builder that exported the state flows.
Emphasis on attempted, not sure I've ever seen it actually work as envisioned. Can see how bringing this directly into the code could remove some hurdles though.
Must say though I am a little skeptical on the readability / comprehensibility of the JSON format as you point out, but it's certainly a cool idea.
Lots of frameworks and state management libraries already lean towards helpful design, in languages with async and ADTs as first-class citizens you've got a real leg up, but at the end of the day it comes down to preventing impossible states.
You can't have an error message when in the success state, you can't have success data while loading or waiting.
By preventing this at compiletime, it also means the UI can't ever show bogus data (i.e. it's impossible to have a success screen with the error message dangling at the bottom because somebody forgot to clear it)
But once you start having much more than that, or nested states, Statecharts makes it really easy to build reliable, performant and easy to change flows.
A state machine is the wrong solution unless you also need to restrict transitions themselves in my opinion
If a TS typed switch statement, say, offers the same guarantees of covering all options yet is just run of the mill JS that anyone can read and instantly grok, and covers 99% of usecases in run of the mill web dev product work, then to me that's an argument that it's the better solution.
All of them.
> Why is it better?
Because it specifies a workflow that actually matches what you want to do instead of employing a pile of ad-hoc rules that quickly become an unmaintainable mess.
If you have animations and async calls and multiple screens/pages, you have an application with application states which transition in response to inputs. That's what state machines are designed to handle.
Storyboards are state machines. Navigation components are state machines. UI binding layers like redux are state machines.
I am not saying you're wrong, but if you're right this would be the first case I've seen of it in my career so far :-)
Truthfully, using state machines at runtime for the use cases above is sometimes too heavy. That distinction is actually a big input to what I’ve been building at Dopt.
Our platform lets you build state machines that are initialized per user in your application via our SDKs—you design the machines in the platform, and we provide APIs to let you transition them based on user interaction/input. We’ve taken a bunch of inspiration from Xstate and statecharts. I actually wrote up a blog about how we took inspiration from the latter https://blog.dopt.com/state-machines-and-their-influence-on-...
[1] https://web.stanford.edu/class/archive/cs/cs103/cs103.1142/b... (requires pointer and not touch input)
Example: Even typing into a text box on Hacker News is a new UI state: you have a different set of shortcuts, the keyboard works slightly differently, the browser has to keep track of the input if you suddenly press back and then forward again (some browsers maintain input in these cases), undo has to work within the scope of the textbox etc.
The more complex your UI becomes, the more contradictory states become, and need to be tracked. We're posting something over XHR/WebSockets? X amount of elements on the page have to be disabled, some state has to updated with save progress etc. We are logged in/logged out? We need to show a different state. There's an error in some part of the app? We need to block user from doing something and show errors etc.
If you can split those into actual states and allow interface and actions based on the current state, it becomes easier to reason about what is going on ini your app
* Only issue is that with so much active development since the training cut-off it usually outputs deprecated structure / patterns.
Learning curve is more similar to rx-js or fp-ts than a state manager.
–a former colleague
{/* the fact that i'm doing this means I probably should have used x-state or something */}
{stages.filter(Boolean).length > 1 && (
<div>
WARNING! More than one assumption is true! {JSON.stringify(stages)}
</div>
)}
One day I'll learn...Pros:
- The concept of states, events, and actions are an intuitive way to model state and the learning curve for me wasn't too bad.
- I enjoyed using the visual editor inside VSCode and after setting up TS, the codegen was pretty cool.
- The library supports parallel states.
Cons:
- The codegen was sometimes pretty bad for TS. There was some jank between the editor and the codegen, leading to frustrating DX.
Orchestrators like Kubernetes discourage designing state machines and transitions inside resource controllers. Instead a list of conditions associated with the object's status define a "phase" (state in k8s term). But there are no formal event-based transitions between states. Depending on the conditions and their tri-boolean values: True/False/Unknown, the object is effectively in a different phase.
Effectively, kubernetes recommends treating Resources like a game ECS - the controller is the system, the resource is the entity and the conditions are the state components.
The visualizer is a major selling point - especially if I need to explain something to non-dev people or someone new to the concept.
The one downside is that building state machines is an art in and of itself and I had to throw away my first implementation in favour of something simpler once I got the hang of it.
All I see here is a switch statement, the input is an enum, and the action that's taken is also determined by an enum.
I find the DSL much easier to wrap my head around than the json format of Xstate.