Skip to content

useParallelPromises

useParallelPromises – Executes multiple promises in parallel with Suspense.

Suspends the component until all promises are resolved, similar to Promise.all. If at least one fails, it propagates the error to the nearest ErrorBoundary.

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 } from "../../../..";
import { useParallelPromises } from "../../../../hooks/api-dom/useParallelPromises";

const Delayed = () => {
	const {result, invalidate} = useParallelPromises(
		[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);
			});
		}],
		[],
		{
			identifiers: ["ss"],
		}
	);

	return <>
		<button onClick={invalidate}>Invalidate</button>
		<pre>{JSON.stringify(result[0])}</pre>
	</>;
}

export const UseParallelPromise = () => {
	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

UseParallelPromisesOptions

Options accepted by useParallelPromises.

PropertyTypeRequiredDescription
cache"unmount" \| numberControls how long resolved results are 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 cache entry expires after the given number of seconds from the moment the promise resolves. Expired entries are deleted on the next render and the factory is re-invoked. - undefined (default) — The cache entry persists indefinitely across mounts and unmounts for the lifetime of the module.
identifiersstring[]An optional array of explicit string keys used to identify each factory in the cache, positionally aligned with the factories array. - When provided, identifiers[i] is used as the cache key for factories[i]. - When omitted, the cache key is derived by serialising the factory function via toString(), which may be unreliable after minification. Providing stable explicit identifiers is strongly recommended in production builds.

UseParallelPromisesProps

  • @template T - A readonly tuple of zero-argument async factory functions. Inferred automatically from the factories argument. The return types of each factory determine the corresponding entry in the result tuple.

Parameters accepted by useParallelPromises.

PropertyTypeRequiredDescription
factoriesTA readonly tuple of factory functions, each returning a Promise. All factories are invoked in parallel on the first render (or after invalidation). Each factory must be a zero-argument function: () =&gt; Promise&lt;any&gt;.
depsDependencyListA React dependency array (same semantics as useEffect). When any dependency changes, the cached result for the affected factory is considered stale and the promise is re-executed on the next render.
optionsUseParallelPromisesOptionsOptional configuration object. See {@link UseParallelPromisesOptions}.

UseParallelPromisesResult

  • @template T - The readonly tuple of factory functions passed to the hook. Used to infer the type of each entry in result.

Return value of useParallelPromises.

PropertyTypeRequiredDescription
result{ -readonly [K in keyof T]: Awaited<ReturnType<T[K]>> }A mutable tuple whose length and types mirror the factories input. result[K] is the awaited return type of factories[K]. This property is only accessible after all promises have fulfilled; if any promise is still pending the component suspends, and if any promise rejects the error is re-thrown for the nearest &lt;ErrorBoundary&gt; to catch.
invalidate() => voidA stable callback that clears all entries from the shared module-level cache and triggers a re-render, causing every factory to be re-invoked on the next render cycle. Useful for manual cache invalidation (e.g. after a mutation).

Released under the MIT License.