Last active
July 31, 2022 17:57
-
-
Save dr-skot/5482ee8b9846ab726c434680e6b40a44 to your computer and use it in GitHub Desktop.
Sometimes you want both useRef's never-stale guarantee and useState's rerender-on-change functionality. This hook delivers a ref & a setter that triggers rerender on change.
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 useRefWithRerender<T>(initialState: T): [MutableRefObject<T>, (value: T) => void] { | |
const ref = useRef(initialState); | |
const [, setState] = useState(true); | |
const setter = useCallback((value: T) => { | |
if (ref.current === value) return; | |
ref.current = value; | |
setState((n) => !n); | |
}, []); | |
return [ref, setter]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment