Skip to main content

Overlays + Async Data (React Query)

Opening a floating overlay (a Sheet, a Dialog, or an AlertDialog) is a navigation: the user has already committed to seeing more context by clicking the trigger. When the overlay's body needs remote data, fetching before opening turns a 404 or 500 into a silent drop back to the parent view, and a spinner on the trigger leaves the click feeling unregistered. This recipe mounts the shell immediately and resolves data inside it, so every click produces forward motion and every error stays in the place the user navigated to.

The pattern is identical across all three overlays: only the shell changes. The query hook, the body-state components, and the retry policy below are shared verbatim; the demo lets you host them in any of the three shells.

important

Don't copy this UI verbatim. This recipe teaches how to reason about asynchronous server state (mount the shell on the click, branch only the body, encode the retry policy, gate actions on success) so the overlay paints immediately and perceived loading time stays low. The user-details layout, copy, and demo controls are deliberately plain stand-ins (the dialog and alert-dialog bodies in particular are not layouts you'd ship as-is); swap them for your product's real content and visual design, and keep the state structure.

Try it in the live demo, directly above the code that renders it.

Why open the overlay first?

  • The open should feel instant, especially on slow networks. The user already committed to the navigation by clicking the trigger. Waiting for the request to resolve before opening means dead air at the parent view, and the wait scales with request latency: long-running endpoints or slow connections turn into seconds where users can't tell whether the click registered. Mounting the shell immediately decouples click feedback from request time.
  • No flashing across the open → load → close → reopen cycle. Within a single open, only the overlay's Body region branches between pending, success, and error, so header, close, and footer stay mounted and layout shift is contained to one region. Across opens, TanStack Query's cache lets a re-trigger after a successful fetch skip the pending state entirely; fetch-then-open does the opposite, re-running the request on every trigger and flashing the chrome in only after each fetch resolves.
  • Errors stay where the user intended to be. An inline error inside the overlay preserves the navigation and keeps recovery actions in reach. Closing on error forces a re-trigger and re-orientation from the parent view.
  • Actions gate on data, not hope. The footer's primary action ("Save changes" in a sheet or dialog, the destructive confirm in an alert dialog) stays disabled until the query succeeds. This matters most for AlertDialog: confirming a destructive action against a record that failed to load is never safe.
  • Retry is a product decision, not a default. Transient 500 responses are worth another attempt; a definitive 404 is not. The query hook owns that policy so the view stays free of conditional retry logic and the intent stays reviewable in one place.

What this covers

CaseDemo behavior
Happy pathWaits 1.5 seconds, then renders a loaded user profile.
404 errorWaits 1.5 seconds once, then renders a not-found empty state.
500 errorWaits 1.5 seconds per request, retries twice, then renders a service empty state.

The demo's segmented control picks which shell hosts the async body; the same three scenarios run identically in a Sheet, a Dialog, and an AlertDialog.

The route is also available as plain markdown at /recipes/overlay-async.md, so humans and LLM tools can fetch the same recipe without scraping the rendered page.

Anatomy

Parent selection state└── Overlay shell: Sheet | Dialog | AlertDialog (mounted immediately)    └── useUserQuery({ userId, scenario })        ├── Header             stable        ├── Body               pending | success | error   ← the only region that branches        └── Footer             stable; gate actions on success

Implementation

The "Why" section above is the user-perceived case for the pattern. These rules are how to wire it up so the code stays consistent with that intent.

  1. Mount the overlay on the click event. Set selection state synchronously in the handler; never gate it on a fetch result.
  2. Branch only the body on query state. query.isPending, query.isError, and query.isSuccess belong inside the overlay's Body region. Header, close button, and footer stay outside the conditional.
  3. Factor the query into a hook. useUserQuery owns fetching, retry, stale-time, and cancellation. The components that render query results (the shells, UserDetailsBody) consume a UseQueryResult and never reach into TanStack Query directly. The cache-observability bits in UserOverlayDemo (the useQueryClient subscription and removeQueries reset) are demo-only; production overlays shouldn't touch the cache.
  4. Encode the retry policy in useQuery. Return false from retry for terminal errors like 404. Return a bounded failureCount check for transient ones like 500.
  5. Match the retry UI to the retry policy. Show a retry button on recoverable errors. Omit it on terminal ones: retrying a definitive not-found adds latency without recovery.

Complete recipe

The worked example below uses Sheet as the shell; the next section shows the Dialog and AlertDialog shells consuming the exact same hook and body components. Copy the UI recipe into a client component that already has a QueryClientProvider mounted near the app root. The demo-only mock API is shown in the appendix below; in production, replace that import with your real API client and error type.

What transfers is the structure: the synchronous mount, the single branching region, the hook-owned retry policy, and the success-gated actions. What doesn't is the markup inside each state: UserDetails, the skeleton shapes, and the header/footer copy are demo content standing in for your real UI.

