Skip to content

A React reducer hook, with a "micro"-reducer style, made for a Typescript world πŸ’™

License

Notifications You must be signed in to change notification settings

kasperpihl/react-micro-reducer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

57 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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! πŸ™Œ

About

A React reducer hook, with a "micro"-reducer style, made for a Typescript world πŸ’™

Resources

License

Stars

Watchers

Forks

Packages