Created
June 26, 2020 07:01
-
-
Save torian257x/70964f80cff4bb2f717fe8f22a7bd7f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const useStateWithRef = (initialState) => { | |
const [state, _setState] = React.useState(initialState); | |
const ref = React.useRef(state); | |
const setState = React.useCallback( | |
(newState) => { | |
if (typeof newState === 'function') { | |
_setState(prevState => { | |
const computedState = newState(prevState); | |
ref.current = computedState; | |
return computedState; | |
}); | |
} else { | |
ref.current = newState; | |
_setState(newState); | |
} | |
}, | |
[] | |
); | |
return [state, setState, ref]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
typescript