@xstate/react
TypeScript icon, indicating that this package has built-in type declarations

4.1.1 • Public • Published

@xstate/react

This package contains utilities for using XState with React.

Quick start

  1. Install xstate and @xstate/react:
npm i xstate @xstate/react
  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({ type: 'TOGGLE' })}>
      {state.value === 'inactive'
        ? 'Click to activate'
        : 'Active! Click to deactivate'}
    </button>
  );
};

Dependents (387)

Package Sidebar

Install

npm i @xstate/react

Weekly Downloads

793,755

Version

4.1.1

License

MIT

Unpacked Size

35.2 kB

Total Files

20

Last publish

Collaborators

  • xstate-release-bot
  • andarist
  • davidkpiano