react-use-event-reducer
v0.0.5
Published
A React hook for reducing state from strongly typed events.
Downloads
85
Maintainers
Readme
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>
);
};