https://github.com/o0y0o/use-reducer-x
๐ฉ An alternative to useReducer that accepts middlewares.
https://github.com/o0y0o/use-reducer-x
npm-package react react-hooks reducer redux
Last synced: 3 months ago
JSON representation
๐ฉ An alternative to useReducer that accepts middlewares.
- Host: GitHub
- URL: https://github.com/o0y0o/use-reducer-x
- Owner: o0y0o
- License: mit
- Created: 2018-11-13T02:23:01.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-08-30T13:19:18.000Z (11 months ago)
- Last Synced: 2025-04-11T12:24:46.221Z (3 months ago)
- Topics: npm-package, react, react-hooks, reducer, redux
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/@0y0/use-reducer-x
- Size: 723 KB
- Stars: 70
- Watchers: 1
- Forks: 7
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @0y0/use-reducer-x ยท [](https://github.com/o0y0o/use-reducer-x/blob/master/LICENSE) [](https://www.npmjs.com/package/@0y0/use-reducer-x)  
`@0y0/use-reducer-x` is an alternative to `React.useReducer` that accepts middlewares to do some cool things before and after dispatch.
Inspired by [Redux Middleware](https://redux.js.org/api/applymiddleware).
### 3-second quick look
```js
import useReducerX from '@0y0/use-reducer-x'function App() {
const middlewares = [
({ getState, dispatch }) => next => action => {
// do something before dispatch...
next(action)
// do something after dispatch...
}
]
const [state, dispatch] = useReducerX(reducer, initialState, middlewares)
// ...
}
```## Installation
```sh
npm install @0y0/use-reducer-x --save
```## Real-world Usage
```js
import React from 'react'
import useReducerX from '@0y0/use-reducer-x'
import thunkMiddleware from 'redux-thunk'function logMiddleware({ getState }) {
return next => action => {
console.log('Prev State:', getState())
console.log('Action:', action)
next(action)
console.log('Next State:', getState())
}
}function gaMiddleware({ getState }) {
return next => action => {
window.ga && window.ga('send', 'event', 'Action', action.type)
next(action)
}
}function useAppReducer(reducer, inititalState) {
return useReducerX(reducer, inititalState, [
thunkMiddleware,
logMiddleware,
gaMiddleware
])
}function counterReducer(state, action) {
switch (action.type) {
case '+1': return { count: state.count + 1 }
case '-1': return { count: state.count - 1 }
case '0': return { count: 0 }
default: return state
}
}function resetCounterAfter1Second() {
return dispatch => setTimeout(() => { dispatch({ type: '0' }) }, 1000)
}function App() {
const [state, dispatch] = useAppReducer(counterReducer, 0)
return (
dispatch({ type: '+1' })}>+
dispatch(resetCounterAfter1Second())}>Reset
dispatch({ type: '-1' })}>-
Count: {state.count}
)
}
```Try the demo in [codesanbox](https://codesandbox.io/s/xono668ynz).
## License
[MIT](https://github.com/o0y0o/use-reducer-x/blob/master/LICENSE)