├── .prettierignore ├── vscode └── settings.json ├── tslint.json ├── .prettierrc.yml ├── .gitignore ├── .editorconfig ├── tsconfig.json ├── .travis.yml ├── CONTRIBUTING.md ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── LICENSE ├── test ├── useTodos.ts └── index.test.tsx ├── src └── index.ts ├── code-of-conduct.md ├── package.json └── README.md /.prettierignore: -------------------------------------------------------------------------------- 1 | lib 2 | coverage 3 | package.json 4 | README.md -------------------------------------------------------------------------------- /vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true 3 | } 4 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ] 6 | } -------------------------------------------------------------------------------- /.prettierrc.yml: -------------------------------------------------------------------------------- 1 | arrowParens: avoid 2 | bracketSpacing: true 3 | printWidth: 100 4 | semi: true 5 | tabWidth: 2 6 | trailingComma: all 7 | singleQuote: true 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache 11 | .rpt2_cache 12 | docs 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module": "es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "jsx": "react", 8 | "strict": true, 9 | "sourceMap": true, 10 | "declaration": true, 11 | "esModuleInterop": true, 12 | "experimentalDecorators": true, 13 | "emitDecoratorMetadata": true, 14 | "outDir": "dist", 15 | "typeRoots": ["node_modules/@types"] 16 | }, 17 | "include": ["src"] 18 | } 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | directories: 4 | - ~/.npm 5 | notifications: 6 | email: false 7 | node_js: 'node' 8 | script: 9 | - npm run test:prod && npm run build 10 | after_success: 11 | - npm run travis-deploy-once "npm run report-coverage" 12 | - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run deploy-docs"; fi 13 | - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run semantic-release"; fi 14 | branches: 15 | except: 16 | - /^v\d+\.\d+\.\d+$/ 17 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/YOUR-USERNAME/typescript-library-starter 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a [GitHub Pull Request](https://github.com/alexjoverm/typescript-library-starter/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 18 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require("shelljs") 2 | const { readFileSync } = require("fs") 3 | const url = require("url") 4 | 5 | let repoUrl 6 | let pkg = JSON.parse(readFileSync("package.json") as any) 7 | if (typeof pkg.repository === "object") { 8 | if (!pkg.repository.hasOwnProperty("url")) { 9 | throw new Error("URL does not exist in repository section") 10 | } 11 | repoUrl = pkg.repository.url 12 | } else { 13 | repoUrl = pkg.repository 14 | } 15 | 16 | let parsedUrl = url.parse(repoUrl) 17 | let repository = (parsedUrl.host || "") + (parsedUrl.path || "") 18 | let ghToken = process.env.GH_TOKEN 19 | 20 | echo("Deploying docs!!!") 21 | cd("docs") 22 | touch(".nojekyll") 23 | exec("git init") 24 | exec("git add .") 25 | exec('git config user.name "Tom Crockett"') 26 | exec('git config user.email "pelotom@gmail.com"') 27 | exec('git commit -m "docs(docs): update gh-pages"') 28 | exec( 29 | `git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages` 30 | ) 31 | echo("Docs deployed!!") 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 Tom Crockett 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "commitlint -E HUSKY_GIT_PARAMS" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "lib", "installer", 'bin'), ['install']) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release-cli setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release-cli setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /test/useTodos.ts: -------------------------------------------------------------------------------- 1 | import useMethods from '../src'; 2 | import React, { useMemo, useRef, useEffect } from 'react'; 3 | 4 | export type Todos = ReturnType; 5 | 6 | export default function useTodos(initialTodos: TodoItem[] = []) { 7 | const initialState: TodosState = { 8 | nextId: initialTodos.reduce((maxId, nextItem) => Math.max(maxId, nextItem.id), 0) + 1, 9 | todos: initialTodos, 10 | filter: 'all', 11 | }; 12 | const [{ todos, filter }, { addTodo, toggleTodo, setFilter }] = useMethods(methods, initialState); 13 | 14 | const visibleTodos = useMemo(() => { 15 | switch (filter) { 16 | case 'all': 17 | return todos; 18 | case 'completed': 19 | return todos.filter(t => t.completed); 20 | case 'active': 21 | return todos.filter(t => !t.completed); 22 | } 23 | }, [todos, filter]); 24 | 25 | // track how many times methods change (should never be more than zero) 26 | const methodChanges = useRef(-1); 27 | useEffect(() => { 28 | methodChanges.current++; 29 | }, [addTodo, toggleTodo, setFilter]); 30 | 31 | return { 32 | todos: visibleTodos, 33 | filter, 34 | addTodo, 35 | toggleTodo, 36 | setFilter, 37 | methodChanges, 38 | }; 39 | } 40 | 41 | interface TodosState { 42 | nextId: number; 43 | todos: TodoItem[]; 44 | filter: VisibilityFilter; 45 | } 46 | 47 | export interface TodoItem { 48 | id: number; 49 | text: string; 50 | completed: boolean; 51 | } 52 | 53 | type VisibilityFilter = 'all' | 'completed' | 'active'; 54 | const visibilityFilters: VisibilityFilter[] = ['all', 'completed', 'active']; 55 | 56 | const methods = (state: TodosState) => ({ 57 | addTodo(text: string) { 58 | if (!text) return; 59 | 60 | state.todos.push({ 61 | id: state.nextId++, 62 | text, 63 | completed: false, 64 | }); 65 | }, 66 | toggleTodo(id: number) { 67 | const todo = state.todos.find(todo => todo.id === id)!; 68 | todo.completed = !todo.completed; 69 | }, 70 | setFilter(filter: VisibilityFilter) { 71 | state.filter = filter; 72 | }, 73 | }); 74 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import produce, { PatchListener } from 'immer'; 2 | import { Reducer, useMemo, useReducer } from 'react'; 3 | 4 | export type StateAndCallbacksFor = [StateFor, CallbacksFor]; 5 | 6 | export type StateFor = M extends MethodsOrOptions 7 | ? S 8 | : never; 9 | 10 | export type CallbacksFor = M extends MethodsOrOptions 11 | ? { 12 | [T in ActionUnion['type']]: ( 13 | ...payload: ActionByType, T>['payload'] 14 | ) => void 15 | } 16 | : never; 17 | 18 | export type Methods = any> = (state: S) => R; 19 | 20 | export type Options = any> = { 21 | methods: Methods; 22 | patchListener?: PatchListener; 23 | }; 24 | 25 | export type MethodsOrOptions = any> = 26 | | Methods 27 | | Options; 28 | 29 | export type MethodRecordBase = Record< 30 | string, 31 | (...args: any[]) => S extends object ? S | void : S 32 | >; 33 | 34 | export type ActionUnion = { 35 | [T in keyof R]: { type: T; payload: Parameters } 36 | }[keyof R]; 37 | 38 | export type ActionByType = A extends { type: infer T2 } ? (T extends T2 ? A : never) : never; 39 | 40 | export default function useMethods>( 41 | methodsOrOptions: MethodsOrOptions, 42 | initialState: S, 43 | ): StateAndCallbacksFor>; 44 | export default function useMethods, I>( 45 | methodsOrOptions: MethodsOrOptions, 46 | initializerArg: I, 47 | initializer: (arg: I) => S, 48 | ): StateAndCallbacksFor>; 49 | export default function useMethods>( 50 | methodsOrOptions: MethodsOrOptions, 51 | initialState: any, 52 | initializer?: any, 53 | ): StateAndCallbacksFor> { 54 | const [reducer, methodsFactory] = useMemo<[Reducer>, Methods]>(() => { 55 | let methods: Methods; 56 | let patchListener: PatchListener | undefined; 57 | if (typeof methodsOrOptions === 'function') { 58 | methods = methodsOrOptions; 59 | } else { 60 | methods = methodsOrOptions.methods; 61 | patchListener = methodsOrOptions.patchListener; 62 | } 63 | return [ 64 | (state: S, action: ActionUnion) => { 65 | return (produce as any)( 66 | state, 67 | (draft: S) => methods(draft)[action.type](...action.payload), 68 | patchListener, 69 | ); 70 | }, 71 | methods, 72 | ]; 73 | }, [methodsOrOptions]); 74 | const [state, dispatch] = useReducer(reducer, initialState, initializer); 75 | const callbacks = useMemo(() => { 76 | const actionTypes: ActionUnion['type'][] = Object.keys(methodsFactory(state)); 77 | return actionTypes.reduce( 78 | (accum, type) => { 79 | accum[type] = (...payload) => dispatch({ type, payload } as ActionUnion); 80 | return accum; 81 | }, 82 | {} as CallbacksFor, 83 | ); 84 | }, []); 85 | return [state, callbacks]; 86 | } 87 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-methods", 3 | "version": "0.5.1", 4 | "description": "A simpler way to useReducers", 5 | "keywords": [ 6 | "react", 7 | "hooks", 8 | "useReducer", 9 | "immer", 10 | "state management" 11 | ], 12 | "main": "dist/index.js", 13 | "typings": "dist/index.d.ts", 14 | "files": [ 15 | "dist", 16 | "src" 17 | ], 18 | "author": "Tom Crockett ", 19 | "repository": { 20 | "type": "git", 21 | "url": "https://github.com/pelotom/use-methods" 22 | }, 23 | "license": "MIT", 24 | "engines": { 25 | "node": ">=6.0.0" 26 | }, 27 | "scripts": { 28 | "lint": "tslint --project tsconfig.json -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 29 | "prebuild": "rimraf dist", 30 | "build": "tsc --module commonjs && typedoc --out docs --target es6 --theme minimal --mode file src", 31 | "start": "rollup -c rollup.config.ts -w", 32 | "test": "jest --coverage", 33 | "test:watch": "jest --coverage --watch", 34 | "test:prod": "npm run lint && npm run test -- --no-cache", 35 | "deploy-docs": "ts-node tools/gh-pages-publish", 36 | "report-coverage": "cat ./coverage/lcov.info | coveralls", 37 | "commit": "git-cz", 38 | "semantic-release": "semantic-release", 39 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 40 | "travis-deploy-once": "travis-deploy-once" 41 | }, 42 | "lint-staged": { 43 | "{src,test}/**/*.ts": [ 44 | "prettier --write", 45 | "git add" 46 | ] 47 | }, 48 | "config": { 49 | "commitizen": { 50 | "path": "node_modules/cz-conventional-changelog" 51 | } 52 | }, 53 | "jest": { 54 | "transform": { 55 | ".(ts|tsx)": "ts-jest" 56 | }, 57 | "testEnvironment": "jsdom", 58 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 59 | "moduleFileExtensions": [ 60 | "ts", 61 | "tsx", 62 | "js" 63 | ], 64 | "coveragePathIgnorePatterns": [ 65 | "/node_modules/", 66 | "/test/" 67 | ], 68 | "coverageThreshold": { 69 | "global": { 70 | "branches": 90, 71 | "functions": 95, 72 | "lines": 95, 73 | "statements": 95 74 | } 75 | }, 76 | "collectCoverageFrom": [ 77 | "src/*.{js,ts}" 78 | ] 79 | }, 80 | "commitlint": { 81 | "extends": [ 82 | "@commitlint/config-conventional" 83 | ] 84 | }, 85 | "dependencies": { 86 | "@types/react": "^16.9.2", 87 | "immer": "^4.0.0" 88 | }, 89 | "devDependencies": { 90 | "@commitlint/cli": "^8.2.0", 91 | "@commitlint/config-conventional": "^8.2.0", 92 | "@testing-library/react-hooks": "^2.0.1", 93 | "@types/jest": "^24.0.18", 94 | "@types/node": "^12.7.5", 95 | "colors": "^1.3.2", 96 | "commitizen": "^4.0.3", 97 | "coveralls": "^3.0.6", 98 | "cross-env": "^5.2.1", 99 | "cz-conventional-changelog": "^3.0.2", 100 | "husky": "^3.0.5", 101 | "jest": "^24.9.0", 102 | "jest-config": "^24.9.0", 103 | "lint-staged": "^9.2.5", 104 | "lodash.camelcase": "^4.3.0", 105 | "prettier": "^1.18.2", 106 | "prompt": "^1.0.0", 107 | "react": "^16.9.0", 108 | "react-test-renderer": "^16.9.0", 109 | "replace-in-file": "^4.1.3", 110 | "rimraf": "^3.0.0", 111 | "semantic-release": "^15.13.24", 112 | "shelljs": "^0.8.3", 113 | "travis-deploy-once": "^5.0.9", 114 | "ts-jest": "^24.1.0", 115 | "ts-node": "^8.4.1", 116 | "tslint": "^5.20.0", 117 | "tslint-config-prettier": "^1.15.0", 118 | "tslint-config-standard": "^8.0.1", 119 | "typedoc": "^0.15.0", 120 | "typescript": "^3.6.3" 121 | }, 122 | "husky": { 123 | "hooks": { 124 | "pre-commit": "lint-staged" 125 | } 126 | }, 127 | "peerDependencies": { 128 | "react": "^16.8.0" 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `use-methods` [![Build Status](https://travis-ci.com/pelotom/use-methods.svg?branch=master)](https://travis-ci.com/pelotom/use-methods) 2 | 3 | 4 | 5 | ## Installation 6 | 7 | Pick your poison: 8 | - ``` 9 | npm install use-methods 10 | ``` 11 | - ``` 12 | yarn add use-methods 13 | ``` 14 | 15 | ## Usage 16 | 17 | This library exports a single [React Hook](https://reactjs.org/docs/hooks-intro.html), `useMethods`, which has all the power of [`useReducer`](https://reactjs.org/docs/hooks-reference.html#usereducer) but none of the ceremony that comes with actions and dispatchers. The basic API follows a similar pattern to `useReducer`: 18 | 19 | ```js 20 | const [state, callbacks] = useMethods(methods, initialState); 21 | ``` 22 | 23 | Instead of providing a single "reducer" function which is one giant switch statement over an action type, you provide a set of "methods" which modify the state or return new states. Likewise, what you get back in addition to the latest state is not a single `dispatch` function but a set of callbacks corresponding to your methods. 24 | 25 | A full example: 26 | 27 | ```js 28 | import useMethods from 'use-methods'; 29 | 30 | function Counter() { 31 | 32 | const [ 33 | { count }, // <- latest state 34 | { reset, increment, decrement }, // <- callbacks for modifying state 35 | ] = useMethods(methods, initialState); 36 | 37 | return ( 38 | <> 39 | Count: {count} 40 | 41 | 42 | 43 | 44 | ); 45 | } 46 | 47 | const initialState = { count: 0 }; 48 | 49 | const methods = state => ({ 50 | reset() { 51 | return initialState; 52 | }, 53 | increment() { 54 | state.count++; 55 | }, 56 | decrement() { 57 | state.count--; 58 | }, 59 | }); 60 | ``` 61 | 62 | *Note: the `methods` factory function must produce the same set of method names on every invocation.* 63 | 64 | ### Comparison to `useReducer` 65 | 66 | [Here's a more complex example](https://codesandbox.io/s/2109324q3r) involving a list of counters, implemented using `useReducer` and `useMethods` respectively: 67 | 68 | ![useReducer vs useMethods comparison](https://i.imgur.com/CayVD72.png) 69 | 70 | _Which of these would you rather write?_ 71 | 72 | ## Immutability 73 | 74 | `use-methods` is built on [`immer`](https://github.com/mweststrate/immer), which allows you to write your methods in an imperative, mutating style, even though the actual state managed behind the scenes is immutable. You can also return entirely new states from your methods where it's more convenient to do so (as in the `reset` example above). 75 | 76 | If you would like to use the [patches](https://github.com/immerjs/immer#patches) functionality from immer, 77 | you can pass an object to `useMethods` that contains the `methods` property and a `patchListener` 78 | property. The callback will be fed the patches applied to the state. For example: 79 | 80 | ```ts 81 | const patchList: Patch[] = []; 82 | const inverseList: Patch[] = []; 83 | 84 | const methodsObject = { 85 | methods: (state: State) => ({ 86 | increment() { 87 | state.count++; 88 | }, 89 | decrement() { 90 | state.count--; 91 | } 92 | }), 93 | patchListener: (patches: Patch[], inversePatches: Patch[]) => { 94 | patchList.push(...patches); 95 | inverseList.push(...inversePatches); 96 | }, 97 | }; 98 | 99 | // ... and in the component 100 | const [state, { increment, decrement }] = useMethods(methodsObject, initialState); 101 | ``` 102 | 103 | ## Memoization 104 | 105 | Like the `dispatch` method returned from `useReducer`, the callbacks returned from `useMethods` aren't recreated on each render, so they will not be the cause of needless re-rendering if passed as bare props to `React.memo`ized subcomponents. Save your `useCallback`s for functions that don't map exactly to an existing callback! In fact, the entire `callbacks` object (as in `[state, callbacks]`) is memoized, so you can use this to your deps array as well: 106 | 107 | ```ts 108 | const [state, callbacks] = useMethods(methods, initialState); 109 | 110 | // can pass to event handlers props, useEffect, etc: 111 | const MyStableCallback = useCallback((x: number) => { 112 | callbacks.someMethod('foo', x); 113 | }, [callbacks]); 114 | 115 | // which is equivalent to: 116 | const MyOtherStableCallback = useCallback((x: number) => { 117 | callbacks.someMethod('foo', x); 118 | }, [callbacks.someMethod]); 119 | ``` 120 | 121 | ## Types 122 | 123 | This library is built in TypeScript, and for TypeScript users it offers an additional benefit: one no longer needs to declare action types. The example above, if we were to write it in TypeScript with `useReducer`, would require the declaration of an `Action` type: 124 | 125 | ```ts 126 | type Action = 127 | | { type: 'reset' } 128 | | { type: 'increment' } 129 | | { type: 'decrement' }; 130 | ``` 131 | 132 | With `useMethods` the "actions" are implicitly derived from your methods, so you don't need to maintain this extra type artifact. 133 | 134 | If you need to obtain the type of the resulting state + callbacks object that will come back from `useMethods`, use the `StateAndCallbacksFor` operator, e.g.: 135 | 136 | ```ts 137 | const MyContext = React.createContext | null>(null); 138 | ``` 139 | -------------------------------------------------------------------------------- /test/index.test.tsx: -------------------------------------------------------------------------------- 1 | import { HookResult, renderHook, act } from '@testing-library/react-hooks'; 2 | import { Patch } from 'immer'; 3 | import useMethods from '../src'; 4 | import useTodos, { Todos } from './useTodos'; 5 | 6 | describe('todos example', () => { 7 | let $: HookResult; 8 | 9 | afterEach(() => { 10 | // tests that methods are not recreated on each render 11 | expect($.current.methodChanges.current).toBeLessThanOrEqual(0); 12 | }); 13 | 14 | describe('with no todos initially', () => { 15 | beforeEach(() => { 16 | $ = renderHook(useTodos).result; 17 | }); 18 | 19 | it('is empty initially', () => { 20 | expect($.current.todos).toHaveLength(0); 21 | }); 22 | 23 | describe('adding a todo', () => { 24 | it("doesn't work if input is empty", () => { 25 | $.current.addTodo(''); 26 | expect($.current.todos).toHaveLength(0); 27 | }); 28 | 29 | it('adds an incomplete todo with the input text', () => { 30 | const todoText = 'climb mt everest'; 31 | act(() => $.current.addTodo(todoText)); 32 | const { todos } = $.current; 33 | expect(todos).toHaveLength(1); 34 | const [todo] = todos; 35 | expect(todo.text).toBe(todoText); 36 | expect(todo.completed).toBe(false); 37 | }); 38 | }); 39 | }); 40 | 41 | describe('with a single todo initially', () => { 42 | beforeEach(() => { 43 | $ = renderHook(useTodos, { 44 | initialProps: [ 45 | { 46 | id: 0, 47 | text: 'hello world', 48 | completed: false, 49 | }, 50 | ], 51 | }).result; 52 | }); 53 | 54 | it('can toggle completeness', () => { 55 | const { id } = getTodo(); 56 | expect(getTodo().completed).toBe(false); 57 | act(() => $.current.toggleTodo(id)); 58 | expect(getTodo().completed).toBe(true); 59 | act(() => $.current.toggleTodo(id)); 60 | expect(getTodo().completed).toBe(false); 61 | 62 | function getTodo() { 63 | const { todos } = $.current; 64 | expect(todos).toHaveLength(1); 65 | return todos[0]; 66 | } 67 | }); 68 | 69 | it('can change filter', () => { 70 | act(() => $.current.setFilter('completed')); 71 | expect($.current.todos).toHaveLength(0); 72 | act(() => $.current.setFilter('active')); 73 | expect($.current.todos).toHaveLength(1); 74 | act(() => $.current.toggleTodo($.current.todos[0].id)); 75 | expect($.current.todos).toHaveLength(0); 76 | act(() => $.current.setFilter('completed')); 77 | expect($.current.todos).toHaveLength(1); 78 | act(() => $.current.setFilter('all')); 79 | expect($.current.todos).toHaveLength(1); 80 | }); 81 | }); 82 | }); 83 | 84 | it('avoids invoking methods more than necessary', () => { 85 | let invocations = 0; 86 | 87 | interface State { 88 | count: number; 89 | } 90 | 91 | const initialState: State = { count: 0 }; 92 | 93 | const methods = (state: State) => ({ 94 | increment() { 95 | invocations++; 96 | state.count++; 97 | }, 98 | }); 99 | 100 | const { result } = renderHook(() => useMethods(methods, initialState)[1]); 101 | 102 | expect(invocations).toBe(0); 103 | 104 | act(result.current.increment); 105 | 106 | expect(invocations).toBe(1); 107 | 108 | act(result.current.increment); 109 | 110 | expect(invocations).toBe(2); 111 | }); 112 | 113 | it('allows lazy initialization', () => { 114 | // Adapted from https://reactjs.org/docs/hooks-reference.html#lazy-initialization 115 | 116 | interface State { 117 | count: number; 118 | } 119 | 120 | const init = (count: number): State => ({ count }); 121 | 122 | let invocations = 0; 123 | const methods = (state: State) => { 124 | invocations++; 125 | return { 126 | increment() { 127 | state.count++; 128 | }, 129 | decrement() { 130 | state.count--; 131 | }, 132 | reset(newCount: number) { 133 | return init(newCount); 134 | }, 135 | }; 136 | }; 137 | 138 | function useCounter(initialCount: number) { 139 | const [state, { reset, ...callbacks }] = useMethods(methods, initialCount, init); 140 | return { ...state, ...callbacks, reset: () => reset(initialCount) }; 141 | } 142 | const { result: $, rerender } = renderHook(useCounter, { initialProps: 0 }); 143 | 144 | expect($.current.count); 145 | 146 | const expectCount = (count: number) => expect($.current.count).toBe(count); 147 | 148 | expect(invocations).toBe(1); 149 | expectCount(0); 150 | 151 | act($.current.increment); 152 | 153 | expect(invocations).toBe(2); 154 | expectCount(1); 155 | 156 | act($.current.increment); 157 | 158 | expect(invocations).toBe(3); 159 | expectCount(2); 160 | 161 | act($.current.reset); 162 | 163 | expect(invocations).toBe(4); 164 | expectCount(0); 165 | 166 | act($.current.decrement); 167 | 168 | expect(invocations).toBe(5); 169 | expectCount(-1); 170 | 171 | rerender(3); 172 | 173 | expect(invocations).toBe(5); 174 | expectCount(-1); 175 | 176 | act($.current.reset); 177 | 178 | expect(invocations).toBe(6); 179 | expectCount(3); 180 | }); 181 | 182 | it('will provide patches', () => { 183 | interface State { 184 | count: number; 185 | } 186 | 187 | const initialState: State = { 188 | count: 0, 189 | }; 190 | 191 | const patchList: any[] = []; 192 | const inverseList: any[] = []; 193 | 194 | const methodsObject = { 195 | methods: (state: State) => ({ 196 | increment() { 197 | state.count++; 198 | }, 199 | decrement() { 200 | state.count--; 201 | }, 202 | }), 203 | patchListener: (patches: Patch[], inversePatches: Patch[]) => { 204 | patchList.push(...patches); 205 | inverseList.push(...inversePatches); 206 | }, 207 | }; 208 | 209 | function useCounter() { 210 | const [state, callbacks] = useMethods(methodsObject, initialState); 211 | return { ...state, ...callbacks }; 212 | } 213 | const { result: $, rerender } = renderHook(useCounter); 214 | 215 | expect(patchList).toEqual([]); 216 | expect(inverseList).toEqual([]); 217 | 218 | act($.current.increment); 219 | expect(patchList).toEqual([{ op: 'replace', path: ['count'], value: 1 }]); 220 | expect(inverseList).toEqual([{ op: 'replace', path: ['count'], value: 0 }]); 221 | 222 | act($.current.increment); 223 | act($.current.decrement); 224 | expect(patchList).toEqual([ 225 | { op: 'replace', path: ['count'], value: 1 }, 226 | { op: 'replace', path: ['count'], value: 2 }, 227 | { op: 'replace', path: ['count'], value: 1 }, 228 | ]); 229 | expect(inverseList).toEqual([ 230 | { op: 'replace', path: ['count'], value: 0 }, 231 | { op: 'replace', path: ['count'], value: 1 }, 232 | { op: 'replace', path: ['count'], value: 2 }, 233 | ]); 234 | }); 235 | --------------------------------------------------------------------------------