How to Use useSubscription Hook in Apollo Client
Use the
useSubscription hook from Apollo Client to subscribe to GraphQL subscription queries in React. Pass your subscription query to useSubscription, and it returns live data, loading, and error states that update automatically when new data arrives.Syntax
The useSubscription hook takes a GraphQL subscription query as its main argument and returns an object with data, loading, and error properties.
Example parts:
SUBSCRIPTION_QUERY: Your GraphQL subscription query.useSubscription(SUBSCRIPTION_QUERY): Hook call to start subscription.data: The latest subscription data received.loading: Boolean indicating if subscription is connecting.error: Any error encountered during subscription.
javascript
const { data, loading, error } = useSubscription(SUBSCRIPTION_QUERY);
Example
This example shows how to subscribe to new messages in a chat app using useSubscription. It displays messages as they arrive in real time.
javascript
import React from 'react'; import { gql, useSubscription } from '@apollo/client'; const NEW_MESSAGES_SUBSCRIPTION = gql` subscription OnNewMessage { newMessage { id content sender } } `; function Messages() { const { data, loading, error } = useSubscription(NEW_MESSAGES_SUBSCRIPTION); if (loading) return <p>Loading messages...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <h2>New Messages</h2> {data && data.newMessage && ( <p><strong>{data.newMessage.sender}:</strong> {data.newMessage.content}</p> )} </div> ); } export default Messages;
Output
<div>
<h2>New Messages</h2>
<p><strong>Alice:</strong> Hello!</p>
</div>
Common Pitfalls
- Not wrapping your app with
ApolloProvidercauses the hook to fail. - Using a query instead of a subscription query will not stream updates.
- Ignoring
loadinganderrorstates can cause UI confusion. - Not handling null or undefined
databefore rendering can cause errors.
javascript
/* Wrong: Using query instead of subscription */ const { data } = useSubscription(gql`query { messages { id } }`); /* Right: Use subscription query */ const { data } = useSubscription(gql`subscription { newMessage { id } }`);
Quick Reference
- Import
useSubscriptionfrom@apollo/client. - Define your subscription with
gql. - Call
useSubscriptionwith your subscription query. - Use
data,loading, anderrorto update your UI. - Ensure your Apollo Client supports subscriptions (e.g., WebSocket link).
Key Takeaways
Use
useSubscription to receive real-time updates in React with Apollo Client.Always handle
loading and error states to improve user experience.Define your subscription query with
gql and pass it to useSubscription.Wrap your app with
ApolloProvider configured for subscriptions to enable live data.Check that your GraphQL server supports subscriptions and your client uses a WebSocket link.