Skip to content

usePromise

Hook to resolve promise with Suspense support. The component that uses it, it need to be wrapped with Suspense component. This hook can be used in conditional blocks.

Demo

INFO

The Delayed component uses usePromise hook to call a promise that resolves with an array of number or reject: if promise has been resolved, array number is rendered with a button to invalidate result, otherwise an alert is invocked. Delayed component is returned from UsePromise component.

Loading demo…
Show source code
tsx
import { Suspense, useCallback } from "react"
import { ErrorBoundary, usePromise } from "../../../..";

const Delayed = () => {
	const [data, invalidate] = usePromise(
		async () => {
			return await new Promise<number[]>((res, rej) => {
				console.log("called");
				setTimeout(() => {
					Math.random() > 0.5
						? res([1, 2, 3, 4, 5])
						: rej("Error throwed by promise");
				}, 4000);
			});
		},
		[],
		{
			cache: 25, //25 seconds
			cleanOnError: true,
			identifier: "ss",
			invalidateManually: true
		}
	);

	return <>
		<button onClick={invalidate}>Invalidate</button>
		<pre>{JSON.stringify(data)}</pre>
	</>;
}

export const UsePromise = () => {
	const fallback = useCallback<(error: Error, info: React.ErrorInfo, retry: () => void) => React.ReactNode>((_, __, retry) => {
		return <button onClick={retry}>Retry</button>
	}, []);

	return <ErrorBoundary fallback={fallback}>
		<Suspense fallback="loading...">
			<Delayed />
		</Suspense>
	</ErrorBoundary>
}

Types

UsePromiseProps

  • @template T - The resolved value type of the promise returned by promise.

Parameters accepted by usePromise.

PropertyTypeRequiredDescription
promise() => Promise<T>A zero-argument factory function that returns the Promise to resolve. Invoked on the first render and again whenever deps changes or the cache is invalidated. The component suspends while the promise is pending, and re-renders with the resolved value once it fulfills.
depsDependencyListA React dependency array (same semantics as useEffect). When any dependency changes, the cached result is considered stale and promise is re-invoked on the next render.
optionsUsePromiseOptionsOptional configuration that controls caching, error handling, and invalidation behaviour.

UsePromiseOptions

Options accepted by {@link usePromise}.

PropertyTypeRequiredDescription
cache"unmount" \| numberControls how long the resolved result is retained in the module-level cache: - "unmount" — The cache entry is deleted when the component unmounts, forcing a fresh fetch on the next mount. - number — A time-to-live in seconds. The entry expires that many seconds after the promise resolves and is re-fetched on the next render. - undefined (default) — The entry persists indefinitely for the lifetime of the module.
cleanOnErrorbooleanWhen true, a rejected promise automatically removes its cache entry after a short delay (~20 ms), allowing the factory to be retried on the next render instead of permanently surfacing the error to the nearest &lt;ErrorBoundary&gt;. Defaults to false.
identifierstringAn explicit string key used to identify this promise in the module-level cache. - When provided, this value is used as the cache key instead of the serialised promise.toString() representation, which may be unreliable after minification. - Providing a stable identifier is strongly recommended in production builds.
invalidateManuallybooleanControls whether the hook exposes a manual invalidation callback: - true — The hook returns [T, () =&gt; void]: the resolved value paired with an invalidate function that clears the cache entry and triggers a re-render, causing the factory to be re-invoked. - false | undefined (default) — The hook returns T directly, with no invalidation handle exposed.

UsePromiseResultWithInvalidate

  • @template T - The resolved value type of the promise.

Return value of usePromise when invalidateManually is true.

IndexTypeDescription
[0]TThe resolved value of the promise. Only accessible after the promise fulfills; the component suspends while pending and throws for &lt;ErrorBoundary&gt; on rejection.
[1]() => voidA stable callback that clears the cache entry for this promise and triggers a re-render, causing the factory to be re-invoked on the next render cycle. Useful for manual cache invalidation after a mutation or user action.

Released under the MIT License.