├── .gitignore ├── .prettierignore ├── .prettierrc ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── useMemo.test.ts └── useMemoValue.ts ├── tsconfig.json └── tsconfig.test.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log 3 | .rts2_cache_* 4 | dist 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .cache 3 | .github 4 | .rts2_cache_* 5 | dist 6 | package-lock.json 7 | .*ignore 8 | LICENSE 9 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": true, 3 | "semi": false, 4 | "trailingComma": "all", 5 | "proseWrap": "always", 6 | "arrowParens": "avoid", 7 | "overrides": [ 8 | { 9 | "files": "**/*.{md,json}", 10 | "options": { 11 | "useTabs": false 12 | } 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Discord 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `useMemoValue()` 2 | 3 | > Reuse the previous version of a value unless it has changed 4 | 5 | ## Install 6 | 7 | ```sh 8 | npm install --save-dev use-memo-value 9 | ``` 10 | 11 | ## Usage 12 | 13 | If you don't know all the members of an object, you may want to use a "shallow 14 | compare" to memoize the value so you can rely on React's referential equality 15 | (such as in `useEffect(..., deps)`). 16 | 17 | ```js 18 | import useMemoValue from "use-memo-value" 19 | 20 | function MyComponent(props) { 21 | let rawParams = getCurrentUrlQueryParams() // we don't know the shape of this object 22 | let memoizedParams = useMemoValue(rawParams) 23 | 24 | useEffect(() => { 25 | search(memoizedParams) 26 | }, [memoizedParams]) 27 | 28 | // ... 29 | } 30 | ``` 31 | 32 | > **Note:** If you know the shape of your object, you are likely better off not 33 | > using this library. 34 | 35 | If you need to customize how the values are compared, you can pass a comparator 36 | as a second argument: 37 | 38 | ```js 39 | let memoizedValue = useMemoValue(rawValue, (nextValue, previousValue) => { 40 | return Object.is(a, b) // or whatever 41 | }) 42 | ``` 43 | 44 | The comparator will not be called until there's a new value. 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-memo-value", 3 | "version": "1.0.1", 4 | "description": "Reuse the previous version of a value unless it has changed", 5 | "author": "Jamie Kyle ", 6 | "license": "MIT", 7 | "repository": "discord/use-memo-value", 8 | "keywords": [ 9 | "react", 10 | "hook", 11 | "use", 12 | "memo", 13 | "memoized", 14 | "value", 15 | "object", 16 | "array", 17 | "shallow", 18 | "equal", 19 | "shallowequal", 20 | "compare", 21 | "comparator", 22 | "comparison" 23 | ], 24 | "source": "src/useMemoValue.ts", 25 | "main": "dist/useMemoValue.js", 26 | "module": "dist/useMemoValue.module.js", 27 | "unpkg": "dist/useMemoValue.umd.js", 28 | "files": [ 29 | "dist" 30 | ], 31 | "scripts": { 32 | "format": "prettier --write '**'", 33 | "test": "TS_NODE_PROJECT=./tsconfig.test.json ava", 34 | "build": "rm -rf dist && microbundle --inline none --name useMemoValue", 35 | "prepublishOnly": "npm run -s build" 36 | }, 37 | "dependencies": { 38 | "shallowequal": "^0.1.0 || ^0.2.0 || ^1.0.0" 39 | }, 40 | "peerDependencies": { 41 | "react": "^16.8.0" 42 | }, 43 | "devDependencies": { 44 | "@testing-library/react-hooks": "^3.2.1", 45 | "@types/shallowequal": "^1.1.1", 46 | "ava": "^3.7.1", 47 | "husky": "^4.2.5", 48 | "lint-staged": "^10.1.6", 49 | "microbundle": "^0.11.0", 50 | "prettier": "^2.0.4", 51 | "react": "^16.13.1", 52 | "react-test-renderer": "^16.13.1", 53 | "ts-node": "^8.9.0", 54 | "typescript": "^3.8.3" 55 | }, 56 | "lint-staged": { 57 | "*": [ 58 | "prettier --write", 59 | "git add" 60 | ] 61 | }, 62 | "ava": { 63 | "extensions": [ 64 | "ts", 65 | "tsx" 66 | ], 67 | "require": [ 68 | "ts-node/register" 69 | ] 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/useMemo.test.ts: -------------------------------------------------------------------------------- 1 | import test from "ava" 2 | import { renderHook, act } from "@testing-library/react-hooks" 3 | import { useState } from "react" 4 | import useMemoValue from "./useMemoValue" 5 | 6 | test("basics", t => { 7 | let { result } = renderHook(() => { 8 | let [rawValue, setRawValue] = useState({ name: "starting value" }) 9 | let memoValue = useMemoValue(rawValue) 10 | return { rawValue, setRawValue, memoValue } 11 | }) 12 | 13 | // init 14 | t.is(result.current.rawValue, result.current.memoValue) 15 | 16 | // update to same value 17 | act(() => result.current.setRawValue({ name: "starting value" })) 18 | t.not(result.current.rawValue, result.current.memoValue) 19 | t.is(result.current.memoValue.name, "starting value") 20 | 21 | // update to new value 22 | act(() => result.current.setRawValue({ name: "changed value" })) 23 | t.is(result.current.rawValue, result.current.memoValue) 24 | t.is(result.current.memoValue.name, "changed value") 25 | }) 26 | 27 | test("comparator", t => { 28 | let fooComparatorCalled = 0 29 | let barComparatorCalled = 0 30 | 31 | let fooComparator = (a: any, b: any) => { 32 | fooComparatorCalled++ 33 | return a.foo === b.foo 34 | } 35 | 36 | let barComparator = (a: any, b: any) => { 37 | barComparatorCalled++ 38 | return a.bar === b.bar 39 | } 40 | 41 | let { result } = renderHook(() => { 42 | let [rawValue, setRawValue] = useState({ foo: 1, bar: 1 }) 43 | let [comparator, setComparator] = useState(() => fooComparator) 44 | let memoValue = useMemoValue(rawValue, comparator) 45 | return { rawValue, setRawValue, setComparator, memoValue } 46 | }) 47 | 48 | // init 49 | t.is(result.current.memoValue.foo, 1) 50 | t.is(result.current.memoValue.bar, 1) 51 | t.is(fooComparatorCalled, 0) 52 | t.is(barComparatorCalled, 0) 53 | 54 | // change something comparator cares about 55 | act(() => result.current.setRawValue({ foo: 2, bar: 2 })) 56 | t.is(result.current.memoValue.foo, 2) 57 | t.is(result.current.memoValue.bar, 2) 58 | t.is(fooComparatorCalled, 1) 59 | t.is(barComparatorCalled, 0) 60 | 61 | // change something comparator doesn't care about 62 | act(() => result.current.setRawValue({ foo: 2, bar: 3 })) 63 | t.is(result.current.memoValue.foo, 2) 64 | t.is(result.current.memoValue.bar, 2) 65 | t.is(fooComparatorCalled, 2) 66 | t.is(barComparatorCalled, 0) 67 | 68 | // switch comparators 69 | act(() => result.current.setComparator(() => barComparator)) 70 | t.is(result.current.memoValue.foo, 2) 71 | t.is(result.current.memoValue.bar, 3) 72 | t.is(fooComparatorCalled, 2) 73 | t.is(barComparatorCalled, 1) 74 | 75 | // change something comparator cares about 76 | act(() => result.current.setRawValue({ foo: 2, bar: 4 })) 77 | t.is(result.current.memoValue.foo, 2) 78 | t.is(result.current.memoValue.bar, 4) 79 | t.is(fooComparatorCalled, 2) 80 | t.is(barComparatorCalled, 2) 81 | 82 | // change something comparator doesn't care about 83 | act(() => result.current.setRawValue({ foo: 3, bar: 4 })) 84 | t.is(result.current.memoValue.foo, 2) 85 | t.is(result.current.memoValue.bar, 4) 86 | t.is(fooComparatorCalled, 2) 87 | t.is(barComparatorCalled, 3) 88 | }) 89 | -------------------------------------------------------------------------------- /src/useMemoValue.ts: -------------------------------------------------------------------------------- 1 | import { useRef, useEffect } from "react" 2 | import shallowEqual from "shallowequal" 3 | 4 | const FIRST_RUN = {} // an opaque value 5 | 6 | /** 7 | * A function to compare two values to determine if they can be considered equal. 8 | */ 9 | export type Comparator = (a: T, b: T) => boolean 10 | 11 | /** 12 | * Reuse the previous version of a value unless it has changed. 13 | * @param value The current value. 14 | * @param comparator An function to compare the current value to its previous value, defaults to "shallowEqual" 15 | */ 16 | export default function useMemoValue( 17 | value: T, 18 | comparator: Comparator = shallowEqual, 19 | ): T { 20 | let ref = useRef(FIRST_RUN as T) 21 | let nextValue = ref.current 22 | 23 | useEffect(() => { 24 | ref.current = nextValue 25 | }) 26 | 27 | if (ref.current === FIRST_RUN || !comparator(value, ref.current)) { 28 | nextValue = value 29 | } 30 | 31 | return nextValue 32 | } 33 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | // prettier-ignore 2 | { 3 | "exclude": ["**/*.test.*"], 4 | "compilerOptions": { 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "esnext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | // "outDir": "./", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["**/*.test.*"], 4 | "compilerOptions": { 5 | "module": "commonjs" 6 | } 7 | } 8 | --------------------------------------------------------------------------------