# Loading

Show that content or an action is on its way, with an indicator to fit the wait.

## Overview

Loading applies at three scales: a region that fetches data, an action that waits for a response, and a transaction that waits for a block. At each scale, keep the layout still, block duplicate requests, and end in a result or an error.

* **Shape Known (Skeleton):** The shape is known, such as a balance or a row value. Outline it with [Skeleton](/docs/components/skeleton).
* **Shape Unknown (Spinner):** Only the arrival is known, such as for search results. Center one named [Spinner](/docs/components/spinner) in the region.
* **Inside a Control (loading):** An action runs in place. Use a busy [Button](/docs/components/button), or [LoadingDots](/docs/components/loading-dots) inside a sentence.
* **Progress Known (Progress):** The work is countable, such as months exported or files uploaded. Show [Progress](/docs/components/progress).

## Structure

1. **Frame:** The page frame, headings, and navigation stay on screen. Only the loading parts change.
2. **Placeholder:** Each loading region holds a placeholder that matches its shape, if the shape is known.
3. **Content:** Each placeholder gives way to its content in place, without moving the content around it.
4. **Failure:** If a request fails, Couldn't load and a retry action replace the placeholder.

```tsx
import { Amount, Button, ListGroup, Skeleton, style, Surface } from '@tempoxyz/ds'
import { Refresh } from '@tempoxyz/ds/icons'
import { useEffect, useState } from 'react'

export const fill = true
const tokens = [
  ['USDC', '1000.00'],
  ['PathUSD', '250.00'],
] as const

export function Demo() {
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  // The first load shows skeletons. A refresh keeps the old values on screen.
  useEffect(() => {
    if (!loading) return
    const timer = setTimeout(() => setLoading(false), 1500)
    return () => clearTimeout(timer)
  }, [loading])

  useEffect(() => {
    if (!refreshing) return
    const timer = setTimeout(() => setRefreshing(false), 1000)
    return () => clearTimeout(timer)
  }, [refreshing])

  return (
    <div {...styles.page()}>
      <Surface {...styles.card()}>
        <Surface.Header>
          <Surface.Title>Balance</Surface.Title>
          <Button
            aria-label="Refresh balance"
            disabled={loading}
            loading={refreshing}
            onClick={() => setRefreshing(true)}
            shape="icon"
            size="small"
            variant="secondary"
          >
            <Refresh />
          </Button>
        </Surface.Header>
        <div {...styles.total()}>
          <Skeleton show={loading}>
            <Amount currency="USD" size="lg" value="1250.00" />
          </Skeleton>
        </div>
        <div {...styles.rows()}>
          <ListGroup.Root>
            {tokens.map(([symbol, value]) => (
              <ListGroup.Row key={symbol}>
                <ListGroup.Label>{symbol}</ListGroup.Label>
                <Skeleton show={loading}>
                  <Amount symbol={symbol} value={value} />
                </Skeleton>
              </ListGroup.Row>
            ))}
          </ListGroup.Root>
        </div>
      </Surface>
      <Button onClick={() => setLoading(true)} size="small" variant="tertiary">
        Replay first load
      </Button>
    </div>
  )
}

namespace styles {
  export const card = style({
    boxSizing: 'border-box',
    maxWidth: '24rem !custom',
    width: '100% !custom',
  })

  export const page = style({
    backgroundColor: 'background.primary',
    display: 'grid',
    gap: '12',
    justifyItems: 'center',
    padding: '16',
  })

  export const rows = style({ marginBlockStart: '16' })

  // A flex row lets the skeleton take the width of the amount instead of the card.
  export const total = style({ display: 'flex' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Patterns/BalanceSkeleton.tsx)

This reference layout uses [Skeleton](/docs/components/skeleton) for the total and for each token value in [ListGroup](/docs/components/list-group), so the token labels stay on screen. A refresh keeps the old values on screen.

## Timing

Time the indicator to the wait. An indicator that appears and vanishes within a moment reads as a flicker.

* **Show Nothing (Under 300ms):** Most responses land here. An indicator would only flash.
* **Delay the Indicator (300ms to 1s):** Delay the skeleton or spinner briefly. Once it appears, keep it for at least 500ms.
* **Name the Work (1 to 10s):** Show a skeleton or spinner, and name the work, such as "Confirming payment".
* **Measure or Explain (Over 10s):** If the work is measurable, show a labelled progress bar. Otherwise explain the wait, and let people leave.

Set `loading` on a pressed button immediately, whatever the wait.

## Skeleton

Wrap the real content in a [Skeleton](/docs/components/skeleton) and set `show={false}` on arrival, instead of swapping elements. The skeleton takes the exact size of the content.

**Do:** Shape skeletons like the content, so the layout holds still when it arrives.

```tsx
/**
 * Do example for "Loading" on the Loading page.
 * Shape skeletons like the content, so the layout holds still when it arrives.
 * @module
 */