Swapping the shell

Everything above the shell (useUserQuery, UserDetailsBody, the loading/error/success components, the retry policy) is overlay-agnostic. To host the same async body in a different overlay, swap only the shell component. The live demo at the top of this page renders all three shells from the same parent selection state behind a segmented control.

Dialog

The Dialog shell is a one-for-one structural swap with Sheet: header and footer stay mounted, only Dialog.Body branches, and the primary action gates on query.isSuccess.

import { Button } from "@ngrok/mantle/button";import { Dialog } from "@ngrok/mantle/dialog"; /** Renders immediately, then swaps the dialog body from pending to success or error. */export function UserDialog({ onClose, scenario, userId }: UserOverlayProps) {	const query = useUserQuery({ scenario, userId }); 	return (		<Dialog.Root			open			onOpenChange={(nextOpen) => {				if (!nextOpen) {					onClose();				}			}}		>			<Dialog.Content preferredWidth="max-w-xl">				{/* Dialog.Header is a single flex row: Title + CloseIconButton only.						The description lives at the top of the Body (Radix wires						aria-describedby from anywhere inside Content). */}				<Dialog.Header>					<Dialog.Title>User details</Dialog.Title>					<Dialog.CloseIconButton />				</Dialog.Header>				<Dialog.Body className="space-y-4">					<Dialog.Description>						Loading <span className="font-mono">{userId}</span> through the{" "}						{scenarioLabels[scenario]} case.					</Dialog.Description>					<UserDetailsBody query={query} />				</Dialog.Body>				<Dialog.Footer>					<Dialog.Close asChild>						<Button type="button" appearance="outlined" intent="neutral">							Close						</Button>					</Dialog.Close>					<Button type="button" appearance="filled" intent="neutral" disabled={!query.isSuccess}>						Save changes					</Button>				</Dialog.Footer>			</Dialog.Content>		</Dialog.Root>	);}

AlertDialog

An AlertDialog confirms a consequential (usually destructive) action, which sharpens the pattern's stakes: the record the user is about to act on is exactly the thing being fetched. Two rules are non-negotiable here:

  • The destructive Action stays disabled until the query succeeds. Confirming against a record that hasn't loaded (or definitively doesn't exist) is never safe. On a 404, the disabled action plus the inline not-found state is the correct terminal UI.
  • Errors never auto-close the confirmation. The user chose to act; an inline error with a retry (for transient failures) keeps them in that intent instead of silently dropping it.
import { AlertDialog } from "@ngrok/mantle/alert-dialog"; /** * Renders immediately and loads the record the user is about to act on. The * destructive action stays disabled until the data resolves. */export function UserAlertDialog({ onClose, scenario, userId }: UserOverlayProps) {	const query = useUserQuery({ scenario, userId }); 	return (		<AlertDialog.Root			intent="danger"			open			onOpenChange={(nextOpen) => {				if (!nextOpen) {					onClose();				}			}}		>			<AlertDialog.Content preferredWidth="max-w-xl">				<AlertDialog.Icon />				<AlertDialog.Body>					<AlertDialog.Header>						<AlertDialog.Title>Remove this user?</AlertDialog.Title>						<AlertDialog.Description>							Review{" "}							<span translate="no" className="font-mono">								{userId}							</span>{" "}							before removing them (loaded through the {scenarioLabels[scenario]} case).						</AlertDialog.Description>					</AlertDialog.Header>					<div className="mt-4">						<UserDetailsBody query={query} />					</div>					<AlertDialog.Footer>						<AlertDialog.Cancel type="button">Cancel</AlertDialog.Cancel>						<AlertDialog.Action type="button" disabled={!query.isSuccess}>							Remove user						</AlertDialog.Action>					</AlertDialog.Footer>				</AlertDialog.Body>			</AlertDialog.Content>		</AlertDialog.Root>	);}

Mock API appendix

The code above imports a mock API module so the overlays can demonstrate happy, 404, and 500 states without a backend. In production, replace this file with your real API client and preserve the same query behavior: accept signal, throw typed errors, and let the UI decide which errors are retryable.

