What is an actual difference between redux and a state machine (e.g. xstate)?

27,139

Solution 1

I created XState, but I'm not going to tell you whether to use one over the other; that depends on your team. Instead, I'll try to highlight some key differences.

Redux XState
essentially a state container where events (called actions in Redux) are sent to a reducer which update state also a state container, but separates finite state (e.g., "loading", "success") from "infinite state", or context (e.g., items: [...])
does not dictate how you define your reducers - they are plain functions that return the next state given the current state and event (action) a "reducer with rules" - you define legal transitions between finite states due to events, and also which actions should be executed in a transition (or on entry/exit from a state)
does not have a built-in way to handle side-effects; there are many community options, like redux-thunk, redux-saga, etc. makes actions (side-effects) declarative and explicit - they are part of the State object that is returned on each transition (current state + event)
currently has no way to visualize transitions between states, since it does not discern between finite and infinite state has a visualizer: https://statecharts.github.io/xstate-viz which is feasible due to the declarative nature
the implicit logic/behavior represented in reducers can't be serialized declaratively (e.g., in JSON) machine definitions, which represent logic/behavior, can be serialized to JSON, and read from JSON; this makes behavior very portable and configurable by external tools
not strictly a state machine adheres strictly to the W3C SCXML specification: https://www.w3.org/TR/scxml/
relies on the developer to manually prevent impossible states uses statecharts to naturally define boundaries for handling events, which prevents impossible states and can be statically analyzed
encourages the use of a single, "global" atomic store encourages the use of an Actor-model-like approach, where there can be many hierarchical statechart/"service" instances that communicate with each other

I will add more key differences to the docs this week.

Solution 2

State machine does not tell (force) you to have Unidirectional data flow. It has nothing to do with data flow. It is more about constraining state changes and about state transitions. So, generally only some parts of the application would be designed with State machines, only and only if you need to constraint/forbid some state changes and you are interested in transitions.

Beware that with state machines, if for some reason (external API dependency etc...), there is chance that app might get locked in a state where it can't transition to another state because of constraints, you have to solve it.

But if you are only interested in last app state itself, instead of state transitions, and state constraints do not matter, then you better be not using state machine and directly be updating state itself (you can still wrap state in a Singleton class update through Action classes).


On the other hand, Redux is Unidirectional architecture framework. Unidirectional architectures enforce you to have single direction of data flow. In Redux, it starts with User->View->(Action)->Store->Reducer->(Middleware)->Store->(State)->View. Like State Machines, you can trigger side effects with Middlewares in Redux. You can constraint/forbid State transitions, if you want. Different from State Machine, Redux forces unidirectional data flow, pure! reducer functions, immutable state objects, single observable app state.

Solution 3

few of my points below.

  • The UI-state and business/backend state are coupled together in redux. Because of this every update on the ui or business state creates a data update in the redux store.
  • Xstate decouples UI state and backend state.
  • In redux all nodes are present inside a root node. Xstate decentralises and distributes data inside independent Machines.
  • Application can only transition between the states defined already. So any error or bug can be fixed in the Machine itself.
  • Internal states are managed by the Machine itself in Xstate. Redux represents new states as flags.
  • Renderer agonistic - keeping as much of the state hoisted into Machines, and if we need, we can switch rendering frameworks relatively easy (eg from react to vue).
  • Contexts provides concrete class to present a single interface to the outside world.
Share:
27,139
Artem Arkhipov
Author by

Artem Arkhipov

Full Stack Web Developer, Web Lead, RnD department member and Speaker. Javascript, Angular, React, Node.js, MongoDB. Serverless, AWS Lambda, AWS, GCP, Cloud Functions, Firebase, Firestore. Check my skills at PluralSight: https://app.pluralsight.com/profile/artem-arkhipov

Updated on July 08, 2022

Comments

  • Artem Arkhipov
    Artem Arkhipov almost 2 years

    I am working on investigation of one front-end application of medium complexity. At this moment it is written in pure javascript, it has a lot of different event-based messages connecting few main parts of this application.

    We decided that we need to implement some kind of state container for this application in scope of further refactoring. Previously I had some experience with redux and ngrx store (which actually follows the same principles).

    Redux is an option for us, but one of the developers proposed using a state-machine based library, in particular the xstate library.

    I've never worked with xstate, so I found it interesting and started reading documentation and looking at different examples. Looked promising and powerful, but at some point I understood that I don't see any significant difference between it and redux.

    I spent hours trying to find an answer, or any other information comparing xstate and redux. I didn't find any clear information, except some articles like "get from redux to a state machine", or links to libraries focused on using redux and xstate together (quite weird).

    If someone can describe the difference or tell me when developers should choose xstate - you are welcome to.

    • Yannic Hamann
      Yannic Hamann over 4 years
      The official docs actually say that you should treat your redux reducers as a state machine redux.js.org/style-guide/…
    • Alfred Young
      Alfred Young about 4 years
      I think the libraries you mention might be for using xstate as an effect management system (alternative to thunk, saga, epic, etc.)
  • Carlos Verdes
    Carlos Verdes over 4 years
    Finally someone using FSM and SCXML for front development... man you saved my life, I'm going to study your library. I don't like redux for some reasons (first it confuse event and action terms) and second it "model" complex states with million flags (verbose and imho incorrect).
  • David Khourshid
    David Khourshid about 4 years
    @Mike76 XState integrates with Redux dev tools.
  • Mike76
    Mike76 about 4 years
    Thanks for the hint, I will look into that.
  • Mike76
    Mike76 about 4 years
    I have now tried XState + Redux DevTools. It works quite well, but some features seem to be missing. For example, XState + Redux DevTools does not support features like "state replay" where a sequence of previous states gets replayed. Is this due to implementation limitations?
  • TamusJRoyce
    TamusJRoyce over 3 years
    Isn't the FSM just a graph that can drive Redux? Navigation is a FSM because you have the back button. Unless you disable the back button, even in Redux, you have a FSM. Redux is an immutable data pattern with good constraints. So as you navigate through your FSM (library or self-written, even if unintentional) Redux prevents side-effects. Redux captures only the unidirectonal portion of data flow. It is not pure.
  • Magne
    Magne almost 3 years
    @Mike76 See this on time travelling in Redux and XState: github.com/statelyai/xstate/issues/906#issuecomment-56976067‌​7
  • Arturo Hernandez
    Arturo Hernandez over 2 years
    I actually am familiar with both. And that is not quite accurate. React is mostly just rendering HTML as a function. React does provide minimum state handling intended for simple UI elements. For "business rules" there are many third party libraries including xstate.
  • Vijay122
    Vijay122 over 2 years
    This compares redux and xstate. Specifically to state management inside react apps.