react-states
TypeScript icon, indicating that this package has built-in type declarations

7.2.1 • Public • Published

react-states

Explicit states for predictable user experiences

Install

npm install react-states

Introduction to react-states

react-states

Examples

Documentation

Values

  • "It is just a reducer"
  • Simple utilities
  • Enhanced type safety
  • Reducer does not express side effects

Learn by example

Instead of expressing your state implicitly:

type State = {
  isLoading: boolean;
  error: string | null;
  data: string[];
};

You can do so explicitly:

type State =
  | {
      state: 'NOT_LOADED';
    }
  | {
      state: 'LOADING';
    }
  | {
      state: 'LOADED';
      data: string[];
    }
  | {
      state: 'ERROR';
      error: string;
    };

With explicit states you can guard what actions are valid in what states using transition:

import { transition } from 'react-states';

const reducer = (prevState: State, action: Action) =>
  transition(prevState, action, {
    NOT_LOADED: {
      FETCH: () => ({
        state: 'LOADING',
      }),
    },
    LOADING: {
      FETCH_SUCCESS: (_, { data }) => ({
        state: 'LOADED',
        data,
      }),
      FETCH_ERROR: (_, { error }) => ({
        state: 'ERROR',
        error,
      }),
    },
    LOADED: {},
    ERROR: {},
  });

With additional utilities like createStates, createActions and match you will increase safety and reduce boilerplate in your code.

Package Sidebar

Install

npm i react-states

Weekly Downloads

50

Version

7.2.1

License

MIT

Unpacked Size

250 kB

Total Files

81

Last publish

Collaborators

  • christianalfoni