Skip to content

reactive/data-client / .agents/skills/data-client-react

data-client-react

Unverified

Read, change and render async and shared state in React with @data-client/react: any data from an API or other async source, and global state shared across components (it has to persist somewhere, which makes it async). Use it for loading and error states, mutations and forms, filtered or derived views, and debugging data that looks wrong or stale on screen. Use it in place of fetch in useEffect, or app-wide useState and context; its main hooks are useSuspense, useQuery and useController.

references/useLive.md

View on GitHub
<!-- Generated by `yarn build:skills` from docs/core/api/useLive.md (react). Edit the source doc, not this file. -->

# useLive()

Async rendering of remotely triggered data mutations.

[useSuspense()](./useSuspense.md) + [useSubscription()](./useSubscription.md) in one hook.

`useLive()` is reactive to data [mutations](./mutations.md); rerendering only when necessary.

## Usage

```typescript title="Ticker" {33}
import { Entity, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class Ticker extends Entity {
  product_id = '';
  trade_id = 0;
  price = 0;
  size = '0';
  time = Temporal.Instant.fromEpochMilliseconds(0);
  bid = '0';
  ask = '0';
  volume = '';

  pk(): string {
    return this.product_id;
  }
  static key = 'Ticker';

  static schema = {
    price: Number,
    time: Temporal.Instant.from,
  };
}

export const getTicker = new RestEndpoint({
  urlPrefix: 'https://api.exchange.coinbase.com',
  path: '/products/:productId/ticker',
  schema: Ticker,
  process(value, { productId }) {
    value.product_id = productId;
    return value;
  },
  pollFrequency: 2000,
});
```

```tsx title="AssetPrice" {6}
import { useLive } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';

function AssetPrice({ productId }: Props) {
  const ticker = useLive(getTicker, { productId });
  return (
    <dl className="stats">
      <div>
        <dt>{productId}</dt>
        <dd>
          <NumberFlow
            value={ticker.price}
            format={{ style: 'currency', currency: 'USD' }}
          />
        </dd>
      </div>
    </dl>
  );
}
interface Props {
  productId: string;
}
render(<AssetPrice productId="BTC-USD" />);
```

## Behavior

> **Tip: Conditional Dependencies**
>
> Use `null` as the second argument to any Data Client hook means "do nothing."
> A [RestEndpoint](https://dataclient.io/rest/api/RestEndpoint) without path or search params takes `{}` in its place, like `enabled ? {} : null`.
>
> ```typescript
> // todo could be undefined if id is undefined
> const todo = useLive(TodoResource.get, id ? { id } : null);
> ```

> **Info: React Native**
>
> When using React Navigation, useLive() will trigger fetches on focus if the data is considered
> stale. useLive() will also sub/unsub with focus/unfocus respectively.

In a hidden [`<Activity>`](https://react.dev/reference/react/Activity), `useLive()` unsubscribes. It subscribes
again when shown. [Example](#pause-hidden-tabs)

## Types

```typescript
function useLive(
  endpoint: ReadEndpoint,
  ...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema>;
```

```typescript
function useLive<
  E extends EndpointInterface<
    FetchFunction,
    Schema | undefined,
    undefined
  >,
  Args extends readonly [...Parameters<E>] | readonly [null],
>(
  endpoint: E,
  ...args: Args
): E['schema'] extends Exclude<Schema, null>
  ? Denormalize<E['schema']>
  : ReturnType<E>;
```

## Examples

### Bitcoin Price (polling)

When our component with `useLive` is rendered, `getTicker` will fetch at [pollFrequency](https://dataclient.io/rest/api/RestEndpoint#pollfrequency)
milliseconds.

Example app: [nextjs](https://github.com/reactive/data-client/tree/master/examples/nextjs) ([`resources/Ticker.ts`](https://github.com/reactive/data-client/blob/master/examples/nextjs/resources/Ticker.ts), [`components/AssetPrice.tsx`](https://github.com/reactive/data-client/blob/master/examples/nextjs/components/AssetPrice.tsx))

### Pause hidden tabs

Keep tabs mounted in [`<Activity>`](https://react.dev/reference/react/Activity). Only the shown tab polls.

```typescript title="Ticker"
import { Entity, RestEndpoint } from '@data-client/rest';

export class Ticker extends Entity {
  product_id = '';
  price = 0;

  pk() {
    return this.product_id;
  }
  static key = 'Ticker';

  static schema = { price: Number };
}

export const getTicker = new RestEndpoint({
  urlPrefix: 'https://api.exchange.coinbase.com',
  path: '/products/:productId/ticker',
  schema: Ticker,
  process(value, { productId }) {
    value.product_id = productId;
    return value;
  },
  pollFrequency: 2000,
});
```

```tsx title="AssetPrice"
import { useLive } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';

export default function AssetPrice({ productId }: Props) {
  const ticker = useLive(getTicker, { productId });
  return (
    <dl className="stats">
      <div>
        <dt>{productId}</dt>
        <dd>
          <NumberFlow
            value={ticker.price}
            format={{ style: 'currency', currency: 'USD' }}
          />
        </dd>
      </div>
    </dl>
  );
}
interface Props {
  productId: string;
}
```

```tsx title="Markets" {25-30}
import React from 'react';
import AssetPrice from './AssetPrice';

const products = ['BTC-USD', 'ETH-USD', 'SOL-USD'];

function Markets() {
  const [shown, setShown] = React.useState(products[0]);
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Markets</h1>
        <div className="segmented" role="group" aria-label="Product">
          {products.map(productId => (
            <button
              key={productId}
              aria-pressed={productId === shown}
              onClick={() => setShown(productId)}
            >
              {productId.split('-')[0]}
            </button>
          ))}
        </div>
      </header>
      {products.map(productId => (
        <React.Activity
          key={productId}
          mode={productId === shown ? 'visible' : 'hidden'}
        >
          <AssetPrice productId={productId} />
        </React.Activity>
      ))}
    </>
  );
}
render(<Markets />);
```

A hidden tab keeps its state, but its Effects stop. If no other component subscribes to its price, polling stops. When
shown, polling resumes. If the last fetch is older than [pollFrequency](https://dataclient.io/rest/api/RestEndpoint#pollfrequency), it
fetches at once.

Hidden tabs still render, so every tab fetches its price before it shows. Switching tabs shows a price with no loading
state.
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 319kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 196kUpdated Claude CodeCodexVerifiedInstall