├── .babelrc ├── .eslintrc ├── .github └── workflows │ ├── codeql-analysis.yml │ ├── package.yml │ └── test.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── package.json ├── rollup.config.js ├── src ├── index.js └── index.test.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { "presets": ["@0y0/vanilla"] } 2 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { "extends": "@0y0/vanilla" } 2 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: CodeQL 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | schedule: 9 | - cron: '0 20 * * 5' 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ubuntu-latest 15 | permissions: 16 | actions: read 17 | contents: read 18 | security-events: write 19 | strategy: 20 | fail-fast: false 21 | matrix: 22 | language: [javascript] 23 | steps: 24 | - name: Checkout repository 25 | uses: actions/checkout@v2 26 | - name: Initialize CodeQL 27 | uses: github/codeql-action/init@v1 28 | with: 29 | languages: ${{ matrix.language }} 30 | - name: Autobuild 31 | uses: github/codeql-action/autobuild@v1 32 | - name: Perform CodeQL Analysis 33 | uses: github/codeql-action/analyze@v1 34 | -------------------------------------------------------------------------------- /.github/workflows/package.yml: -------------------------------------------------------------------------------- 1 | name: Package 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | package: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-node@v2 14 | with: 15 | node-version: 19 16 | registry-url: https://registry.npmjs.org/ 17 | - run: yarn install --frozen-lockfile 18 | - run: yarn lint && yarn test 19 | - run: yarn build 20 | - run: yarn pkg 21 | env: 22 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 23 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | pull_request 5 | 6 | jobs: 7 | test: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v2 12 | with: 13 | node-version: 19 14 | - run: yarn install --frozen-lockfile 15 | - run: yarn lint && yarn test 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/macos,vscode,node 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=macos,vscode,node 3 | 4 | ### macOS ### 5 | # General 6 | .DS_Store 7 | .AppleDouble 8 | .LSOverride 9 | 10 | # Icon must end with two \r 11 | Icon 12 | 13 | 14 | # Thumbnails 15 | ._* 16 | 17 | # Files that might appear in the root of a volume 18 | .DocumentRevisions-V100 19 | .fseventsd 20 | .Spotlight-V100 21 | .TemporaryItems 22 | .Trashes 23 | .VolumeIcon.icns 24 | .com.apple.timemachine.donotpresent 25 | 26 | # Directories potentially created on remote AFP share 27 | .AppleDB 28 | .AppleDesktop 29 | Network Trash Folder 30 | Temporary Items 31 | .apdisk 32 | 33 | ### Node ### 34 | # Logs 35 | logs 36 | *.log 37 | npm-debug.log* 38 | yarn-debug.log* 39 | yarn-error.log* 40 | lerna-debug.log* 41 | 42 | # Diagnostic reports (https://nodejs.org/api/report.html) 43 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 44 | 45 | # Runtime data 46 | pids 47 | *.pid 48 | *.seed 49 | *.pid.lock 50 | 51 | # Directory for instrumented libs generated by jscoverage/JSCover 52 | lib-cov 53 | 54 | # Coverage directory used by tools like istanbul 55 | coverage 56 | *.lcov 57 | 58 | # nyc test coverage 59 | .nyc_output 60 | 61 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 62 | .grunt 63 | 64 | # Bower dependency directory (https://bower.io/) 65 | bower_components 66 | 67 | # node-waf configuration 68 | .lock-wscript 69 | 70 | # Compiled binary addons (https://nodejs.org/api/addons.html) 71 | build/Release 72 | 73 | # Dependency directories 74 | node_modules/ 75 | jspm_packages/ 76 | 77 | # TypeScript v1 declaration files 78 | typings/ 79 | 80 | # TypeScript cache 81 | *.tsbuildinfo 82 | 83 | # Optional npm cache directory 84 | .npm 85 | 86 | # Optional eslint cache 87 | .eslintcache 88 | 89 | # Optional stylelint cache 90 | .stylelintcache 91 | 92 | # Microbundle cache 93 | .rpt2_cache/ 94 | .rts2_cache_cjs/ 95 | .rts2_cache_es/ 96 | .rts2_cache_umd/ 97 | 98 | # Optional REPL history 99 | .node_repl_history 100 | 101 | # Output of 'npm pack' 102 | *.tgz 103 | 104 | # Yarn Integrity file 105 | .yarn-integrity 106 | 107 | # dotenv environment variables file 108 | .env 109 | .env.test 110 | .env*.local 111 | 112 | # parcel-bundler cache (https://parceljs.org/) 113 | .cache 114 | .parcel-cache 115 | 116 | # Next.js build output 117 | .next 118 | 119 | # Nuxt.js build / generate output 120 | .nuxt 121 | dist 122 | 123 | # Gatsby files 124 | .cache/ 125 | # Comment in the public line in if your project uses Gatsby and not Next.js 126 | # https://nextjs.org/blog/next-9-1#public-directory-support 127 | # public 128 | 129 | # vuepress build output 130 | .vuepress/dist 131 | 132 | # Serverless directories 133 | .serverless/ 134 | 135 | # FuseBox cache 136 | .fusebox/ 137 | 138 | # DynamoDB Local files 139 | .dynamodb/ 140 | 141 | # TernJS port file 142 | .tern-port 143 | 144 | # Stores VSCode versions used for testing VSCode extensions 145 | .vscode-test 146 | 147 | ### vscode ### 148 | .vscode/* 149 | !.vscode/settings.json 150 | !.vscode/tasks.json 151 | !.vscode/launch.json 152 | !.vscode/extensions.json 153 | *.code-workspace 154 | 155 | # End of https://www.toptal.com/developers/gitignore/api/macos,vscode,node 156 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "avoid", 3 | "semi": false, 4 | "singleQuote": true, 5 | "trailingComma": "none" 6 | } 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Jason Chung 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # @0y0/use-reducer-x · [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/o0y0o/use-reducer-x/blob/master/LICENSE) [![npm](https://img.shields.io/npm/v/@0y0/use-reducer-x.svg)](https://www.npmjs.com/package/@0y0/use-reducer-x) ![Package Status](https://github.com/o0y0o/use-reducer-x/workflows/Package/badge.svg) ![Test Status](https://github.com/o0y0o/use-reducer-x/workflows/Test/badge.svg) 2 | 3 | `@0y0/use-reducer-x` is an alternative to `React.useReducer` that accepts middlewares to do some cool things before and after dispatch. 4 | 5 | Inspired by [Redux Middleware](https://redux.js.org/api/applymiddleware). 6 | 7 | ### 3-second quick look 8 | 9 | ```js 10 | import useReducerX from '@0y0/use-reducer-x' 11 | 12 | function App() { 13 | const middlewares = [ 14 | ({ getState, dispatch }) => next => action => { 15 | // do something before dispatch... 16 | next(action) 17 | // do something after dispatch... 18 | } 19 | ] 20 | const [state, dispatch] = useReducerX(reducer, initialState, middlewares) 21 | // ... 22 | } 23 | ``` 24 | 25 | ## Installation 26 | 27 | ```sh 28 | npm install @0y0/use-reducer-x --save 29 | ``` 30 | 31 | ## Real-world Usage 32 | 33 | ```js 34 | import React from 'react' 35 | import useReducerX from '@0y0/use-reducer-x' 36 | import thunkMiddleware from 'redux-thunk' 37 | 38 | function logMiddleware({ getState }) { 39 | return next => action => { 40 | console.log('Prev State:', getState()) 41 | console.log('Action:', action) 42 | next(action) 43 | console.log('Next State:', getState()) 44 | } 45 | } 46 | 47 | function gaMiddleware({ getState }) { 48 | return next => action => { 49 | window.ga && window.ga('send', 'event', 'Action', action.type) 50 | next(action) 51 | } 52 | } 53 | 54 | function useAppReducer(reducer, inititalState) { 55 | return useReducerX(reducer, inititalState, [ 56 | thunkMiddleware, 57 | logMiddleware, 58 | gaMiddleware 59 | ]) 60 | } 61 | 62 | function counterReducer(state, action) { 63 | switch (action.type) { 64 | case '+1': return { count: state.count + 1 } 65 | case '-1': return { count: state.count - 1 } 66 | case '0': return { count: 0 } 67 | default: return state 68 | } 69 | } 70 | 71 | function resetCounterAfter1Second() { 72 | return dispatch => setTimeout(() => { dispatch({ type: '0' }) }, 1000) 73 | } 74 | 75 | function App() { 76 | const [state, dispatch] = useAppReducer(counterReducer, 0) 77 | return ( 78 | 79 | 80 | 81 | 82 |
83 | Count: {state.count} 84 |
85 | ) 86 | } 87 | ``` 88 | 89 | Try the demo in [codesanbox](https://codesandbox.io/s/xono668ynz). 90 | 91 | ## License 92 | 93 | [MIT](https://github.com/o0y0o/use-reducer-x/blob/master/LICENSE) 94 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@0y0/use-reducer-x", 3 | "version": "1.0.0", 4 | "description": "An alternative to React.useReducer that accepts middlewares to do some cool things before and after dispatch.", 5 | "src": "src/index.js", 6 | "main": "dist/index.cjs.js", 7 | "module": "dist/index.esm.js", 8 | "repository": "https://github.com/o0y0o/use-reducer-x", 9 | "author": "Jason Chung ", 10 | "license": "MIT", 11 | "publishConfig": { 12 | "access": "public" 13 | }, 14 | "files": [ 15 | "/dist" 16 | ], 17 | "keywords": [ 18 | "react", 19 | "react-hooks", 20 | "hooks", 21 | "use-reducer", 22 | "use-state", 23 | "redux", 24 | "redux-middleware", 25 | "middleware", 26 | "dispatch" 27 | ], 28 | "scripts": { 29 | "format": "prettier --write src/*.js", 30 | "lint": "eslint src/*.js", 31 | "test": "jest", 32 | "build": "rollup -c --bundleConfigAsCjs", 33 | "pkg": "[ $(yarn info $npm_package_name version) != $npm_package_version ] && yarn publish || echo Skip publishing due to v$npm_package_version exist" 34 | }, 35 | "devDependencies": { 36 | "@0y0/babel-preset-vanilla": "^1.1.6", 37 | "@0y0/eslint-config-vanilla": "^1.4.0", 38 | "@rollup/plugin-babel": "^6.0.3", 39 | "@testing-library/react-hooks": "^8.0.1", 40 | "babel-jest": "^29.6.2", 41 | "eslint": "^8.46.0", 42 | "jest": "^29.6.2", 43 | "prettier": "^2.8.8", 44 | "react": "^18.2.0", 45 | "react-test-renderer": "^18.2.0", 46 | "rollup": "^3.27.2" 47 | }, 48 | "peerDependencies": { 49 | "react": ">=16.8.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import path from 'path' 2 | import babel from '@rollup/plugin-babel' 3 | import pkg from './package.json' 4 | 5 | const external = [pkg.dependencies, pkg.peerDependencies] 6 | .filter(Boolean) 7 | .flatMap(dep => Object.keys(dep)) 8 | .map(pkg => new RegExp(`^${pkg}`)) 9 | 10 | export default { 11 | input: path.join(__dirname, pkg.src), 12 | external, 13 | plugins: [babel({ exclude: 'node_modules/**', babelHelpers: 'runtime' })], 14 | output: [ 15 | { 16 | file: path.join(__dirname, pkg.main), 17 | format: 'cjs', 18 | exports: 'default' 19 | }, 20 | { 21 | file: path.join(__dirname, pkg.module), 22 | format: 'es' 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { useRef, useState } from 'react' 2 | 3 | function compose(...fns) { 4 | if (fns.length === 0) return arg => arg 5 | if (fns.length === 1) return fns[0] 6 | return fns.reduce( 7 | (a, b) => 8 | (...args) => 9 | a(b(...args)) 10 | ) 11 | } 12 | 13 | function useReducerX(reducer, initialState, middlewares = []) { 14 | const hook = useState(initialState) 15 | const state = hook[0] 16 | const setState = hook[1] 17 | const draftState = useRef(initialState) 18 | 19 | const dispatch = action => { 20 | draftState.current = reducer(draftState.current, action) 21 | setState(draftState.current) 22 | return action 23 | } 24 | const store = { 25 | getState: () => draftState.current, 26 | dispatch: (...args) => enhancedDispatch(...args) 27 | } 28 | const chain = middlewares.map(middleware => middleware(store)) 29 | const enhancedDispatch = compose.apply(undefined, chain)(dispatch) 30 | 31 | return [state, enhancedDispatch] 32 | } 33 | 34 | export default useReducerX 35 | -------------------------------------------------------------------------------- /src/index.test.js: -------------------------------------------------------------------------------- 1 | import { act, renderHook } from '@testing-library/react-hooks' 2 | import useReducerX from './index' 3 | 4 | const initialState = 0 5 | const reducer = (state, action) => { 6 | switch (action.type) { 7 | case '+1': 8 | return state + 1 9 | case '+x': 10 | return state + action.x 11 | default: 12 | return state 13 | } 14 | } 15 | 16 | test('useReducerX should work like React.useReducer', () => { 17 | const { result } = renderHook(() => useReducerX(reducer, initialState)) 18 | 19 | act(() => { 20 | result.current[1]({}) 21 | }) 22 | expect(result.current[0]).toEqual(0) 23 | 24 | act(() => { 25 | result.current[1]({ type: '+1' }) 26 | }) 27 | expect(result.current[0]).toEqual(1) 28 | 29 | act(() => { 30 | result.current[1]({ type: '+x', x: 2 }) 31 | }) 32 | expect(result.current[0]).toEqual(3) 33 | }) 34 | 35 | test('middlewares should be invoked by order', () => { 36 | let step = 0 37 | const middlewares = [ 38 | () => next => action => { 39 | expect(++step).toEqual(1) 40 | next(action) 41 | expect(++step).toEqual(4) 42 | }, 43 | () => next => action => { 44 | expect(++step).toEqual(2) 45 | next(action) 46 | expect(++step).toEqual(3) 47 | } 48 | ] 49 | const { result } = renderHook(() => 50 | useReducerX(reducer, initialState, middlewares) 51 | ) 52 | 53 | act(() => { 54 | result.current[1]({}) 55 | }) 56 | 57 | expect(step).toEqual(4) 58 | }) 59 | 60 | test('middleware should able to re-dispatch action', () => { 61 | let step = 0 62 | const middlewares = [ 63 | ({ dispatch }) => 64 | next => 65 | action => { 66 | if (typeof action === 'function') { 67 | expect(++step).toEqual(1) 68 | action(dispatch) 69 | expect(++step).toEqual(2) 70 | } else { 71 | expect(++step).toEqual(4) 72 | next(action) 73 | expect(++step).toEqual(7) 74 | } 75 | }, 76 | () => next => action => { 77 | expect(++step).toEqual(5) 78 | next(action) 79 | expect(++step).toEqual(6) 80 | } 81 | ] 82 | const { result } = renderHook(() => 83 | useReducerX(reducer, initialState, middlewares) 84 | ) 85 | 86 | act(() => { 87 | result.current[1](dispatch => setTimeout(() => dispatch({}))) 88 | }) 89 | 90 | expect(++step).toEqual(3) 91 | }) 92 | 93 | test('middleware should able to get state', () => { 94 | const x = 2 95 | const addAction = { type: '+x', x } 96 | const middlewares = [ 97 | ({ getState }) => 98 | next => 99 | action => { 100 | expect(getState()).toEqual(initialState) 101 | next(action) 102 | expect(getState()).toEqual(initialState + x) 103 | } 104 | ] 105 | const { result } = renderHook(() => 106 | useReducerX(reducer, initialState, middlewares) 107 | ) 108 | 109 | act(() => { 110 | result.current[1](addAction) 111 | }) 112 | }) 113 | --------------------------------------------------------------------------------