# react-states

> Explicit states for predictable user experiences

Latest version **8.3.7** (published 2024-06-10) · MIT license · 0 weekly downloads

## Install

```sh
npm install react-states
pnpm add react-states
yarn add react-states
bun add react-states
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 8.3.7 |
| Published | 2024-06-10 |
| First published | 2021-02-15 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 32.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 141 |
| Author | Christian Alfoni |
| Maintainers | christianalfoni |
| Keywords | typescript, react, reducer, state, statemachine |

## Links

- npm: https://www.npmjs.com/package/react-states
- Repository: https://github.com/christianalfoni/react-states
- Homepage: https://github.com/christianalfoni/react-states#readme
- Issues: https://github.com/christianalfoni/react-states/issues
- npm.io page: https://npm.io/package/react-states

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 8.3.7 (latest) — 2024-06-10
- 8.0.0-rc13 (next) — 2022-08-09
- 6.26.2-next-fix2 (next-fix2) — 2022-06-29
- 6.26.2-next-fix (next-fix) — 2022-06-29
- 8.3.6 — 2024-05-30
- 8.3.4 — 2024-05-25
- 8.3.3 — 2024-05-24
- 8.3.2 — 2024-05-24
- 8.3.1 — 2024-05-24
- 8.3.0 — 2024-05-23
- 8.2.0 — 2024-05-22
- 8.1.4 — 2024-05-22
- 8.1.3 — 2024-05-21
- 8.1.2 — 2024-05-21
- 8.1.1 — 2024-05-21
- … 217 more at https://npm.io/package/react-states/versions

## README

# react-states

> Explicit states for predictable user experiences

## Install

```sh
npm install react-states
```

## Description

This video is the initial introduction of the concept:

[![react-states concept](https://img.youtube.com/vi/ul_3ABrpj64/0.jpg)](https://www.youtube.com/watch?v=ul_3ABrpj64)

After exploring this concept at [CodeSandbox.io](https://codesandbox.io) we discovered one flaw in the concept. Using transition effects led to a lot of indirection in the code, which made it very difficult to reason about application flows. The indirection happens because your logic is split between the reducer, which is often a single file, and the component handling the effects of those transitions.

To fix this issue **react-states** is now co locating state with effects. That means your reducer does not only describe the transitions from one state to another, but can also describe an `effect` to execute as part of that transition.

You can now define your state, transitions and effects as a pure reducer hook. The actual execution of the effects is implemented with the usage of the hook. This is great for separation of concerns and testability.

## API

### createTransitionsHook

```tsx
import { createTransitionsHook } from "react-states";

type State =
  | {
      status: "NOT_LOADED";
    }
  | {
      status: "LOADING";
    }
  | {
      status: "LOADED";
      data: string;
    }
  | {
      status: "ERROR";
    };

type Action = {
  type: "FETCH";
};

type Effect = {
  type: "FETCH_DATA";
};

const useData = createTransitionsHook<State, Action, Effect>((transition) => ({
  NOT_LOADED: {
    FETCH: () =>
      transition(
        {
          status: "LOADING",
        },
        {
          type: "FETCH_DATA",
        }
      ),
  },
  LOADING: {
    FETCH_SUCCESS: ({ data }) =>
      transition({
        status: "LOADED",
        data,
      }),
    FETCH_ERROR: ({ error }) =>
      transition({
        status: "ERROR",
        error,
      }),
  },
  LOADED: {},
  ERROR: {},
}));

const DataComponent = () => {
  const [state, dispatch] = useData(
    {
      FETCH_DATA: async () => {
        const newData = await Promise.resolve("Some data");

        dispatch({
          type: "FETCH_SUCCESS",
          data: newData,
        });
      },
    },
    {
      status: "NOT_LOADED",
    }
  );

  return <div />;
};
```

The `transition` function is used to ensure type safety. It is not strictly necessary, but TypeScript does not have exact return types. That means you only get errors on lacking properties. The `transition` function ensures exact types on your state and effects.

### match

Transform state into values and UI.

#### Exhaustive match

```tsx
import { match } from "react-states";
import { useData } from "./useData";

const DataComponent = () => {
  const [state, dispatch] = useData(
    {
      FETCH_DATA: async () => {
        const newData = await Promise.resolve("Some data");

        dispatch({
          type: "FETCH_SUCCESS",
          data: newData,
        });
      },
    },
    {
      status: "NOT_LOADED",
    }
  );

  return match(state, {
    NOT_LOADED: () => (
      <button onClick={() => dispatch({ type: "LOAD" })}>Load data</button>
    ),
    LOADING: () => "Loading...",
    LOADED: ({ data }) => <div>Data: {data}</div>,
    ERROR: ({ error }) => <div style={{ color: "red" }}>{error}</div>,
  });
};
```

#### Partial match

```tsx
import { match } from "react-states";
import { useData } from "./useData";

const DataComponent = () => {
  const [state, dispatch] = useData(
    {
      FETCH_DATA: async () => {
        const newData = await Promise.resolve("Some data");

        dispatch({
          type: "FETCH_SUCCESS",
          data: newData,
        });
      },
    },
    {
      status: "NOT_LOADED",
    }
  );

  const dataWithDefault = match(
    state,
    {
      LOADED: ({ data }) => data,
    },
    (otherStates) => "No data yet"
  );

  return <div>Data: {dataWithDefault}</div>;
};
```

#### Match by key

```tsx
import { match } from "react-states";
import { useData } from "./useData";

const DataComponent = () => {
  const [state, dispatch] = useData(
    {
      FETCH_DATA: async () => {
        const newData = await Promise.resolve("Some data");

        dispatch({
          type: "FETCH_SUCCESS",
          data: newData,
        });
      },
    },
    {
      status: "NOT_LOADED",
    }
  );

  const dataWithDefault = match(state, "data")?.data ?? "No data yet";

  return <div>Data: {dataWithDefault}</div>;
};
```

### Debugging

```ts
import { debugging } from "react-states";

debugging.active = Boolean(import.meta.DEV);
```

You could also implement custom behaviour like a keyboard shortcut, localStorage etc.

---
_Source: https://npm.io/package/react-states · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
