All Projects → phenax → use-tiny-state-machine

phenax / use-tiny-state-machine

Licence: MIT License
A tiny (~700 bytes) react hook to help you write finite state machines

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to use-tiny-state-machine

stateless
Finite State Machine porting from Stateless C#
Stars: ✭ 25 (-32.43%)
Mutual labels:  state-machine, finite-state-machine
xstate
State machines and statecharts for the modern web.
Stars: ✭ 21,286 (+57429.73%)
Mutual labels:  state-machine, finite-state-machine
tsm
A Hierarchical State Machine Framework in C++
Stars: ✭ 30 (-18.92%)
Mutual labels:  state-machine, finite-state-machine
StateBuilder
State machine code generator for C++ and Java.
Stars: ✭ 30 (-18.92%)
Mutual labels:  state-machine, finite-state-machine
UnityHFSM
A simple yet powerful class based hierarchical finite state machine for Unity3D
Stars: ✭ 243 (+556.76%)
Mutual labels:  state-machine, finite-state-machine
flviz
FLVIz - Finite Automata Simulator written in QT/Graphviz
Stars: ✭ 36 (-2.7%)
Mutual labels:  state-machine, finite-state-machine
smacha
SMACHA is a meta-scripting, templating, and code generation engine for rapid prototyping of ROS SMACH state machines.
Stars: ✭ 15 (-59.46%)
Mutual labels:  state-machine, finite-state-machine
Python Statemachine
Python Finite State Machines made easy.
Stars: ✭ 184 (+397.3%)
Mutual labels:  state-machine, finite-state-machine
simple-state-machine
A simple Java state machine for Spring Boot projects
Stars: ✭ 25 (-32.43%)
Mutual labels:  state-machine, finite-state-machine
pastafarian
A tiny event-based finite state machine
Stars: ✭ 20 (-45.95%)
Mutual labels:  state-machine, finite-state-machine
React Context Hook
A React.js global state manager with Hooks
Stars: ✭ 50 (+35.14%)
Mutual labels:  hooks, state-machine
statemachine-go
🚦 Declarative Finite-State Machines in Go
Stars: ✭ 47 (+27.03%)
Mutual labels:  state-machine, finite-state-machine
Fluent State Machine
Fluent API for creating state machines in C#
Stars: ✭ 195 (+427.03%)
Mutual labels:  state-machine, finite-state-machine
go-sm
A finite-state machine library for the Go programming language
Stars: ✭ 14 (-62.16%)
Mutual labels:  state-machine, finite-state-machine
Awesome Fsm
🤖 A curated list of awesome resources related to finite state machines and statecharts.
Stars: ✭ 189 (+410.81%)
Mutual labels:  state-machine, finite-state-machine
FiniteStateMachine
This project is a finite state machine designed to be used in games.
Stars: ✭ 45 (+21.62%)
Mutual labels:  state-machine, finite-state-machine
Nanostate
🚦- Small Finite State Machines
Stars: ✭ 151 (+308.11%)
Mutual labels:  state-machine, finite-state-machine
Easy States
The simple, stupid state machine for Java
Stars: ✭ 167 (+351.35%)
Mutual labels:  state-machine, finite-state-machine
use-state-machine
Use Finite State Machines with React Hooks
Stars: ✭ 28 (-24.32%)
Mutual labels:  state-machine, finite-state-machine
useStateMachine
The <1 kb state machine hook for React
Stars: ✭ 2,231 (+5929.73%)
Mutual labels:  hooks, state-machine

useTinyStateMachine

A tiny (~700 bytes) react hook to help you write finite state machines

CircleCI npm bundle size (minified + gzip) Codecov

Read the documentation for more information

Install

Import

yarn add use-tiny-state-machine

Examples

Manual traffic lights

import useTinyStateMachine from 'use-tiny-state-machine';

const stateChart = {
  id: 'traffixLight',
  initial: 'green',
  states: {
    green: { on: { NEXT: 'red' } },
    orange: { on: { NEXT: 'green' } },
    red: { on: { NEXT: 'orange' } },
  },
};

export default function ManualTrafficLights() {
  const { cata, state, dispatch } = useTinyStateMachine(stateChart);

  return (
    <Fragment>
      <div
        className="trafficLight"
        style={{
          backgroundColor: cata({
            green: '#51e980',
            red: '#e74c3c',
            orange: '#ffa500',
          }),
        }}
      >
        The light is {state}
      </div>
      <button onClick={() => dispatch('NEXT')}>Next light</button>
    </Fragment>
  );
};

Automated traffic lights with onEntry action

onEntry is called every time you enter a given state. onEntry is called with the current state machine instance.

import useTinyStateMachine from 'use-tiny-state-machine';

const stateChart = {
  id: "traffixLight",
  initial: "green",
  states: {
    green: {
      onEntry: waitForNextLight,
      on: {
        NEXT: "red"
      }
    },
    orange: {
      onEntry: waitForNextLight,
      on: {
        NEXT: "green"
      }
    },
    red: {
      onEntry: waitForNextLight,
      on: {
        NEXT: "orange"
      }
    }
  }
};

function waitForNextLight({ dispatch }) {
  const timer = setTimeout(() => dispatch('NEXT'), 1000);
  return () => clearTimeout(timer);
}

function TrafficLights() {
  const { cata, state, dispatch } = useTinyStateMachine(stateChart);

  return (
    <Fragment>
      <div
        style={{
          width: "30px",
          height: "30px",
          backgroundColor: cata({
            green: "#51e980",
            red: "#e74c3c",
            orange: "#ffa500"
          })
        }}
      >
        The light is {state}
      </div>
      <button onClick={() => dispatch("NEXT")}>Force next light</button>
    </Fragment>
  );
}

Fetching data

You can use context to store any data associated with a state.

const stateChart = {
  id: 'userData',
  initial: 'idle',
  context: {
    data: null,
    error: null,
  },
  states: {
    idle: {
      on: {
        FETCH: {
          target: 'pending',
          action: ({ dispatch }, userId) => {
            fetchUser(userId)
              .then(user => dispatch('SUCCESS', user))
              .catch(error => dispatch('FAILURE', error));
          },
        },
      },
    },
    pending: {
      on: {
        SUCCESS: {
          target: 'success',
          beforeStateChange: ({ updateContext }, data) => updateContext(c => ({ ...c, data })),
        },
        FAILURE: {
          target: 'failure',
          beforeStateChange: ({ updateContext }, error) => updateContext(c => ({ ...c, error })),
        },
      },
    },
  },
};

const UserData = () => {
  const { context, dispatch, cata } = useTinyStateMachine(stateChart);
  return (
    <div>
      {cata({
        idle: () => (
          <button onClick={() => dispatch('FETCH')}>
            Fetch user data
          </button>
        ),
        pending: () => <Spinner />,
        success: () => `Hi ${context.data.name}`,
        failure: () => `Error: ${context.error.message}`,
      })}
    </div>
  );
};
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].