one-hook
Size
0.21 kb
View source

useActions

A simpler and typesafe alternative to useReducer.

Installation

npm install @1hook/use-actions

Quick Start

Define how each action modifies the state:

export const  = ((: number) => ({
  : (: number) =>  + ,
  : (: number) =>  - ,
}))

Use the actions in your component:

const [, ] = (0)

.(1)
.(3)

Build a generic hook

We can leverage typescript generics to build reusable hooks.

Let's build a custom useArray hook:

use-array.ts
export const useArray = defineActions(<T>(items: Array<T>) => ({
  push: (item: T) => [...items, item],
  remove: (item: T) => items.filter((i) => i !== item),
  clear: () => [],
}))

We can now use the useArray hook in our components:

const [, ] = ([1, 2, 3])

.(4)
.(2)
.()

On this page