Skip to main content
Version: 6.6

useSubscription()

function useSubscription(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): void;

Great for keeping resources up-to-date with frequent changes.

When using the default polling subscriptions, frequency must be set in Endpoint, otherwise will have no effect.

Send null to params to unsubscribe.

Example

api/Price.ts
import { Resource, Entity } from '@rest-hooks/rest';

export class Price extends Entity {
readonly symbol: string | undefined = undefined;
readonly price: string = '0.0';
// ...

pk() {
return this.symbol;
}
}

export const getPrice = new RestEndpont({
urlPrefix: 'http://test.com',
path: '/price/:symbol',
schema: Price,
pollFrequency: 5000,
});
MasterPrice.tsx
import { useSuspense, useSubscription } from 'rest-hooks';
import { getPrice } from 'api/Price';

function MasterPrice({ symbol }: { symbol: string }) {
const price = useSuspense(getPrice, { symbol });
useSubscription(getPrice, { symbol });
// ...
}

Only subscribe while element is visible

MasterPrice.tsx
import { useRef } from 'react';
import { useSuspense, useSubscription } from 'rest-hooks';
import { getPrice } from 'api/Price';

function MasterPrice({ symbol }: { symbol: string }) {
const price = useSuspense(getPrice, { symbol });
const ref = useRef();
const onScreen = useOnScreen(ref);
// null params means don't subscribe
useSubscription(getPrice, onScreen ? null : { symbol });

return (
<div ref={ref}>{price.value.toLocaleString('en', { currency: 'USD' })}</div>
);
}

Using the last argument active we control whether the subscription is active or not based on whether the element rendered is visible on screen.

useOnScreen() uses IntersectionObserver, which is very performant.

Useful Endpoints to send

Resource provides these built-in:

  • get
  • getList

Feel free to add your own RestEndpoint as well.