Created
April 4, 2021 16:48
-
-
Save jamsesso/b857423e754e2378d43c9aaace6e205b 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 {useRef, useState, useCallback, useEffect} from 'react'; | |
function useStateThen(initialValue) { | |
const p = useRef(null); | |
const [value, setValue] = useState(initialValue); | |
const wrappedSetValue = useCallback((...args) => { | |
return new Promise(resolve => { | |
p.current = resolve; | |
setValue(...args); | |
}); | |
}, [setValue]); | |
useEffect(() => { | |
if (p.current) { | |
p.current(value); | |
p.current = null; | |
} | |
}, [value]); | |
return [value, wrappedSetValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment