JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 10654
  • Score
    100M100P100Q5618F
  • License MIT

React hook for managing effects from reducers.

Package Exports

  • react-use-bireducer
  • react-use-bireducer/dist/index.esm.js
  • react-use-bireducer/dist/index.umd.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-use-bireducer) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

🔀 React use bireducer tests codecov npm

React hook for managing effectful reducers.

Motivation

When your application gets bigger, it is hard to manage both state changes and effectful computations. I find the Model-View-Update pattern (which the Elm architecture is based on) really effective for this kind of task. useBireducer implements this pattern by combining two reducers (hence the name): a state reducer and an effect reducer.

The state reducer is really close to useReducer, except that it returns the new state AND the effects to execute:

type StateReducer<S, A, E> = (state: S, action: A) => [S, Array<E>];

The effect reducer just executes effects and can return a cleanup function. This cleanup function is called when the component unmounts:

type EffectReducer<E, A> = (effect: E, dispatch: React.Dispatch<A>) => void | (() => void);

This pattern helps you to separate state changes from effectful computations. It also makes your tests stronger.

Installation

yarn add react-use-bireducer
# or
npm install react-use-bireducer

Usage

import {useBireducer} from "react-use-bireducer";

const [state, dispatch] = useBireducer(stateReducer, effectReducer, defaultState);

See a complete example on CodeSandbox.

If you want to see an example in a real world application, have a look at react-pin-field.

Development

Development environment is managed by Nix. First you need to install it:

curl -L https://nixos.org/nix/install | sh

Then you can start your development environment by spawning a Nix shell:

nix-shell

Now you should be able to clone the repo and install Node.js dependencies:

git clone https://github.com/soywod/react-use-bireducer.git
cd react-use-bireducer
yarn

You can leave the development environment either by killing your terminal or by entering the command exit.

Tests

Tests are handled by Jest (.test files) and React Testing Library (.spec files).

yarn test

Similar projects

  • useEffectReducer: the state reducer exposes a third argument called exec to schedule effects
  • useElmish: it is a mix between useEffectReducer and useBireducer

Sponsoring

github paypal ko-fi buy-me-a-coffee liberapay