Skip to content

Instantly share code, notes, and snippets.

@chinchang
Created May 21, 2024 07:07
Show Gist options
  • Save chinchang/7a9cda69a1e0d5b5b6672a3ab5bb3df4 to your computer and use it in GitHub Desktop.
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
/**
* 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