0.0.5 • Published 2 years ago

react-use-event-reducer v0.0.5

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

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>
  );
};
0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago