Socket
Socket
Sign inDemoInstall

react-use-event-reducer

Package Overview
Dependencies
3
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    react-use-event-reducer

A React hook for reducing state from strongly typed events.


Version published
Maintainers
1
Created

Readme

Source

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

Keywords

FAQs

Last updated on 13 Mar 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc