Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Created September 24, 2024 05:51
Show Gist options
  • Save Phryxia/2b605d237295b73f4ed9e92c474bad45 to your computer and use it in GitHub Desktop.
Save Phryxia/2b605d237295b73f4ed9e92c474bad45 to your computer and use it in GitHub Desktop.
Listen for promises and give the last promise value as react state
import { useLayoutEffect, useRef, useState } from 'react'
export function usePromise<T>(promise: Promise<T>) {
const [isLoading, setIsLoading] = useState(true)
const [value, setValue] = useState<T>()
const valueVersion = useRef(0)
useLayoutEffect(() => {
const valueOnClosure = ++valueVersion.current
promise.then(newValue => {
if (valueOnClosure < valueVersion.current) return
setValue(newValue)
setIsLoading(false)
})
setIsLoading(true)
}, [promise])
return { value, isLoading }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment