Last active
October 16, 2020 14:02
-
-
Save joepuzzo/8f03718159c98c1e4ac12d1a89caf89c 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
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