# React and Next.js

> Typed React skeleton loader components with server rendering, for React 19 and the Next.js App Router.

To show a skeleton loader in React, wrap the part of the page that loads in Dotquilt's `<LoadingRegion>`, give it a `placeholder` such as `<SkeletonText lines={3} />`, and set its `state` from your data: `pending`, `refreshing` or `ready`.

The React adapter wraps the same native components in typed React components. They register themselves, render their placeholder on the server, and take their state from your props.

```tsx
import { LoadingRegion, SkeletonText } from '@dotquilt/react';
```

Each component also has its own entry point, such as `@dotquilt/react/region`, if you prefer to import only what a page uses.

## State comes from your data

A region needs only two things from you: whether the data is `pending`, `refreshing` or `ready`, and a `cycle` naming the current request. Keep the request in your own state, as in the component pages' examples:

- **Start a new cycle per request**, such as the id you are loading. A stale answer for an older cycle can't settle a newer one.
- **Use `refreshing`** when you already show data and are fetching a newer copy: the content stays visible and usable.
- **On an error**, show your message with `state="ready"` and `timing={{ duration: 0 }}`, so it replaces the placeholder at once.

## Next.js App Router

The components are client components (`'use client'`), and they render on the server too: the placeholder is in the first HTML, before any JavaScript runs. Put your data loading in a client component of your own, and use it from a Server Component page:

```tsx title="app/revenue/page.tsx"
// app/revenue/page.tsx: a Server Component. It renders the client component
// below on the server, so the placeholder is in the first HTML.
import { RevenueChart } from '@/components/revenue-chart';

export default function RevenuePage() {
  return (
    <main>
      <h1>Revenue</h1>
      <RevenueChart year={2026} />
    </main>
  );
}
```

```tsx title="components/revenue-chart.tsx"
'use client';
import { ChartLoader, LoadingRegion } from '@dotquilt/react';
import type { TargetProvider } from 'dotquilt/chart';
import { useEffect, useState } from 'react';
import { linePath, linePoints } from './data';

async function fetchRevenue(
  year: number,
  signal: AbortSignal,
): Promise<number[]> {
  const response = await fetch(`/api/revenue/${year}`, { signal });
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return response.json();
}

type Result =
  | { status: 'loading' }
  | { status: 'done'; series: number[] }
  | { status: 'failed' };

export function RevenueChart({ year }: { year: number }) {
  const [result, setResult] = useState<Result>({ status: 'loading' });

  useEffect(() => {
    const request = new AbortController();
    setResult({ status: 'loading' });
    fetchRevenue(year, request.signal)
      .then((series) => setResult({ status: 'done', series }))
      .catch(() => {
        if (!request.signal.aborted) setResult({ status: 'failed' });
      });
    return () => request.abort();
  }, [year]);

  // Where the real line will be, in the loader's own size: the marks glide
  // onto it before the chart draws in.
  const target: TargetProvider = ({ width, height }) =>
    result.status === 'done'
      ? {
          kind: 'line',
          points: linePoints(result.series, width, height),
          baseline: height,
        }
      : null;

  return (
    <LoadingRegion
      aria-label={`Revenue in ${year}`}
      state={result.status === 'loading' ? 'pending' : 'ready'}
      cycle={String(year)}
      timing={result.status === 'failed' ? { duration: 0 } : undefined}
      placeholder={
        <ChartLoader
          variant="line"
          targetProvider={target}
          style={{ height: 160 }}
        />
      }
    >
      {result.status === 'done' && (
        <svg
          viewBox="0 0 320 160"
          preserveAspectRatio="none"
          style={{ display: 'block', width: '100%', height: 160 }}
          role="img"
          aria-label={`Revenue in ${year}, by month`}
        >
          <path
            d={linePath(result.series, 320, 160)}
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            vectorEffect="non-scaling-stroke"
          />
        </svg>
      )}
      {result.status === 'failed' && (
        <p role="alert">We couldn't load revenue. Try again later.</p>
      )}
    </LoadingRegion>
  );
}

export function Report() {
  return <RevenueChart year={2026} />;
}
```

Keep functions such as `targetProvider` and custom animations inside client components: they can't be passed from a Server Component.

### Suspense

Suspense and a loading region do different jobs. Suspense waits for server-side work before sending HTML; a region shows a placeholder while the browser loads data. If you stream a server component through Suspense, you can use a Dotquilt placeholder as its fallback without a region:

```tsx
<Suspense fallback={<SkeletonText lines={3} />}>
  <RevenueSummary />
</Suspense>
```

A placeholder on its own is decoration, hidden from assistive technology. If the wait matters, say so in your own words nearby.

## View transitions

Dotquilt works inside React's `<ViewTransition>` (and `document.startViewTransition`). A view transition shows frozen snapshots of the page while it runs, so when one is running as a region becomes ready, the region holds the first frame of its handoff and plays it in full once the transition ends. Nothing jumps when the snapshots lift.

```tsx
<ViewTransition>
  <LoadingRegion state={data ? 'ready' : 'pending'} placeholder={<SkeletonText lines={3} />}>
    {data && <Summary data={data} />}
  </LoadingRegion>
</ViewTransition>
```

To let the view transition alone reveal the content, pass `timing={{ duration: 0 }}` to the region.

## Styles and CSP

By default each component adds its styles inline, once per page. If your site has a Content Security Policy, pass a `stylePolicy` to every component: a nonce, or an external stylesheet. See [Content Security Policy](/docs/guides/csp/).
