Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active April 28, 2022 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/61fd15fd4d7981da8594c05f6da0be68 to your computer and use it in GitHub Desktop.
Save tvler/61fd15fd4d7981da8594c05f6da0be68 to your computer and use it in GitHub Desktop.
function useGetterState<T>(value: T) {
const [state, setState] = React.useState<T>(value)
const stateRef = React.useRef<T>(state)
React.useEffect(() => {
stateRef.current = state
}, [state])
const getter = React.useCallback(function (newValue?: React.SetStateAction<T>): T {
// use arguments.length because it's the only way to
// distinuish between getter() and getter(undefined)
if (arguments.length !== 0) {
setState(newValue!)
}
return stateRef.current
}, [])
return getter
}
const Component = () => {
const count = useGetterState(0)
const inc = React.useCallback(() => {
count((prev) => prev + 1)
}, [count])
React.useEffect(() => {
window.addEventListener('click', () => {
console.log(count())
})
}, [count])
return <button onClick={inc}>{count()}</button>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment