Skip to content

A utility that creates a type-safe reducer and actions

License

Notifications You must be signed in to change notification settings

eylamf/tiny-reducer

Repository files navigation

tiny-reducer

A tiny utility that helps you create type-safe reducers with readable actions

Installation

npm install tiny-reducer
# or
yarn add tiny-reducer

Note

This package uses immer (docs) under the hood so you will need to install it as well

API

import { createReducer } from "tiny-reducer";

type State = { count: number };

const initialState: State = {
  count: 0,
};

const { reducer, actions } = createReducer(initialState, {
  increment(state) {
    state.count += 1;
  },
  assign(state, value: number) {
    state.count = value;
  },
});

Example with React's useReducer

import { useReducer } from "react";

function MyComponent() {
  // Using the reducer and actions from the snippet above 👆
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleIncrement = () => {
    dispatch(actions.increment());
  };

  const handleAssign = () => {
    dispatch(actions.assign(10));
  };

  // render (...);
}

Outside of React

This can be used with any JS logic since it is just a type-safe reducer

function someFunc(toValue: number) {
  const initial = getInitialState(...);
  const afterAssignment = reducer(initial, actions.assign(toValue));
  return reducer(afterAssignment, actions.increment());
}

About

A utility that creates a type-safe reducer and actions

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published