Created
May 21, 2024 07:07
-
-
Save chinchang/7a9cda69a1e0d5b5b6672a3ab5bb3df4 to your computer and use it in GitHub Desktop.
A custom wrapper hook for useState that return a promise on calling setValue
This file contains 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
/** | |
* A custom wrapper hook for useState that return a promise | |
* on calling setValue. | |
* Useful with APIs like document.startViewTransition | |
* | |
* Demo: https://codesandbox.io/p/sandbox/react-view-transition-list-3ycjj9 | |
* | |
*/ | |
import { useEffect, useRef, useState } from "react"; | |
export function usePromiseState(initialVal) { | |
const [val, setVal] = useState(initialVal); | |
const resolveRef = useRef(); | |
useEffect(() => { | |
if (resolveRef.current) { | |
resolveRef.current(); | |
} | |
}, [val]); | |
const setValue = (value) => { | |
setVal(value); | |
return new Promise((resolve) => { | |
resolveRef.current = resolve; | |
}); | |
}; | |
return [val, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment