@xstate/react

XState tools for React

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
@xstate/react
23,1252383.2.1a month ago4 years agoMinified + gzip package size for @xstate/react in KB

Readme

@xstate/react
This package contains utilities for using XState with React.

Quick start

  1. Install xstate and @xstate/react:

npm i xstate @xstate/react

Via CDN
<script src="https://unpkg.com/@xstate/react/dist/xstate-react.umd.min.js"></script>

By using the global variable XStateReact
or
<script src="https://unpkg.com/@xstate/react/dist/xstate-react-fsm.umd.min.js"></script>

By using the global variable XStateReactFSM
  1. Import the useMachine hook:

import { useMachine } from '@xstate/react';
import { createMachine } from 'xstate';

const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: { TOGGLE: 'active' }
    },
    active: {
      on: { TOGGLE: 'inactive' }
    }
  }
});

export const Toggler = () => {
  const [state, send] = useMachine(toggleMachine);

  return (
    <button onClick={() => send('TOGGLE')}>
      {state.value === 'inactive'
        ? 'Click to activate'
        : 'Active! Click to deactivate'}
    </button>
  );
};