Skip to content

Instantly share code, notes, and snippets.

@ogwurujohnson
Created January 8, 2021 06:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ogwurujohnson/7aa5955945395991b31e86138501e0da to your computer and use it in GitHub Desktop.
Save ogwurujohnson/7aa5955945395991b31e86138501e0da to your computer and use it in GitHub Desktop.
Await state changes, can be used as well to make a method call after state change
const useStateWithPromise = (initialState) => {
const [state, setState] = useState(initialState);
const resolverRef = useRef(null);
useEffect(() => {
if (resolverRef.current) {
resolverRef.current(state);
resolverRef.current = null;
}
/**
* Since a state update could be triggered with the exact same state again,
* it's not enough to specify state as the only dependency of this useEffect.
* That's why resolverRef.current is also a dependency, because it will guarantee,
* that handleSetState was called in previous render
*/
}, [resolverRef.current, state]);
const handleSetState = useCallback((stateAction) => {
setState(stateAction);
return new Promise(resolve => {
resolverRef.current = resolve;
});
}, [setState])
return [state, handleSetState];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment