Skip to content

Instantly share code, notes, and snippets.

@jamsesso
Created April 4, 2021 16:48
Show Gist options
  • Save jamsesso/b857423e754e2378d43c9aaace6e205b to your computer and use it in GitHub Desktop.
Save jamsesso/b857423e754e2378d43c9aaace6e205b to your computer and use it in GitHub Desktop.
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