Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Last active October 16, 2020 14:02
Show Gist options
  • Save joepuzzo/8f03718159c98c1e4ac12d1a89caf89c to your computer and use it in GitHub Desktop.
Save joepuzzo/8f03718159c98c1e4ac12d1a89caf89c to your computer and use it in GitHub Desktop.
import { useState, useRef, useEffect } from 'react';
// https://github.com/facebook/react/issues/14543
function useStateWithGetter(initial) {
const ref = useRef();
const mounted = useRef(true);
const [state, setState] = useState(initial);
ref.current = state;
const set = value => {
ref.current = value;
if (mounted.current) setState(value);
};
const get = () => {
return ref.current;
};
useEffect(() => {
return () => {
mounted.current = false;
};
}, []);
return [state, set, get];
}
export default useStateWithGetter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment