https://github.com/wasabi315/react-use-actions
https://github.com/wasabi315/react-use-actions
react react-hooks typescript use-reducer
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/wasabi315/react-use-actions
- Owner: wasabi315
- License: mit
- Created: 2020-05-09T17:40:53.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T05:25:35.000Z (over 2 years ago)
- Last Synced: 2024-04-17T03:20:03.341Z (about 1 year ago)
- Topics: react, react-hooks, typescript, use-reducer
- Language: TypeScript
- Size: 2.51 MB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-use-actions
[](https://github.com/tterb/atomic-design-ui/blob/master/LICENSEs)

[](https://david-dm.org/tterb/Hyde)> Just another style of `useReducer`
In this `react-use-actions` world, we define the `reducer` like
```ts
const actions = defineActions()({
increment: state => ({ count: state.count + 1 })
...
})
```instead of
```ts
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 }
...
}
}
```and invoke the `dispatch` with method call style
```ts
const onClick = () => dispatch.increment()
```instead of
```ts
const onClick = () => dispatch({ type: 'INCREMENT' })
```Since the **dispatch object** is fully typed, this style helps editors' autocompletion:heart_eyes:
## Installation
```sh
$ npm i --save react-use-actions
# or
$ yarn add react-use-actions
```## Example
```tsx
import React from 'react'
import { render } from 'react-dom'
import { defineActions, useActions } from 'react-use-actions'interface State {
count: number
}const actions = defineActions()({
decrement: state => ({ count: state.count - 1 }),
increment: state => ({ count: state.count + 1 }),
})const App: React.FC = () => {
const [state, dispatch] = useActions(actions, 0)
return (
-
count = {state.count}
+
)
}render(, document.getElementById('root'))
```## API
### `defineActions()(actions)`
```ts
interface State {
...
}const actions = defineActions()({
foo: state => { /* 'state' is typed as 'State' here */ return ... },
// You can pass arguments to actions
bar: (state, arg1: T1, arg2: T2) => { return ... },
// Optional argument and variable length argument are allowed
baz: (state, arg3: T3 = t3, ...arg4: T4[]) => { return ... },
})
```A no-op behavior-wise function. This function is provided only for type inference.
### `useActions(actions, intialState)`
```tsx
const SomeComponent = () => {
const [state, dispatch] = useActions(actions, initialState)
...
return (
<>
{/* 'dispatch' is fully typed! */}
dispatch.foo()}>foo
dispatch.bar(arg1, arg2)}>foo
dispatch.baz(arg3, arg41, arg42)}>foo
>
)
}
```You can create an initial state lazily as with the original API of `useReducer`.
```ts
const [state, dispatch] = useActions(actions, initialArg, initializer)
```## License
MIT