const SIMULATED_USER_API_LATENCY_MS = 1_500; /** Scenario names used by the docs demo controls. */export type UserRequestScenario = "success" | "not-found" | "server-error"; /** The typed user record returned by the demo API. */export type User = {	/** Stable user identifier from the backend. */	id: string;	/** Display name shown in the overlay header content. */	name: string;	/** Primary email address for the account. */	email: string;	/** Role within the current workspace. */	role: string;	/** Workspace name used to make the example feel like app data. */	workspace: string;	/** Billing plan attached to the workspace. */	plan: string;	/** ISO date string for when the user joined. */	joinedAt: string;	/** Human-readable recent activity summary. */	lastActiveAt: string;}; /** The HTTP status codes intentionally simulated by the demo. */type UserRequestErrorStatus = 404 | 500; /** Options for constructing a typed demo request error. */type UserRequestErrorOptions = {	/** HTTP status returned by the simulated endpoint. */	status: UserRequestErrorStatus;	/** User-facing or operator-facing error message. */	message: string;	/** Request identifier included in the inline error UI. */	requestId: string;}; /** Error shape used when the simulated endpoint returns a non-2xx response. */export class UserRequestError extends Error {	/** HTTP status returned by the simulated endpoint. */	readonly status: UserRequestErrorStatus;	/** Request identifier included in the inline error UI. */	readonly requestId: string; 	/** Creates a typed request error that preserves HTTP metadata. */	constructor({ message, requestId, status }: UserRequestErrorOptions) {		super(message);		this.name = "UserRequestError";		this.requestId = requestId;		this.status = status;	}} /** Error used when TanStack Query aborts a request after the overlay unmounts. */export class RequestCancelledError extends Error {	/** Creates a cancellation error that the retry policy can ignore. */	constructor() {		super("The user details request was cancelled.");		this.name = "RequestCancelledError";	}} /** Options for delaying the simulated API response. */type WaitForDemoApiOptions = {	/** Delay duration in milliseconds. */	durationMs: number;	/** Abort signal passed by TanStack Query. */	signal?: AbortSignal;}; /** Waits before resolving so the overlay can show the pending state. */function waitForDemoApi({ durationMs, signal }: WaitForDemoApiOptions): Promise<void> {	return new Promise((resolve, reject) => {		if (signal?.aborted) {			reject(new RequestCancelledError());			return;		} 		const timeoutId = setTimeout(() => {			signal?.removeEventListener("abort", handleAbort);			resolve();		}, durationMs); 		/** Cancels the simulated API delay when the query unmounts. */		function handleAbort() {			clearTimeout(timeoutId);			signal?.removeEventListener("abort", handleAbort);			reject(new RequestCancelledError());		} 		signal?.addEventListener("abort", handleAbort, { once: true });	});} /** Options accepted by the simulated user fetcher. */type FetchUserOptions = {	/** User identifier requested by the overlay. */	userId: string;	/** Demo scenario selected by the user. */	scenario: UserRequestScenario;	/** Abort signal passed by TanStack Query. */	signal?: AbortSignal;}; /** Simulates a production API client with latency, typed data, and HTTP errors. */export async function fetchUser({ scenario, signal, userId }: FetchUserOptions): Promise<User> {	await waitForDemoApi({ durationMs: SIMULATED_USER_API_LATENCY_MS, signal }); 	if (scenario === "not-found") {		throw new UserRequestError({			status: 404,			message: `No user exists for ${userId}.`,			requestId: createDemoRequestId({ status: 404, userId }),		});	} 	if (scenario === "server-error") {		throw new UserRequestError({			status: 500,			message: "The user service failed before returning profile data.",			requestId: createDemoRequestId({ status: 500, userId }),		});	} 	return {		id: userId,		name: "Ada Lovelace",		email: "ada.lovelace@example.com",		role: "Founding Engineer",		workspace: "Analytical Engines",		plan: "Enterprise",		joinedAt: "1843-07-08",		lastActiveAt: "2 minutes ago",	};} /** Options for creating a deterministic request id in the demo. */type CreateDemoRequestIdOptions = {	/** HTTP status returned by the simulated endpoint. */	status: UserRequestErrorStatus;	/** User identifier requested by the overlay. */	userId: string;}; /** Creates a stable request id so the error UI looks like real production output. */function createDemoRequestId({ status, userId }: CreateDemoRequestIdOptions): string {	return `req_${status}_${userId.replace(/[^a-z0-9]/gi, "").slice(-8)}`;}

Production notes

  • Keep each overlay shell in one component and keep API details behind fetchUser or your app's equivalent data client. The shell is the only overlay-specific code; everything else is shared.
  • Use the signal argument from TanStack Query's queryFn when your API client supports cancellation.
  • Tune retry by status code. This demo does not retry 404 because the server already answered definitively. Retry not-found responses only when eventual consistency is expected.
  • Gate footer actions on query.isSuccess. For AlertDialog specifically, never enable the destructive Action while the query is pending or errored: the confirmation is only meaningful against loaded data.
  • Let staleTime and gcTime govern cache lifetime; the overlay does not need to manually evict on close. The demo's "Clear cache" button only exists to make the cache state observable in docs; production overlays typically don't surface a manual reset.
  • Prefer explicit query state branches here over useSuspenseQuery. Suspense works, but error recovery requires an additional reset boundary and is harder to copy into route-controlled overlays.