import { Skeleton, style, Surface } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Surface size="medium" {...styles.card()}>
      <Skeleton style={{ height: 14, width: 64 }} />
      <Skeleton style={{ height: 32, width: 160 }} />
      <div {...styles.row()}>
        <Skeleton shape="circle" style={{ height: 32, width: 32 }} />
        <Skeleton style={{ flex: 1, height: 14 }} />
      </div>
      <div {...styles.row()}>
        <Skeleton shape="circle" style={{ height: 32, width: 32 }} />
        <Skeleton style={{ flex: 1, height: 14 }} />
      </div>
    </Surface>
  )
}

namespace styles {
  export const card = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '12',
    width: '100% !custom',
  })

  export const row = style({ alignItems: 'center', display: 'flex', gap: '12' })
}
```

**Don't:** Put a lone spinner in a region with a known layout.

```tsx
/**
 * Don't example for "Loading" on the Loading page.
 * Don't put a lone spinner in a region with a known layout.
 * @module
 */
import { Spinner, style, Surface } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Surface size="medium" {...styles.card()}>
      <Spinner aria-label="Loading balance" />
    </Surface>
  )
}

namespace styles {
  export const card = style({
    alignItems: 'center',
    display: 'flex',
    height: '10rem !custom',
    justifyContent: 'center',
    width: '100% !custom',
  })
}
```

### Keep Content On Screen While It Refreshes

Show skeletons on the first load only. During a refresh, keep content visible and show progress on the control that started it. On views that poll, such as a live dashboard, update values in place without an indicator.

**Do:** Keep the current balance visible and set `loading` on the refresh button.

```tsx
/**
 * Do example for "Keep Content On Screen While It Refreshes" on the Loading page.
 * Keep the current balance visible and set `loading` on the refresh button.
 * @module
 */
import { Amount, Button, style } from '@tempoxyz/ds'
import { Refresh } from '@tempoxyz/ds/icons'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.row()}>
      <div>
        <p {...styles.caption()}>Balance</p>
        <Amount currency="USD" size="md" value="1250.00" />
      </div>
      <Button loading size="small" variant="secondary">
        <Refresh />
        Refresh
      </Button>
    </div>
  )
}

namespace styles {
  export const caption = style({ color: 'content.secondary', margin: '0', typography: 'body.b3' })

  export const row = style({
    alignItems: 'center',
    columnGap: '12',
    display: 'flex',
    justifyContent: 'space-between',
    width: '100% !custom',
  })
}
```

**Don't:** Replace a visible balance with a skeleton on every refresh.

```tsx
/**
 * Don't example for "Keep Content On Screen While It Refreshes" on the Loading page.
 * Don't replace a visible balance with a skeleton on every refresh.
 * @module
 */
import { Amount, Button, Skeleton, style } from '@tempoxyz/ds'
import { Refresh } from '@tempoxyz/ds/icons'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.row()}>
      <div>
        <p {...styles.caption()}>Balance</p>
        <Skeleton>
          <Amount currency="USD" size="md" value="1250.00" />
        </Skeleton>
      </div>
      <Button size="small" variant="secondary">
        <Refresh />
        Refresh
      </Button>
    </div>
  )
}

namespace styles {
  export const caption = style({ color: 'content.secondary', margin: '0', typography: 'body.b3' })

  export const row = style({
    alignItems: 'center',
    columnGap: '12',
    display: 'flex',
    justifyContent: 'space-between',
    width: '100% !custom',
  })
}
```

## Pending Actions

Show the pending state on the pressed [Button](/docs/components/button) itself. Inside a line of text, such as a balance that refreshes beside its label, use [LoadingDots](/docs/components/loading-dots).

**Do:** Set `loading` on the button that started the action.

```tsx
<Button loading>Send payment</Button>
```

**Don't:** Leave the button active while a spinner shows elsewhere.

```tsx
<Inline gap="12">
  <Spinner aria-label="Sending" />
  <Button>Send payment</Button>
