useSubscription()
Keeps data that changes often up to date.
The default polling subscriptions need pollFrequency set on the Endpoint. Without it, subscribing logs an error and does nothing.
useLive() combines useSubscription() with useSuspense() in one call.
Usage
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
Use null as the second argument to any Data Client hook means "do nothing."
A RestEndpoint without path or search params takes {} in its place, like enabled ? {} : null.
// todo could be undefined if id is undefined
const todo = useSubscription(TodoResource.get, id ? { id } : null);
When using React Navigation, useSubscription() will sub/unsub with focus/unfocus respectively.
In a hidden <Activity>, useSubscription() unsubscribes. It
subscribes again when shown. Example
Types
- Type
- With Generics
function useSubscription(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): void;
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
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,
which is very performant. Hooks such as useIntersectionObserver() do
the same.
Pause while hidden
To hide a panel or tab, wrap it in <Activity>. AssetPrice needs
no change.
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, 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 that useSubscription() sends, so it only receives updates for rendered components.
Explore the coin-app example