A React hook for reducing state from strongly typed events.
npm i react-use-event-reducer
A React hook for leveraging useReducer with strongly typed events, each with a separate handler.
Create your custom hook to manage your state
``jsx harmony
// 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
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
`jsx harmony
// ExampleComponent.ts
import React from "react";
import { useAppendOnlyString } from "./useAppendOnlyString";
const ExampleComponent: React.FC = () => {
const { state, emit } = useAppendOnlyString({ text: "" });
return (