The user wants a React application that uses GraphQL subscriptions for live updates.
I need to provide a complete, runnable example.
To do this effectively, I should:
-
Choose the Stack:
- Frontend: React (obviously).
- GraphQL Client: Apollo Client is the industry standard and handles subscriptions well.
- GraphQL Server: I need a mock server to make the subscriptions actually work in the example. Apollo Server is the natural choice here.
- Transport: WebSocket (via
graphql-ws or subscriptions-transport-ws). graphql-ws is the modern standard.
-
Structure the Response:
- Prerequisites: Briefly mention necessary packages.
- Step 1: The Server: It's hard to demonstrate subscriptions without a backend that pushes data. I'll create a simple Node.js/Express + Apollo Server setup that emits a random number or a message every second.
- Step 2: The Client Setup: How to configure Apollo Client to support WebSocket links.
- Step 3: The React Component: A component that subscribes to the data and renders it.
- Step 4: Running it: Instructions on how to glue it together.
-
Drafting the Server (Server-side):
- Need
apollo-server, graphql, graphql-subscriptions.
- Schema:
type Query, type Subscription.
- Resolvers:
Query (dummy), Subscription (using PubSub).
- I need to make sure the server handles WebSocket connections. Apollo Server 4 requires a bit of setup for subscriptions (often using
express and createServer or just the built-in logic if using standalone). Let's stick to ApolloServer from @apollo/server and expressMiddleware combined with graphql-ws and ws (WebSocket library) for a modern v4 setup. Self-correction: That might be too complex for a "quick example".
- Alternative: Use
apollo-server (v3) which has built-in subscription support easier to demo, OR just provide the code for the modern v4 approach because it's what people should use now. Let's go with the modern Apollo Server 4 approach because it's robust.
-
Drafting the Client (Front-end):
- Dependencies:
@apollo/client, graphql-ws, react.
- Setup: Split HTTP link and WebSocket link using
split.
- Hook:
useSubscription.
-
Refining the Example Scenario:
- A "Live Counter" or "Chat Message" is the classic example. Let's do a "Live Timer" or "Countdown" that updates every second. It's visual and easy to verify.
-
Step-by-Step Implementation Plan:
-
Writing the Code (Mental Draft & Refinement):
-
Server:
import { ApolloServer } from '@apollo/server';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
// ... resolvers ...
// Interval: pubsub.publish('NUMBER', { number: i });
Actually, to keep it simple for the user to copy-paste, maybe I should provide a single file server setup.
-
Client:
import { split, HttpLink, ApolloClient, InMemoryCache } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
// Split link logic
// useSubscription hook
-
Addressing Potential Issues:
- CORS: The server needs CORS headers if running on a different port than React.
- Protocol: React usually runs on 3000, Server on 4000.
-
Finalizing the Structure for the Output:
I will provide a "Backend" folder and a "Frontend" folder structure approach, as that's how real apps are built.
- Backend:
server.js
- Frontend:
App.js (setup + component)
- Dependencies: List them clearly.
-
Reviewing the Code Snippets:
- Server: Use
graphql-ws library. It's the current standard, replacing subscriptions-transport-ws.
- Client:
GraphQLWsLink is required.
-
Self-Correction during drafting:
- The Apollo Client setup in v3 was simpler, but v4 is the current version. I must use the v4 syntax (
@apollo/client).
- I should explicitly mention the
split function. It's the "magic" part that directs subscription traffic to WS and query/mutation to HTTP.
-
Constructing the Response:
- Start with the architecture explanation.
- Provide the Server code.
- Provide the Client code.
- Explain the key parts (PubSub, WebSocket Link,
useSubscription).
(Self-Correction on Complexity): Setting up a full Apollo Server 4 with WebSockets is verbose (requires express, http, ws, body-parser, etc.). If I make it too long, the user might get lost. I will simplify the server to use the standalone server pattern if possible, or stick to the Express one but keep it minimal. Actually, graphql-ws has a dedicated recipe for Apollo Server. I will use that standard recipe.
Let's refine the "Scenario". Let's make a "Live Message" system. The server emits a timestamp every second.
- Backend:
type Subscription { currentTime: String! }
- Frontend: Displays the time string.
-
Final Polish: Ensure import statements are correct for modern ESM (using import syntax) as Node supports it now, or stick to CommonJS (require) to be safe? Modern React tutorials usually use ESM. I'll use ESM and assume "type": "module" in package.json or assume the user knows how to run it. I'll stick to standard CommonJS for the server to ensure maximum compatibility without configuration headaches, or strictly note ESM. Let's go with ESM for frontend and CJS for backend to be safe, or ESM for both if I specify the flag. Let's write the server in CJS (standard Node style) and client in ESM (standard React style).
Wait, actually, @apollo/server encourages ESM. I will stick to standard syntax but add a note.
Let's write the solution.
Plan:
- Prerequisites: List npm packages.
- Server Implementation: Simple Apollo Server 4 + graphql-ws setup.
- Client Implementation: React + Apollo Client 3+ with GraphQLWsLink.
- Explanation: Detail how the
split link and useSubscription work.
Code Check - Server:
npm install @apollo/server graphql graphql-ws ws
npm install @apollo/client graphql graphql-ws (client side)
Let's go.
To implement a React application with GraphQL subscriptions, you need two main parts:
-
A Server that maintains an open connection (usually via WebSockets) to push data to clients.
-
A Client (React) that listens for that data.
I will use the Apollo Client (industry standard) and the modern graphql-ws library.
Here is a complete, runnable example.
Prerequisites
You will need to install the following dependencies:
Server:
npm install @apollo/server graphql graphql-ws ws
Client:
npm install @apollo/client graphql graphql-ws
Part 1: The GraphQL Server (Node.js)
We need a server that supports WebSocket connections. This server will publish a random number every second to simulate live data.
Create a file named server.js:
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { PubSub } from 'graphql-subscriptions';
// 1. Setup PubSub to handle events
const pubsub = new PubSub();
const NUMBER_INCREMENTED = 'NUMBER_INCREMENTED';
// 2. Define Schema
const typeDefs = `#graphql
type Query {
currentNumber: Int
}
type Subscription {
numberIncremented: Int
}
`;
// 3. Define Resolvers
const resolvers = {
Query: {
currentNumber: () => 0,
},
Subscription: {
numberIncremented: {
subscribe: () => pubsub.asyncIterator([NUMBER_INCREMENTED]),
},
},
};
// 4. Create Schema
const schema = makeExecutableSchema({ typeDefs, resolvers });
// 5. Start Apollo Server (HTTP)
const server = new ApolloServer({ schema });
const { url } = await startStandaloneServer(server, { port: 4000 });
console.log(`🚀 Query endpoint ready at ${url}`);
// 6. Setup WebSocket Server (Subscriptions)
const wsServer = new WebSocketServer({
port: 4001,
path: '/graphql',
});
useServer({ schema }, wsServer);
console.log(`🚀 Subscription endpoint ready at ws://localhost:4001/graphql`);
// 7. Simulate Live Data
let currentNumber = 0;
setInterval(() => {
currentNumber++;
pubsub.publish(NUMBER_INCREMENTED, { numberIncremented: currentNumber });
}, 1000);
Part 2: The React Application
In your React app (e.g., App.js), you need to configure the ApolloClient to split your communication: standard HTTP for queries/mutations, and WebSockets for subscriptions.
import React from 'react';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
split,
HttpLink
} from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { useSubscription, gql } from '@apollo/client';
// 1. Define the Subscription Query
const NUMBER_SUBSCRIPTION = gql`
subscription OnNumberIncremented {
numberIncremented
}
`;
// 2. Setup Links
// HTTP Link for standard queries
const httpLink = new HttpLink({
uri: 'http://localhost:4000' // Server HTTP Port
});
// WebSocket Link for subscriptions
const wsLink = new GraphQLWsLink(createClient({
url: 'ws://localhost:4001/graphql', // Server WebSocket Port
}));
// Split Link: Send data to WS if operation is subscription, else HTTP
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
// 3. Initialize Client
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
// 4. Component that uses the Subscription
function LiveDataComponent() {
const { data, loading, error } = useSubscription(NUMBER_SUBSCRIPTION);
if (loading) return <div>Connecting to WebSocket...</div>;
if (error) return <div>Error! {error.message}</div>;
return (
<div style={{ padding: '20px', border: '1px solid #ccc', marginTop: '20px' }}>
<h3>Live Update:</h3>
<div style={{ fontSize: '2rem', fontWeight: 'bold', color: 'green' }}>
{data && data.numberIncremented}
</div>
</div>
);
}
// 5. Main App
export default function App() {
return (
<ApolloProvider client={client}>
<div className="App">
<h2>GraphQL Subscription Demo</h2>
<p>Open this app in multiple tabs. The number below should sync automatically.</p>
<LiveDataComponent />
</div>
</ApolloProvider>
);
}
How it works
split Link: This is the most critical part of the React setup. It inspects every GraphQL operation.
- If it is a Subscription, it sends it through the
wsLink (WebSocket).
- If it is a Query or Mutation, it sends it through the
httpLink.
GraphQLWsLink: This establishes a persistent connection to the server. Unlike HTTP requests which close immediately, this stays open to allow the server to push messages.
useSubscription: This hook behaves similarly to useQuery. It returns data, loading, and error. However, the data property will update whenever the server pushes a new event, triggering a re-render of the component.
- Server
PubSub: On the backend, we use a publish-subscribe pattern. When pubsub.publish is called, the server finds all active WebSocket connections listening to that specific event and pushes the data out.