useStateMachine

The <1 kb state machine hook for React

README


The <1 kb _state machine_ hook for React:

See the user-facing docs at: usestatemachine.js.org

- Batteries Included: Despite the tiny size, useStateMachine is feature complete (Entry/exit callbacks, Guarded transitions & Extended State - Context)
- Amazing TypeScript experience: Focus on automatic type inference (auto completion for both TypeScript & JavaScript users without having to manually define the typings) while giving you the option to specify and augment the types for context & events.
- Made for React: useStateMachine follow idiomatic React patterns you and your team are already familiar with. (The library itself is actually a thin wrapper around React's useReducer & useEffect.)

size badge


Examples


- State-driven UI (Hiding and showing UI Elements based on the state) - CodeSandbox - Source
- Async orchestration (Fetch data with limited retry) - CodeSandbox - Source
- Sending data with events (Form) - CodeSandbox - Source

Installation


  1. ``` sh
  2. npm install @cassiozen/usestatemachine
  3. ```

Sample Usage


  1. ```typescript
  2. const [state, send] = useStateMachine({
  3.   initial: 'inactive',
  4.   states: {
  5.     inactive: {
  6.       on: { TOGGLE: 'active' },
  7.     },
  8.     active: {
  9.       on: { TOGGLE: 'inactive' },
  10.       effect() {
  11.         console.log('Just entered the Active state');
  12.         // Same cleanup pattern as `useEffect`:
  13.         // If you return a function, it will run when exiting the state.
  14.         return () => console.log('Just Left the Active state');
  15.       },
  16.     },
  17.   },
  18. });

  19. console.log(state); // { value: 'inactive', nextEvents: ['TOGGLE'] }

  20. // Refers to the TOGGLE event name for the state we are currently in.

  21. send('TOGGLE');

  22. // Logs: Just entered the Active state

  23. console.log(state); // { value: 'active', nextEvents: ['TOGGLE'] }
  24. ```


API


useStateMachine


  1. ```typescript
  2. const [state, send] = useStateMachine(/* State Machine Definition */);
  3. ```

useStateMachine takes a JavaScript object as the state machine definition. It returns an array consisting of a current machine state object and a send function to trigger transitions.

state


The machine's state consists of 4 properties: value, event, nextEvents and context.

value (string): Returns the name of the current state.

event ({type: string}; Optional): The name of the last sent event that led to this state.

nextEvents (string[]): An array with the names of available events to trigger transitions from this state.

context: The state machine extended state. See "Extended State" below.

Send events


send takes an event as argument, provided in shorthand string format (e.g. "TOGGLE") or as an event object (e.g. { type: "TOGGLE" })

If the current state accepts this event, and it is allowed (see guard), it will change the state machine state and execute effects.

You can also send additional data with your event using the object notation (e.g. { type: "UPDATE" value: 10 }). Check schema for more information about strong typing the additional data.

State Machine definition


KeyRequiredDescription
---------------|-----------
verbose|
schema|
context|
initial*The
states*Define

Defining States


A finite state machine can be in only one of a finite number of states at any given time. As an application is interacted with, events cause it to change state.

States are defined with the state name as a key and an object with two possible keys: on (which events this state responds to) and effect (run arbitrary code when entering or exiting this state):

On (Events & transitions)


Describes which events this state responds to (and to which other state the machine should transition to when this event is sent):

  1. ```typescript
  2. states: {
  3.   inactive: {
  4.     on: {
  5.       TOGGLE: 'active';
  6.     }
  7.   },
  8.   active: {
  9.     on: {
  10.       TOGGLE: 'inactive';
  11.     }
  12.   },
  13. },
  14. ```

The event definition can also use the extended, object syntax, which allows for more control over the transition (like adding guards):

  1. ``` js
  2. on: {
  3.   TOGGLE: {
  4.     target: 'active',
  5.   },
  6. };
  7. ```

Guards


Guards are functions that run before actually making the state transition: If the guard returns false the transition will be denied.

  1. ``` js
  2. const [state, send] = useStateMachine({
  3.   initial: 'inactive',
  4.   states: {
  5.     inactive: {
  6.       on: {
  7.         TOGGLE: {
  8.           target: 'active',
  9.           guard({ context, event }) {
  10.             // Return a boolean to allow or block the transition
  11.           },
  12.         },
  13.       },
  14.     },
  15.     active: {
  16.       on: { TOGGLE: 'inactive' },
  17.     },
  18.   },
  19. });
  20. ```

The guard function receives an object with the current context and the event. The event parameter always uses the object format (e.g. { type: 'TOGGLE' }).

Effects (entry/exit callbacks)


Effects are triggered when the state machine enters a given state. If you return a function from your effect, it will be invoked when leaving that state (similarly to how useEffect works in React).

  1. ```typescript
  2. const [state, send] = useStateMachine({
  3.   initial: 'active',
  4.   states: {
  5.     active: {
  6.       on: { TOGGLE: 'inactive' },
  7.       effect({ send, setContext, event, context }) {
  8.         console.log('Just entered the Active state');
  9.         return () => console.log('Just Left the Active state');
  10.       },
  11.     },
  12.   },
  13. });
  14. ```

The effect function receives an object as parameter with four keys:

- send: Takes an event as argument, provided in shorthand string format (e.g. "TOGGLE") or as an event object (e.g. { type: "TOGGLE" })
- setContext: Takes an updater function as parameter to set a new context (more on context below). Returns an object with send, so you can set the context and send an event on a single line.
- event: The event that triggered a transition to this state. (The event parameter always uses the object format (e.g. { type: 'TOGGLE' }).).
- context The context at the time the effect runs.

In this example, the state machine will always send the "RETRY" event when entering the error state:

  1. ```typescript
  2. const [state, send] = useStateMachine({
  3.   initial: 'loading',
  4.   states: {
  5.     /* Other states here... */
  6.     error: {
  7.       on: {
  8.         RETRY: 'load',
  9.       },
  10.       effect({ send }) {
  11.         send('RETRY');
  12.       },
  13.     },
  14.   },
  15. });
  16. ```

Extended state (context)


Besides the finite number of states, the state machine can have extended state (known as context).

You can provide the initial context value in the state machine definition, then use the setContext function within your effects to change the context:

  1. ``` js
  2. const [state, send] = useStateMachine({
  3.   context: { toggleCount: 0 },
  4.   initial: 'inactive',
  5.   states: {
  6.     inactive: {
  7.       on: { TOGGLE: 'active' },
  8.     },
  9.     active: {
  10.       on: { TOGGLE: 'inactive' },
  11.       effect({ setContext }) {
  12.         setContext(context => ({ toggleCount: context.toggleCount + 1 }));
  13.       },
  14.     },
  15.   },
  16. });

  17. console.log(state); // { context: { toggleCount: 0 }, value: 'inactive', nextEvents: ['TOGGLE'] }

  18. send('TOGGLE');

  19. console.log(state); // { context: { toggleCount: 1 }, value: 'active', nextEvents: ['TOGGLE'] }
  20. ```

Schema: Context & Event Typing


TypeScript will automatically infer your context type; event types are generated automatically.

Still, there are situations where you might want explicit control over the context and event types: You can provide you own typing using the t whithin schema:

Typed Context example

  1. ```typescript
  2. const [state, send] = useStateMachine({
  3.   schema: {
  4.     context: t<{ toggleCount: number }>()
  5.   },
  6.   context: { toggleCount: 0 },
  7.   initial: 'inactive',
  8.   states: {
  9.     inactive: {
  10.       on: { TOGGLE: 'active' },
  11.     },
  12.     active: {
  13.       on: { TOGGLE: 'inactive' },
  14.       effect({ setContext }) {
  15.         setContext(context => ({ toggleCount: context.toggleCount + 1 }));
  16.       },
  17.     },
  18.   },
  19. });
  20. ```

Typed Events


All events are type-infered by default, both in the string notation (send("UPDATE")) and the object notation (send({ type: "UPDATE"})).

If you want, though, you can augment an already typed event to include arbitrary data (which can be useful to provide values to be used inside effects or to update the context). Example:

  1. ```typescript
  2. const [machine, send] = useStateMachine({
  3.   schema: {
  4.     context: t<{ timeout?: number }>(),
  5.     events: {
  6.       PING: t<{ value: number }>()
  7.     }
  8.   },
  9.   context: {timeout: undefined},
  10.   initial: 'waiting',
  11.   states: {
  12.     waiting: {
  13.       on: {
  14.         PING: 'pinged'
  15.       }
  16.     },
  17.     pinged: {
  18.       effect({ setContext, event }) {
  19.         setContext(c => ({ timeout: event?.value ?? 0 }));
  20.       },
  21.     }
  22.   },
  23. });

  24. send({ type: 'PING', value: 150 })
  25. ```

Note that you don't need to declare all your events in the schema, only the ones you're adding arbitrary keys and values.


Wiki



Contributors ✨


Thanks goes to these wonderful people (emoji key):




    

Cassio Zen

💻 📖 ⚠️ 🤔 🐛

Devansh Jethmalani

💻 ⚠️ 🤔 🐛

Michael Schmidt

💻 ⚠️ 🤔

Joseph

💻

Jeremy Mack

📖

Ron

📖

Klaus Breyer

📖

Arthur Denner

💻 🐛 ⚠️ 🤔






This project follows the all-contributors specification. Contributions of any kind welcome!