8 ms·
Xstate: State machines and statecharts for the modern web
- b0afc375b5 4y agoI wanted to learn about state machines so I searched for reading material here in hackernews. Found out about statecharts and used it immediately to rewrite a frontend app. What a fantastic development experience. It feels like I finally graduated from spaghetti coding to disciplined programming.
- swyx 4y agolove how xstate makes implicit state machines explicit with a time tested (one might say Lindy) format. badly/ad hoc defined state machines are the source of so many bugs - David has been banging this particular drum the entire time i've known him (https://www.youtube.com/watch?v=HPoC-k7Rxwo&list=PLRvKvw42Rc7O0eWo2m_guXdZsGTEQM_jj&index=6&t=81s https://www.youtube.com/watch?v=HPoC-k7Rxwo&list=PLRvKvw42Rc...)
- a4isms 4y ago“Any sufficiently complicated model class contains an ad-hoc, informally-specified, bug-ridden, slow implementation of half of a state machine.” –a former colleague
- baq 4y ago“I don’t need a state machine library” - everyone when starting a new project
- xavdid 4y agoI came across this code from 2-years-ago-me today: {/* 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...
- vaughan 4y agoI wonder if we could build better implicit state machines if we could more easily visualize our imperative code by annotating it with visualization hints and parsing the AST. Also easier to debug/step-through this way.
- mattgreenrocks 4y agoI need to write a post on this, but I've been using this pattern to great effect: https://gist.github.com/andymatuschak/d5f0a8730ad601bcccae97e8398e25b2 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.
- mhoad 4y agoSeems you’re not alone. This was ripped out of Google’s Stadia platform I believe but might be wrong https://github.com/google/hierarchical-state-machine.dart https://github.com/google/hierarchical-state-machine.dart
- davnicwil 4y agoThe readme gives the example of a traffic light to demo a state machine usecase. 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?
- andy_ppp 4y agoAlmost everything can be written as a state machine and arguably it’s very useful to do so, for example let’s take a note taking app, you can probably list a set of transitions that can happen to change the state of the app. Keeping the state changes separate from the UI is a good thing. In a way redux is a state machine too. Try it out on a project and see if it works for you!
- davnicwil 4y ago> Keeping the state changes separate from the UI is a good thing Why? Can you give an example?
- andy_ppp 4y agoChatGPT it, it’ll do a better job than I will and it’ll be relevant to your requirements. 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.
- deleted 4y ago[deleted]
- lioeters 4y agoFor example, the browser extension Redux DevTools implements "time travelling" by taking snapshots of the entire state on every state change. This is enabled by the fact that in Redux, state changes are separate from the UI. This same principle can be used for undo/redo history. Another example is sending and receiving state changes from anywhere other than the UI, such as via WebSockets in a collaborative editing environment.
- sonicrocketman 4y agoI was one half of a team that heavily leveraged XState in 2020. We used it to build a general-purpose kiosk app (in Electron) that could be updated remotely using an Xstate configuration served by a graphene-django app. One of the most technically impressive pieces of software I've ever had the pleasure to work on. (I mostly did server/backend stuff). 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.
- jrvarela56 4y agoSounds awesome, given it died could you publish the source? Would be great to see how something like this is structured.
- sonicrocketman 4y agoUnfortunately no. It was proprietary. (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.
- jjclane 4y agoWe're currently building something that sounds superficially similar, would you be interested in having a chat?
- sonicrocketman 4y agoSure. Check bio. Email in blog's about page.
- yagodragon 4y agoI'm also exploring xstate for a similar use case and would love to know more about your experience with it. I'm particularly interested in understanding the level of customizability you allowed in your implementation. 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?
- davidkpiano 4y agoHey, creator of XState here! 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.
- ar-nelson 4y agoWould you consider supporting Deno? (The npm module can probably be imported as-is in newer Deno versions, but a dedicated module is always nice and likely wouldn't be much work)
- capableweb 4y agoIf it (probably) already works as-is, why not just use it? Why is it nicer with a "dedicated module" if using it from npm is the same? More work is more work, reducing maintainer work is something we should strive towards, rather than adding "just a little bit of work".
- fallingmeat 4y agodo you foresee sysml like diagrams in your roadmap? if you could do activity diagrams with swimlanes…dude. that'd be huge.
- davidkpiano 4y agoYes! Visualizing how different actors communicate with each other in general is a big goal for us this year. We're going to start with sequence diagrams.
- nickpeterson 4y agoI know this probably isn’t on the radar, but process trees or pétri nets with token visualization feels doable, any interest in supporting those kinds of tools?
- deleted 4y ago
- satvikpendem 4y agoI've seen XState more and more, recently, what are the pros and cons versus other state management solutions? Anything that XState fails at particularly that potential users should be aware of?
- epolanski 4y agoVerbosity, complexity. It's probably overkill for 99.9% of the things you imagine. Learning curve is more similar to rx-js or fp-ts than a state manager.
- phpnode 4y agowhen you do get over the learning curve it's really excellent though.
- brigadier132 4y agoThe story for composition and reusability of multiple state machines is not good and it's not compatible with existing solutions for certain things (react query for example.) Supposedly this will all be fixed to some extent in v5 but that hasn't launched yet.
- kidfiji 4y agoHad the pleasure of working with XState at my last role. Where I found it greatly shined was being able to jump into a UI/machine I have never worked on before and contribute almost immediately after digesting the machine's definition
- a-dub 4y agoany thoughts on a custom DSL for defining and verifying abstract state machines and then machinery for generators for different languages/libraries/environments/visualizations?
- lerchmo 4y agoI have been using this XState alternative https://github.com/StoneCypher/jssm https://github.com/StoneCypher/jssm I find the DSL much easier to wrap my head around than the json format of Xstate.
- joshribakoff 4y agoI used it in the past and really disliked how it encouraged things like defining which functions to call by specifying a string with the function name. I would have much rather had it be more opinionated and require passing a reference to the function so it forces you to write code that benefits from typescript
- phpnode 4y agoThere's many benefits in having a state machine configuration that can be serialized, especially if you can store that config in a database and load it at runtime. And actually xstate does allow you to pass the functions directly if you want to
- joshribakoff 4y agoYes it allows strings or references to the function. My issue is that since the former is allowed, either people start using that method, or you have to start a “debate” within your team about patterns to avoid. 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
- Rapzid 4y agoI'm a simple man. I just want to embed a state machine in my objects. I want to let it know when an event occurs. I want it to let me know when an event occurs. Sigh.. 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..
- davidkpiano 4y agoWould love to know more about an example "simple embedding use-case" that you may have in mind. 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.
- sanitycheck 4y agoI had a similar reaction after trying it a couple of years ago. I only needed a fairly straightforward FSM for a video player UI, and I like to properly understand any libraries I use. Xstate seemed to have waay too much going on. 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.
- dabernathy89 4y agoRan into the same trouble re: TypeScript. Wanted to break up my definition into smaller chunks but it really did not like that.
- gooseus 4y agoI've gotten good results from asking ChatGPT to give me Xstate representations of machines that I describe, very cool to copy-paste* into the visualizer as a starting point. * Only issue is that with so much active development since the training cut-off it usually outputs deprecated structure / patterns.
- lenkite 4y agoI always found it strange how state machines work so nicely in the small but tend to be difficult to scale up to large-scale, distributed systems. 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.
- instagary 4y agoI tried XState for a mobile app. 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.
- paultarvydas 4y agoThere is a HUGE difference between StateCharts and State Machines, yet, the difference is subtle. 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 https://guitarvydas.github.io/2020/12/09/StateCharts.html
- deleted 4y ago[deleted]
- troyharvey 4y agoHad an absolute blast building an audio player web component with xstate! We deleted so much code by switching to a state machine design.
- Emanation 4y agoAdd a description please. I get it's a state machine. I get states have state-tags, transitions can be ran via these transition-tags. What is your philosophy behind this library. Why should I give a fuck that states and transitions are strings rather than enums? 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.
- Tade0 4y agoWe're using Xstate for state management instead of Redux and the like and it fits well for this purpose - chiefly I have an idiomatic way of defining which inputs are appropriate in different contexts. 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.