Last active
April 28, 2022 21:54
-
-
Save tvler/61fd15fd4d7981da8594c05f6da0be68 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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