reactive/data-client / .agents/skills/data-client-react
data-client-react
UnverifiedRead, 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/useSubscription.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/core/api/useSubscription.md (react). Edit the source doc, not this file. -->
# useSubscription()
Keeps data that changes often up to date.
The default [polling subscriptions](https://dataclient.io/docs/api/PollingSubscription) need
[pollFrequency](https://dataclient.io/rest/api/RestEndpoint#pollfrequency) set on the [Endpoint](https://dataclient.io/rest/api/Endpoint). Without it, subscribing
logs an error and does nothing.
> **Tip**
>
> [useLive()](./useLive.md) combines `useSubscription()` with [useSuspense()](./useSuspense.md) in one call.
## Usage
```typescript title="Ticker" {23}
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" {7}
import { useSuspense, useSubscription } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';
function AssetPrice({ productId }: { productId: string }) {
const ticker = useSuspense(getTicker, { productId });
useSubscription(getTicker, { productId });
return (
<dl className="stats">
<div>
<dt>{productId}</dt>
<dd>
<NumberFlow
value={ticker.price}
format={{ style: 'currency', currency: 'USD' }}
/>
</dd>
</div>
</dl>
);
}
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 = useSubscription(TodoResource.get, id ? { id } : null);
> ```
> **Info: React Native**
>
> When using React Navigation, useSubscription() will sub/unsub with focus/unfocus respectively.
In a hidden [`<Activity>`](https://react.dev/reference/react/Activity), `useSubscription()` unsubscribes. It
subscribes again when shown. [Example](#pause-while-hidden)
## Types
```typescript
function useSubscription(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): void;
```
```typescript
function useSubscription<
E extends EndpointInterface<
FetchFunction,
Schema | undefined,
undefined
>,
Args extends readonly [...Parameters<E>] | readonly [null],
>(endpoint: E, ...args: Args): void;
```
## Examples
### Only subscribe while element is visible
```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="useInView"
import React from 'react';
/** Whether the element is on screen */
export function useInView<T extends Element>() {
const ref = React.useRef<T>(null);
const [inView, setInView] = React.useState(false);
React.useEffect(() => {
// one callback can hold several entries: the last is current
const observer = new IntersectionObserver(entries =>
entries.forEach(entry => setInView(entry.isIntersecting)),
);
if (ref.current) observer.observe(ref.current);
return () => observer.disconnect();
}, []);
return [ref, inView] as const;
}
```
```tsx title="Watchlist" {9-10}
import { useSuspense, useSubscription } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';
import { useInView } from './useInView';
function AssetRow({ productId }: { productId: string }) {
const ticker = useSuspense(getTicker, { productId });
const [ref, inView] = useInView<HTMLDivElement>();
// null args means don't subscribe
useSubscription(getTicker, inView ? { productId } : null);
return (
<div className="listItem" ref={ref}>
<h4>{productId}</h4>
<NumberFlow
className="value"
value={ticker.price}
format={{ style: 'currency', currency: 'USD' }}
/>
</div>
);
}
const products = [
'BTC-USD',
'ETH-USD',
'SOL-USD',
'BCH-USD',
'LTC-USD',
'AAVE-USD',
'AVAX-USD',
'LINK-USD',
];
render(
<>
<header className="appHeader">
<h1 className="appTitle">Watchlist</h1>
</header>
<div className="list scroll">
{products.map(productId => (
<AssetRow key={productId} productId={productId} />
))}
</div>
</>,
);
```
Passing `null` as the second argument turns the subscription off for this component. Updates continue while other
components subscribe to the same data.
`useInView()` uses [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API),
which is very performant. Hooks such as [useIntersectionObserver()](https://usehooks.com/useintersectionobserver) do
the same.
### Pause while hidden
To hide a panel or tab, wrap it in [`<Activity>`](https://react.dev/reference/react/Activity). `AssetPrice` needs
no change.
```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 { useSuspense, useSubscription } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';
export default function AssetPrice({ productId }: { productId: string }) {
const ticker = useSuspense(getTicker, { productId });
useSubscription(getTicker, { productId });
return (
<dl className="stats">
<div>
<dt>{productId}</dt>
<dd>
<NumberFlow
value={ticker.price}
format={{ style: 'currency', currency: 'USD' }}
/>
</dd>
</div>
</dl>
);
}
```
```tsx title="PricePanel" {14-16}
import React from 'react';
import AssetPrice from './AssetPrice';
function PricePanel({ productId }: { productId: string }) {
const [open, setOpen] = React.useState(false);
return (
<>
<header className="appHeader">
<h1 className="appTitle">Prices</h1>
<button aria-expanded={open} onClick={() => setOpen(!open)}>
{open ? 'Hide' : 'Show'} price
</button>
</header>
<React.Activity mode={open ? 'visible' : 'hidden'}>
<AssetPrice productId={productId} />
</React.Activity>
</>
);
}
render(<PricePanel productId="BTC-USD" />);
```
A hidden `<Activity>` keeps `AssetPrice` and its state, but stops its Effects. If no other component subscribes to the
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.
A hidden `<Activity>` still renders. So `useSuspense()` fetches the price before the panel opens, and the panel opens
without a loading state.
### Crypto prices (websockets)
A custom `StreamManager` handles the websocket protocol. It listens to the [subscribe and unsubscribe
actions](./Actions.md#subscribe) that `useSubscription()` sends, so it only receives updates for rendered components.
Example app: [coin-app](https://github.com/reactive/data-client/tree/master/examples/coin-app) ([`src/resources/StreamManager.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/StreamManager.ts), [`src/resources/Ticker.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/Ticker.ts), [`src/pages/Home/AssetPrice.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/Home/AssetPrice.tsx))
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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: 319k | Updated | Claude CodeCodex | Verified | Install |
| 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: 196k | Updated | Claude CodeCodex | Verified | Install |
| 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: 196k | Updated | Claude CodeCodex | Verified | Install |
| 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: 196k | Updated | Claude CodeCodex | Verified | Install |