Make Your Apollo GraphQL Queries Even Faster With Prefetching and Optimistic Response | Daniel.Me

Make Your Apollo GraphQL Queries Even Faster With Prefetching and Optimistic Response

Date: December 30th, 2020

There are some possible ways to improve performance in the Apollo Client. Two of the best tweaks are prefetching data, and optimistic response. Let's spend time with each of them, and find out what they are, and where you can use them in your code.

Prefetching

The term is self-explanatory. Prefetching is a way to make your app's UI feel instantaneous by anticipating when a user will require data to be loaded. One way I use this in my Teachery app is when a user hovers over the More pagination button, it will prefetch the next set of data, saving the user a click and a second or two of time. These small prefetching techniques add up, providing a snappy performance users will praise.

Here's an example of an onMouseOver event that triggers a client query to prefetch information.

const Query = () => {
  const { loading, error, data, client } = useQuery<GetPostsData, GetPostsVars>(
    GET_POSTS,
    { variables: { options: { paginate: { page: 1, limit: 3 } } } }
  );
  return (
    <div>
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Error! `{error.message}</p>
      ) : (
        <div>
          {data &&
            data.posts.data.map((post) => <Post key={post.id} post={post} />)}
        </div>
      )}
      <>
        <button
          type="button"
          onMouseOver={() =>
            console.log(
              client.query({
                query: GET_POSTS,
                variables: { options: { paginate: { page: 2, limit: 3 } } },
              })
            )
          }
        >
          Show
        </button>
      </>
    </div>
  );
};

Optimistic Response

Another pattern used is optimistic UI which simulates the result of an Apollo mutation or update before receiving a response from the server. After the response is received, the optimistic response is replaced with the actual result. This pattern provides a way to make your UI respond much faster, and is useful in cases where a user edits certain items that are likely to not change after the server response is received. For example, we could use optimistic on a like/unlike button, or editing the title of an item (as used in my Teachery project).

 const [updateCard, { loading, error }] = useMutation(UPDATE_CARD, {
    optimisticResponse: {
      __typename: "Mutation",
      updateCard: {
        id: id,
        __typename: "",
        front: front,
        back: back,
        pictureName: pictureName,
        pictureUrl: pictureUrl,
      },
    },

These 2 features built into Apollo will make for snappy performance, and provide users with a better UI experience, with just a few lines of code. I recommend they be used as much as possible, where appropriate.

Menu