In the world of web and mobile application development, efficiently managing state and fetching data is crucial for building high-quality user experiences. Traditionally, REST APIs have been the go-to solution. However, as application complexity grows, REST can feel limiting for cases requiring real-time data and frequent client-server communication.

This is where GraphQL and Apollo Client shine—by enabling precise, flexible data fetching and caching. In this post, we’ll explore implementing real-time data updates in React using GraphQL subscriptions and Apollo Client.

Why GraphQL for Real-Time Data?

GraphQL is a query language spec that provides an alternative to REST for developing APIs. With GraphQL requests on the backend and Apollo bringing it to the frontend, several key benefits emerge:

Precise data fetching: Fetch exactly the data you need, nothing more. No over or under-fetching resources.

Real-time updates: Subscribe to specific events or data changes rather than polling.

Strongly typed: Excellent support for static typing systems like TypeScript.

Flexible: Easily evolve APIs and build powerful tools like GraphiQL.

These capabilities make GraphQL a prime choice for applications needing real-time data synchronization.

Implementing Real-Time Updates with Subscriptions

Apollo Client is a fully-featured GraphQL client for JavaScript applications. It enables查询,变更和订阅operations against a GraphQL API.

Subscriptions are what enable real-time data over GraphQL. As a server’s data changes, it publishes update events that subscribed clients react to by reading the updates and modifying their UI.

Here’s an overview of implementing real-time updates with subscriptions:

  1. Set up a GraphQL API with subscription capabilities
  2. Connect Apollo Client to the API
  3. Write subscription query and handler logic
  4. Register the client to subscribe
  5. Display real-time updates in UI

Next, we’ll walk through a concrete example to see these steps in action.

Building a Real-Time Commenting App

To demonstrate live data fetching with React Apollo and GraphQL, we’ll build a simple real-time commenting app.

Here’s a look at the key pieces we’ll implement:

  • A GraphQL server with subscription capabilities
  • An Apollo Client to connect the React frontend
  • A subscription to update when new comments are added
  • Real-time display of new comments

Let’s get building!

Creating the GraphQL Server

Our GraphQL server will need to handle queries, mutations for adding comments, and subscriptions for notifying on new comments.

Many servers like Apollo and Hasura support GraphQL out-of-the-box. To keep things simple though, we’ll use a lightweight GraphQL Yoga server.

First install GraphQL Yoga:

npm install graphql-yoga

Then implements the schema andresolvers:

import { GraphQLServer } from 'graphql-yoga';

interface Comment {
  id: string;
  text: string;
}

let comments: Comment[] = [];

const typeDefs = `
  type Comment {
    id: ID!
    text: String!
  }

  type Query {
    comments: [Comment!]!
  }

  type Mutation {
    addComment(text: String!): Comment!
  }

  type Subscription {
    newComment: Comment!
  }
`;

const resolvers = {
  Query: {
    comments() {
      return comments;
    },
  },

  Mutation: {
    addComment(parent, { text }, ctx, info) {
      const comment = {
        id: String(comments.length + 1),
        text,
      };
      comments.push(comment);

      ctx.pubsub.publish('NEW_COMMENT', {
        newComment: comment,
      });

      return comment;
    },
  },

  Subscription: {
    newComment: {
      subscribe: (parent, args, ctx) => {
        return ctx.pubsub.asyncIterator('NEW_COMMENT');
      },
    },
  },
};

const pubsub = new PubSub();

const server = new GraphQLServer({
  typeDefs,
  resolvers,
  context: {
    pubsub,
  },
});

server.start(() => {
  console.log(`GraphQL server running on http://localhost:4000`);
});

This gives us everything needed for queries, mutations and subscriptions against comments.

Connecting Apollo Client

Now we can utilize Apollo Client graphql in our React app to connect to this GraphQL API.

First install Apollo dependencies:

npm install @apollo/client graphql

Inside the React component, initialize the client:

import {
  ApolloClient,
  InMemoryCache,
  gql,
  useSubscription
} from '@apollo/client';

const client = new ApolloClient({
  uri: 'http://localhost:4000',
  cache: new InMemoryCache()
});

We now have Apollo Client ready for data fetching!

Implementing the Comment Subscription

Next up is creating the subscription to update whenever a new comment is added.

Inside our React component, write the subscription query:

const NEW_COMMENT = gql`
  subscription NewComment {
    newComment {
      id
      text
    }
  }
`;

This listens for the newComment event published by the server.

Then create a handler to process the update:

function NewComment() {
  const { data } = useSubscription(NEW_COMMENT);

  if (data) {
    const comment = data.newComment;
    addComment(comment);
  }

  return null;
}

Whenever data arrives, we’ll add that comment into the UI list.

Finally, register the subscription:

return (
  <ApolloProvider client={client}>
    <NewComment /> {/* subscribe */}

    {/* display comments */}
  </ApolloProvider>
);

Now real-time comment updates will flow through.

Displaying Comments

All that’s left is querying and showing the list of comments:

const GET_COMMENTS = gql`
  query GetComments {
    comments {
      id
      text
    }
  }
`;

function Comments() {
  const { data, loading } = useClient.query({
    query: GET_COMMENTS,
  });

  if (loading) return <Loading />

  return (
    <ul>
      {data.comments.map(comment => (
        <li key={comment.id}>
          {comment.text}
        </li>
      ))}
    </ul>
  );
}

We fetch the comments and render each one. Combining everything together delivers a real-time commenting experience!

Key Takeaways

Implementing live data and synchronization in apps using GraphQL and Apollo provides an excellent developer experience. The key strengths we demonstrated include:

Precise data handling: Our comment subscription updates only what is needed.

React integration: Apollo Client integrates cleanly with React frontend code.

Type safety: Our queries, mutations and component props were typed with TypeScript.

Real-time UI updates: As soon as the server published new comment events, Apollo propagated those updates to automatically rerender UI.

GraphQL eliminates major pain points around fetching data, enabling you to focus on creating amazing user experiences. Apollo brings that power directly into your React apps.

Need Help Building Your Frontend Apps?

React paired with GraphQL & Apollo Client equips engineering teams to ship sophisticated, real-time mobile and web applications.

As an experienced full-stack developer, I help with architect, build, and launch production-ready apps leveraging these modern technologies.