useSubscription
⚠️ NOTE: This document still needs to be updated for Apollo React/Relay Duct-Tape.
useSubscription
Hook used to subscribe and unsubscribe to a subscription.
import {graphql, useSubscription} from 'react-relay';
import {useMemo} from 'react';
const subscription = graphql`
subscription UserDataSubscription($input: InputData!) {
# ...
}
`;
function UserComponent({ id }) {
// IMPORTANT: your config should be memoized.
// Otherwise, useSubscription will re-render too frequently.
const config = useMemo(() => ({
variables: {id},
subscription,
}), [id, subscription]);
useSubscription(config);
return (/* ... */);
}
Arguments
config: a config of typeGraphQLSubscriptionConfigpassed torequestSubscriptionrequestSubscriptionFn:?<TSubscriptionPayload>(IEnvironment, GraphQLSubscriptionConfig<TSubscriptionPayload>) => Disposable. An optional function with the same signature asrequestSubscription, which will be called in its stead. Defaults torequestSubscription.
Type GraphQLSubscriptionConfig<TSubscriptionPayload>
- An object with the following fields:
cacheConfig: [Optional]CacheConfigsubscription:GraphQLTaggedNode. A GraphQL subscription specified using agraphqltemplate literalvariables: The variables to pass to the subscriptiononCompleted: [Optional]() => void. An optional callback that is executed when the subscription is establishedonError: [Optional](Error) => {}. An optional callback that is executed when an error occursonNext: [Optional](TSubscriptionPayload) => {}. An optional callback that is executed when new data is receivedupdater: [Optional]SelectorStoreUpdater.
Flow Type Parameters
TSubscriptionPayload: The type of the payloads vended by the subscription. You should pass the flow type imported from the auto-generated.graphqlfile corresponding to the subscription, e.g. useUserDataSubscriptionas the type parameter, fromimport type {UserDataSubscription} from './__generated__/UserDataSubscription.graphql';
Behavior
- This is only a thin wrapper around the
requestSubscriptionAPI. It will:- Subscribe when the component is mounted with the given config
- Unsubscribe when the component is unmounted
- Unsubscribe and resubscribe with new values if the environment, config or
requestSubscriptionFnchanges.
- If you have the need to do something more complicated, such as imperatively requesting a subscription, please use the
requestSubscriptionAPI directly. - See the GraphQL Subscriptions Guide for a more detailed explanation of how to work with subscriptions.