Blog>
Snippets

Using useSyncExternalStore with GraphQL Subscriptions

Example code for a scenario where useSyncExternalStore is used to handle GraphQL subscriptions and update component state accordingly.
import { useSyncExternalStore } from 'react';
import { useSubscription } from '@apollo/client';
import gql from 'graphql-tag';

// Define your GraphQL subscription
const MY_SUBSCRIPTION = gql`
  subscription OnNewItem {
    newItem {
      id
      title
      description
    }
  }
`;

// Custom hook to use GraphQL subscription with useSyncExternalStore
function useSubscriptionStore(getSnapshot, subscribe) {
  const store = useSyncExternalStore(
    subscribe,
    getSnapshot,
    getSnapshot,
  );
  return store;
}

function MyComponent() {
  // Setup the subscription
  const { data, loading } = useSubscription(MY_SUBSCRIPTION);

  // Subscribe and getSnapshot functions for useSyncExternalStore
  const subscribe = (onStoreChange) => {
    // TODO: Set up the subscription event listeners and notify onStoreChange when the data changes
  };
  const getSnapshot = () => data;

  // Use custom hook to integrate subscription with React state
  const itemData = useSubscriptionStore(getSnapshot, subscribe);

  if (loading) return <p>Loading...</p>;
  if (!itemData) return <p>No data received</p>;

  // Render the new item data
  return (
    <div>
      <h3>{itemData.newItem.title}</h3>
      <p>{itemData.newItem.description}</p>
    </div>
  );
}
This example demonstrates how to integrate a GraphQL subscription into a React component's state using the `useSyncExternalStore` hook with a custom `useSubscriptionStore` hook. The `useSubscription` hook from Apollo Client sets up the subscription and provides the data, while `useSyncExternalStore` syncs that data with the component's state. When the subscription's data changes, the component will re-render with the new data.