</Inline>
```

### Update Optimistically Only When You Can Undo It

Apply a change before the server confirms it only if the change is low-risk, easy to reverse, and almost always succeeds, such as renaming an API key or flipping a notification [Switch](/docs/components/switch).

* **Restore on Failure (Toast):** Restore the previous value and state the failure, such as Couldn't rename key.
* **Never for Onchain State:** Never update onchain state, such as balances, optimistically. Show the transaction as Pending.

### Show Pending Transactions

```tsx
import { Amount, Badge, Button, ListGroup, style, Surface, Toast } from '@tempoxyz/ds'
import { CheckCircle, Pending } from '@tempoxyz/ds/icons'
import { useRef, useState } from 'react'

export const fill = true
type Payment = { id: number; status: 'confirmed' | 'pending' }

function Status(props: { status: Payment['status'] }) {
  if (props.status === 'pending')
    return (
      <Badge>
        <Pending />
        Pending
      </Badge>
    )

  return (
    <Badge>
      <CheckCircle />
      Confirmed
    </Badge>
  )
}

function Activity() {
  const toast = Toast.useToast()
  const next = useRef(1)
  const [payments, setPayments] = useState<readonly Payment[]>([])
  const [submitting, setSubmitting] = useState(false)

  const confirmed = payments.filter((payment) => payment.status === 'confirmed').length
  const balance = (1250 - confirmed * 25).toFixed(2)

  return (
    <Surface {...styles.card()}>
      <Surface.Header>
        <Surface.Title>Activity</Surface.Title>
        <Button
          loading={submitting}
          onClick={() => {
            const id = next.current++
            setSubmitting(true)

            // The button stays busy only until the network accepts the transaction.
            setTimeout(() => {
              setSubmitting(false)
              setPayments((current) => [{ id, status: 'pending' }, ...current])
            }, 800)

            setTimeout(() => {
              setPayments((current) =>
                current.map((payment) =>
                  payment.id === id ? { ...payment, status: 'confirmed' as const } : payment,
                ),
              )
              toast.add({ intent: 'positive', title: 'Payment confirmed' })
            }, 3000)
          }}
          size="small"
        >
          Send 25 USDC
        </Button>
      </Surface.Header>
      <p {...styles.caption()}>Balance</p>
      <Amount currency="USD" size="md" value={balance} />
      <div {...styles.rows()}>
        <ListGroup.Root>
          {payments.map((payment) => (
            <ListGroup.Row key={payment.id}>
              <ListGroup.Info>
                <ListGroup.Title>Sent 25.00 USDC</ListGroup.Title>
                <ListGroup.Description>To 0x71C7…976F</ListGroup.Description>
              </ListGroup.Info>
              <Status status={payment.status} />
            </ListGroup.Row>
          ))}
          <ListGroup.Row>
            <ListGroup.Info>
              <ListGroup.Title>Received 120.00 USDC</ListGroup.Title>
              <ListGroup.Description>From 0x3C44…93BC</ListGroup.Description>
            </ListGroup.Info>
            <Status status="confirmed" />
          </ListGroup.Row>
        </ListGroup.Root>
      </div>
    </Surface>
  )
}

export function Demo() {
  return (
    <div {...styles.page()}>
      <Toast.Provider>
        <Activity />
        <Toast.Viewport />
      </Toast.Provider>
    </div>
  )
}

namespace styles {
  export const caption = style({ color: 'content.secondary', margin: '0', typography: 'body.b3' })

  export const card = style({
    boxSizing: 'border-box',
    maxWidth: '26rem !custom',
    width: '100% !custom',
  })

  export const page = style({
    backgroundColor: 'background.primary',
    display: 'grid',
    justifyItems: 'center',
    padding: '16',
  })

