react-use-event-reducer
TypeScript icon, indicating that this package has built-in type declarations

0.0.5 • Public • Published

useEventReducer()

Bundlephobia Types NPM Version MIT License

npm i react-use-event-reducer

A React hook for leveraging useReducer with strongly typed events, each with a separate handler.

Quick Start

Create your custom hook to manage your state

// useAppendOnlyString.ts
import { useEventReducer, Handlers } from "react-use-event-reducer";

// Specify the type of your state
type State = {
  text: string,
};

// Specify your events and the expected payload
type Events = {
  Append: {
    text: string,
    repetitions: number,
  },
  Clear: void,
};

// Create your strongly typed handlers
const handlers: Handlers<State, Events> = {
  Append: (state: State, payload) => {
    // return new state
    return {
      text: `${state.text}${payload.text.repeat(payload.repetitions)}`,
    };
  },
  Clear: () => ({ text: "" }),
};

export const useAppendOnlyString = (initialState: State) =>
  useEventReducer(handlers, initialState);

Use your custom hook

// ExampleComponent.ts
import React from "react";
import { useAppendOnlyString } from "./useAppendOnlyString";

const ExampleComponent: React.FC = () => {
  const { state, emit } = useAppendOnlyString({ text: "" });

  return (
    <div>
      <h1>{state.text}</h1>
      <button
        onClick={() => emit.Append({ text: "hello world", repetitions: 1 })}
      >
        Append
      </button>
      <button onClick={() => emit.Clear()}>Clear</button>
    </div>
  );
};

/react-use-event-reducer/

    Package Sidebar

    Install

    npm i react-use-event-reducer

    Weekly Downloads

    8

    Version

    0.0.5

    License

    MIT

    Unpacked Size

    5.5 kB

    Total Files

    6

    Last publish

    Collaborators

    • thehenrymcintosh