react-micro-reducer
v2.0.1
Published
A React reducer hook, with a "micro"-reducer style, made for a Typescript world π
Downloads
1,035
Maintainers
Readme
react-micro-reducer
A React reducer hook, with a "micro"-reducer style, made for a Typescript world π
Split your reducer into micro reducers based on actions, and avoid having one large reducer function with a switch statement
useMicroReducer uses the standard useReducer under the hook π
Ohh, and it supports Immer π
Installation
npm i react-micro-reducer
Demo
I've made a couple of Codesandboxes to play around with useMicroReducer
Usage
import React from "react";
import { useMicroReducer } from "react-micro-reducer";
export default function App() {
const [state, dispatch] = useMicroReducer(
state => ({
reset: () => 0,
increment: (value: number) => state + value,
decrement: (value: number) => state - value,
multiply: (value: number) => state * value
}),
0
);
return (
<div>
<h1>{state}</h1>
<button onClick={() => dispatch.decrement(5)}>Decrement with 5</button>
<button onClick={() => dispatch.increment(5)}>Increment with 5</button>
<button onClick={() => dispatch.multiply(5)}>Multiply with 5</button>
<button onClick={() => dispatch.reset()}>Reset</button>
</div>
);
}
Usage with Immer
Just pass the produce function as a third argument to useMicroReducer, and your state will be a draft object πͺ
import React from "react";
import { useMicroReducer } from "react-micro-reducer";
import produce from "immer";
export default function App() {
const [state, dispatch] = useMicroReducer(
draft => ({
search: (query: string) => {
// Draft is an immer draft object π
draft.query = query;
}
}),
{
query: ""
},
produce
);
// Return render stuff
}
Credits
Thanks to Maciej Sikora for helping with the type definitions, and to Jeppe Hasseris for helping with the naming/API! π