Skip to content

Explicit states for predictable user experiences

License

Notifications You must be signed in to change notification settings

Volue/react-states

 
 

Repository files navigation

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.

About

Explicit states for predictable user experiences

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 96.3%
  • CSS 1.7%
  • JavaScript 1.3%
  • HTML 0.7%