├── .github └── FUNDING.yml ├── tsconfig.json ├── package.json ├── index.ts ├── LICENSE ├── .gitignore └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: aminadav 4 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "lib": ["ES2015"], 5 | "outDir": "dist", 6 | "declaration": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-usestateref", 3 | "version": "1.0.8", 4 | "description": "useRef and UseState together!", 5 | "main": "dist/index.js", 6 | "files": [ 7 | "dist" 8 | ], 9 | "scripts": { 10 | "build": "npx rimraf dist && tsc", 11 | "deploy": "npm run build && npm version patch && git push && npm publish" 12 | }, 13 | "peerDependencies": { 14 | "react": ">16.0.0" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/Aminadav/react-useRefState.git" 19 | }, 20 | "keywords": [ 21 | "react", 22 | "hooks", 23 | "useState", 24 | "useRef" 25 | ], 26 | "author": "Aminadav Glickshtein", 27 | "license": "ISC", 28 | "bugs": { 29 | "url": "https://github.com/Aminadav/react-useRefState/issues" 30 | }, 31 | "homepage": "https://github.com/Aminadav/react-useRefState#readme", 32 | "devDependencies": { 33 | "@types/react": "^16.0.0", 34 | "typescript": "^4.0.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { useCallback, useRef, useState, SetStateAction, Dispatch } from "react"; 2 | 3 | const isFunction = (setStateAction: SetStateAction): setStateAction is (prevState: S) => S => 4 | typeof setStateAction === "function"; 5 | 6 | type ReadOnlyRefObject = { 7 | readonly current: T; 8 | }; 9 | 10 | type UseStateRef = { 11 | (initialState: S | (() => S)): [S, Dispatch>, ReadOnlyRefObject]; 12 | (): [S | undefined, Dispatch>, ReadOnlyRefObject]; 13 | }; 14 | 15 | const useStateRef: UseStateRef = (initialState?: S | (() => S)) => { 16 | const [state, setState] = useState(initialState); 17 | const ref = useRef(state); 18 | 19 | const dispatch: typeof setState = useCallback((setStateAction:any) => { 20 | ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction; 21 | 22 | setState(ref.current); 23 | }, []); 24 | 25 | return [state, dispatch, ref]; 26 | }; 27 | 28 | export = useStateRef; 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Aminadav Glickshtein 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 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-useStateRef 2 | 3 | 4 | 5 | useRef and UseState together! 6 | 7 | ## How to use 8 | 9 | ### Installation 10 | 11 | ```shell 12 | $ npm i react-usestateref 13 | ``` 14 | 15 | ```javascript 16 | import useState from 'react-usestateref' 17 | function MyComponent(){ 18 | var [state,setState,ref]=useState(0) 19 | // ref.current will always have the latest state 20 | } 21 | ``` 22 | 23 | As you can see it's 100% backward compatible. You can replace all your `useState` with this import and you will always have the latest state. 24 | 25 | ## Motivation: 26 | 27 | Many StackOverflow questions that people struggling to get the current state 28 | 29 | - https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately 30 | - https://stackoverflow.com/questions/60438537/usestate-shows-previous-value-always 31 | - https://stackoverflow.com/questions/57847594/react-hooks-accessing-up-to-date-state-from-within-a-callback 32 | - https://stackoverflow.com/questions/55874789/using-react-hooks-why-are-my-event-handlers-firing-with-the-incorrect-state 33 | 34 | In React when functions accessing the state they receive the state from the moment 35 | the function defined - not the current state. 36 | 37 | So if the state changed, your functions and effects my use older state. 38 | 39 | Using `useRef`, can solve it because it have always one value. But when you update the Ref it's not re-render. 40 | 41 | See the example code: 42 | 43 | ```js 44 | function MyComponent(){ 45 | var [counter,setCounter]=useState(0) 46 | function increment(){ 47 | setCounter(counter+1) 48 | alert(counter) // will show 0 since the state not updated yet. 49 | } 50 | useEffect(()=>{ 51 | alert(counter) // Whatever is the current state. It always alert 0 52 | return ()=>{ 53 | alert(counter) // On unmount it still alert 0, even if you called increment many times. 54 | } 55 | },[]) 56 | return ( 57 |
58 | Current number: {counter} 59 | 62 |
) 63 | } 64 | ``` 65 | 66 | To solve it I created a new hook `useStateRef` 67 | 68 | See it in action: 69 | 70 | ```js 71 | import useState from 'react-usestateref' // see this line 72 | function MyComponent(){ 73 | var [counter,setCounter,counterRef]=useState(0) 74 | function increment(){ 75 | setCounter(counter+1) 76 | alert(counterRef.current) // will show 1 77 | } 78 | useEffect(()=>{ 79 | alert(counterRef.current) // Always show the last value 80 | return ()=>{ 81 | alert(counterRef.current) // // Always show the last value 82 | } 83 | },[]) 84 | return ( 85 |
86 | Current number: {counter} 87 | 90 |
) 91 | } 92 | ``` 93 | 94 | It's fully support the `useState` API, so you can change your `useState` to `useStateRef` and it will not break your app. 95 | 96 | ## Contribution 97 | 98 | - Star & fork this project. 99 | - I'm open to your contribution. 100 | - Better documentation or whatever your like. Just open a PR 101 | 102 | ## Other innovations by cretors: 103 | 104 | - [Webpage Screenshot](https://chromewebstore.google.com/detail/webpage-screenshot-entire/akgpcdalpfphjmfifkmfbpdmgdmeeaeo) 105 | - [ערוץ מבניד](https://xn----2hcgfw2apl2a2a.boti.bot/) 106 | --------------------------------------------------------------------------------