Search code examples
reactjsreduxxstate

Redux and XState for data store and React integration


I've been using Redux for most of my React applications.

I think I will start using XState as I don't have to use effects as a plugin all the time.

And I think is a more complete pattern.

One thing that I want to understand is it's connection with React (hooks and classes) and it's interaction with reactive programming in general:

Can I (and should I) use XState context as Redux data store in the same way, having a single source of truth on a shared by React Components way? Will my components be able to "connect" and "mapToProps" the XState context and rerender only when those values changes and not every time the state machine state changes?

From what I understand Redux lacking side effects is so it can adhere to a pure functional paradigm. But that breaks with side effects usage, that is a lot of times needed in web apps or games for example.

Thanks in advance!


Solution

  • XState can basically manage your global state in Redux (or other state management libraries) if you want to, but it won't replace connecting with React as Redux does. You should view it as an extension to Redux and you would still need to follow the patterns used in Redux, but use XState to perform them. A few examples:

    • Redux state can be represented as anything, so it can be a XState machine state + XState machine context.
    • Redux actions should basically trigger XState machine transitions. They can also trigger async actions (https://xstate.js.org/docs/guides/communication.html#invoking-promises), so you might not need something like redux-thunk to deal with that. You actions will become much simpler, but the actual handling is moved to the machine.
    • Redux reducers usually return a new state, therefore they are the outcome of a XState transition.

    You can probably find a way to connect this all together (did a similar thing with Vuex recently). The XState machine would simply be a singleton called from Redux entities, but you would not "embed" the machine inside Redux.

    You would also still need to use the react-redux tools as before and the machine would never really be exposed to the actual React components (except you want to use XState machines for local state as well).