  export const rows = style({ marginBlockStart: '16' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Patterns/PendingPayment.tsx)

Press Send 25 USDC to move the payment from Pending to Confirmed. The balance changes only on confirmation.

* **Release the Button (loading):** Keep it busy until the network accepts the payment. Then add it to activity as Pending.
* **Don't Block the Screen:** Don't open a dialog while the transaction waits for a block. Other work stays available.
* **Design for the Slow Case (Under 1s):** Tempo blocks finalize this fast, but a wallet or RPC can still add delay. Link the Pending row to its details.

**Do:** Keep the balance as it is, and show the payment as Pending.

```tsx
/**
 * Do example for "Show Pending Transactions" on the Loading page.
 * Keep the balance as it is, and show the payment as Pending.
 * @module
 */
import { Amount, Badge, ListGroup, style } from '@tempoxyz/ds'
import { Pending } from '@tempoxyz/ds/icons'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.fill()}>
      <p {...styles.caption()}>Balance</p>
      <Amount currency="USD" size="md" value="1250.00" />
      <ListGroup.Root {...styles.rows()}>
        <ListGroup.Row>
          <ListGroup.Info>
            <ListGroup.Title>Sent 25.00 USDC</ListGroup.Title>
          </ListGroup.Info>
          <Badge>
            <Pending />
            Pending
          </Badge>
        </ListGroup.Row>
      </ListGroup.Root>
    </div>
  )
}

namespace styles {
  export const caption = style({ color: 'content.secondary', margin: '0', typography: 'body.b3' })

  export const fill = style({ width: '100% !custom' })

  export const rows = style({ marginBlockStart: '12' })
}
```

**Don't:** Subtract a payment from the balance before it confirms.

```tsx
/**
 * Don't example for "Show Pending Transactions" on the Loading page.
 * Don't subtract a payment from the balance before it confirms.
 * @module
 */
import { Amount, Badge, ListGroup, style } from '@tempoxyz/ds'
import { Pending } from '@tempoxyz/ds/icons'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.fill()}>
      <p {...styles.caption()}>Balance</p>
      <Amount currency="USD" size="md" value="1225.00" />
      <ListGroup.Root {...styles.rows()}>
        <ListGroup.Row>
          <ListGroup.Info>
            <ListGroup.Title>Sent 25.00 USDC</ListGroup.Title>
          </ListGroup.Info>
          <Badge>
            <Pending />
            Pending
          </Badge>
        </ListGroup.Row>
      </ListGroup.Root>
    </div>
  )
}

namespace styles {
  export const caption = style({ color: 'content.secondary', margin: '0', typography: 'body.b3' })

  export const fill = style({ width: '100% !custom' })

  export const rows = style({ marginBlockStart: '12' })
}
```

## Progress

Use [Progress](/docs/components/progress) when the work is measurable, such as files uploaded or steps completed. Use `value={null}` only if the remaining work is unknown.

**Do:** Show how much of a long task is done.

```tsx
/** Do example for "Show Pending Transactions" on the Loading page: show how much of a long task is done. @module */
import { Progress, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Progress.Root getAriaValueText={() => '3 of 5 months'} value={60} {...styles.fill()}>
      <Progress.Label>Exporting activity</Progress.Label>
      <Progress.Value>{() => '3 of 5 months'}</Progress.Value>
      <Progress.Track>
        <Progress.Indicator />
      </Progress.Track>
    </Progress.Root>
  )
}

namespace styles {
  export const fill = style({ width: '100% !custom' })
}
```

**Don't:** Show a spinner for a long, measurable task.

```tsx
/**
 * Don't example for "Show Pending Transactions" on the Loading page.
 * Don't show a spinner for a long, measurable task.
 * @module
 */
import { Spinner, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.row()}>
      <Spinner aria-label="Exporting activity" />
      <span {...styles.text()}>Exporting activity…</span>
    </div>
  )
}

namespace styles {
  export const row = style({ alignItems: 'center', display: 'flex', gap: '8' })

  export const text = style({ typography: 'body.b2' })
}
```

## States

* **Error:** Couldn't load in place of the placeholder, with Try again. Never leave an indicator spinning after a failure.
* **Empty:** An [Empty](/docs/components/empty) state after loading finishes with no content. Never show it while loading.
* **Disabled:** Controls that depend on the data stay disabled until it arrives, such as Send before balances load.
* **Success:** The content replaces the placeholder. Confirm finished actions with a [Toast](/docs/components/toast).

## Content

* **Present Tense:** Use the present tense: "Confirming payment".
* **Name the Thing:** Write "Loading transactions", not "Loading".

## Accessibility

* **Named Indicators (aria-label):** [Spinner](/docs/components/spinner), [LoadingDots](/docs/components/loading-dots), and the row loaders are named Loading. Pass `aria-label` to name what loads.
* **Skeleton (aria-busy):** Marks the region busy, blocks pointer input, and hides placeholder text from screen readers.
* **Busy Buttons (aria-busy):** A loading button is marked busy. Announce the result separately, such as in a toast.
* **Reduced Motion (prefers-reduced-motion):** Every sweep, rotation, and pulse stops. The indicators still mark work in progress.
* **Focus:** Don't move focus to an indicator, or to content when it arrives after a background load.

## Related

[Skeleton](/docs/components/skeleton)

Use for content with a known shape.

[Spinner](/docs/components/spinner)

Use for content with an unknown shape.

[Progress](/docs/components/progress)

Use for measurable work.

[Button](/docs/components/button)

Use for the `loading` state.

[Feedback and Status](/docs/patterns/feedback-and-status)

Covers Pending and Confirmed.

[Empty States](/docs/patterns/empty-states)

Covers what follows an empty result.

[Payments](/docs/patterns/payments)

Covers the send and review flow.
