Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Last active July 31, 2022 17:57
Show Gist options
  • Save dr-skot/5482ee8b9846ab726c434680e6b40a44 to your computer and use it in GitHub Desktop.
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.
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