Skip to content

createReducer

Category
Export Size
327 B
Last Changed
5 days ago

Build a useReducer-shaped hook around a Redux-style middleware chain.

Demo

Usage

tsx
import { 
createReducer
} from '@reause/shared'
type
Action
= {
type
: 'increment' } | {
type
: 'reset',
payload
: number }
// called once, at module scope: the returned function is a hook const
useReducer
=
createReducer
<
Action
, {
count
: number }>(
// store / next / action are contextually typed by the factory
store
=>
next
=> (
action
) => {
const
result
=
next
(
action
)
console
.
log
('count',
store
.
getState
().
count
) // already the new state
return
result
}, ) function
Counter
() {
const [
state
,
dispatch
] =
useReducer
(
(
state
,
action
) =>
action
.
type
=== 'increment'
? {
count
:
state
.
count
+ 1 }
: {
count
:
action
.
payload
},
{
count
: 0 },
) return <
button
onClick={() =>
dispatch
({
type
: 'increment' })}>{
state
.count}</button>
}

Type Declarations

ts
type Middleware<Action, State> = (store: Store<Action, State>) => (next: Dispatch<Action>) => (action: Action) => void

export function createReducer<Action, State>(...middlewares: Middleware<Action, State>[])

Source

Source · Demo · react-use

Contributors

hairyf

Changelog

v0.1.6 on
28897 - feat(shared): add createReducer (#931)

Released under the MIT License. v0.1.8