Declarative state machines for React!
React Component state is a powerful way of managing state within a component, but can we do more? Can we create and maintain state which is more readable and self-explantory and powerful at the same time?
Quick Example
const ViewToggler = // In your component's render method <ViewTogglerProvider> ... <ViewTogglerConsumer> <> <button disabled=togglerisvisible onClick=togglershow > Show </button> <button disabled=togglerishidden onClick=togglerhide > Hide </button> </> </ViewTogglerConsumer> ... </ViewTogglerProvider>
Motivation
Let's compare these two examples.
<button disabled=countercandecrement && counterisstarted onClick=counterincrement> Delete </button>
vs
<button disabled=countervalue > 0 && countervalue < counterMAX_VALUE onClick=counterincrement > Decrement </button>
The first one is extremely readable and you can immeditately tell what the developer is trying to do in this code. It hardly requires comments. That is the motivation for this project. State machines in Arminjs with meaningful names for states have great potential to make developer experience great for building applications with React.
Features :
- State machine creation is similar to the api of Rematch
- Uses the new 16.3 React Context API for data flow across components
- Async actions are supported
- Multiple state machines are supported but you can subscribe to only the ones you need within a component
Examples
Let's see how we can build a counter with Arminjs.
Single State Machine -> An async counter example with armin
- Create a machine
const Provider Consumer = ;
- Using the machine inside React
<Provider> <Consumer> { return <div> <p> <button disabled=!machineControllercanincrement onClick= machineController > Increment By 2 </button> </p> <p>Value is machineControllervalue</p> <p> <button disabled=!machineControllercandecrement onClick= machineController > Decrement </button> </p> <p> <button disabled=!machineControllercanincrement onClick= machineController > Wait for a second and increment by 5 </button> </p> <p> <button disabled=!machineControllercanstop onClick= machineController > Stop counter </button> </p> </div> ; } </Consumer> </Provider>
Multiple state machines
Just like above, but we can create multiple machines at once and then subscribe to only the ones we need to ensure maximum performance during rerenders on update.
// create a an object with state machine config as aboveconst toggler = allStates: "showing" "hiding" state: "hiding" reducers: show: from: "hiding" "showing" hide: from: "showing" "hiding" const counter = ... const user = ... const store Provider createConsumer = ; const Consumer = ; { return <Consumer> <button isDisabled=togglerishidden onClick=counterincrement>countervalue</button> </Consumer> } { return <Provider> <MyChildComponent/> </Provider> }
License
MIT