Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created August 20, 2020 06:35
Show Gist options
  • Save andycarrell/2a7b02ef14e068bdf76f74c3f22f54bd to your computer and use it in GitHub Desktop.
Save andycarrell/2a7b02ef14e068bdf76f74c3f22f54bd to your computer and use it in GitHub Desktop.
function useRefGetAndSet(value) {
const ref = React.useRef(value);
const getRef = React.useCallback(() => ref.current, []);
const setRef = React.useCallback((newValue) => {
ref.current = newValue;
}, []);
// Optional: sync value every render
useLayoutEffect(() => {
setRef(value);
});
return [getRef, setRef];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment