Apollo Client alternative: GraphQL in React with HyperFetch
Apollo Client is the GraphQL client most React teams start with, and for a lot of them it's the right one to keep. If you're looking at graphql and react and wondering whether you need Apollo at all, the useful question is narrower: does your app depend on a normalized cache, or do you mostly need typed operations, loading state and caching per query? This page compares the apollo graphql client with HyperFetch's GraphQL adapter on that question and the ones around it. Every claim about Apollo links to its own docs.
- What Apollo Client does well, and who should stay on it.
- How a normalized cache differs from a per-operation cache in daily work.
- How queries, mutations and subscriptions look in each client.
- When HyperFetch is a reasonable Apollo Client alternative, and when it isn't.
What Apollo Client does well
Apollo describes itself as a "GraphQL state management library for JavaScript". That's accurate. It's more than a request sender.
- A normalized cache.
InMemoryCachesplits each response into objects and stores each one once, under a cache ID built from__typenameandid. Every query that returned the same object reads the same entry, so an update shows up everywhere it's referenced. See the caching overview. - Cache-first reads.
useQueryanswers from the cache when it can. The defaultfetchPolicyiscache-first(queries docs). - Mutations that update the cache on their own. If a mutation returns the changed object with its
id, Apollo writes it to the cache and every query showing it updates. New items in lists needrefetchQueriesor anupdatefunction.optimisticResponseshows the predicted result right away (mutations docs). - Subscriptions two ways. Over WebSocket with
GraphQLWsLinkand thegraphql-wslibrary, and over HTTP with multipart responses throughHttpLink(subscriptions docs). - Devtools. A browser extension for Chrome and Firefox with a cache inspector, a watched query inspector, a mutation inspector and GraphiQL. There's also an experimental VS Code version that can debug React Native and Node apps (developer tooling).
- Reach. React integration is built in, and the docs list community integrations for Angular, Vue, Svelte, Solid.js and others.
If your UI shows the same entities in many places (a user's name in a header, a list, a detail panel and a comment thread) and you want one mutation to fix all of them without thinking about it, Apollo is built for that. Stay on it.
The core difference: how results are cached
The two clients cache at different levels, and most other differences follow from that.
| Question | Apollo Client | HyperFetch |
|---|---|---|
| What is a cache entry? | One object, keyed by __typename:id | One operation with one set of variables |
| A mutation returns an updated user | Every query holding that user updates | You invalidate or update the queries that need it |
| A new item should appear in a list | refetchQueries or an update function | Invalidate the list query |
| Two queries return different fields of one object | Fields merge into one entry | Two separate entries |
| Debugging "why did this change?" | Follow references in the normalized store | Look at one entry |
A per-operation cache is less automatic. It's also easy to predict: a query's result is exactly what the server sent for that query, and it changes only when that query is refetched, invalidated or set by hand.
HyperFetch's GraphQL adapter builds the cache key from the operation name, a fingerprint of the document and the variables, so two documents with the same operation name but different fields never share an entry. Details are in the GraphQL adapter overview.
Queries
Apollo, from its get started page:
import { ApolloClient, HttpLink, InMemoryCache, gql } from "@apollo/client";
import { ApolloProvider, useQuery } from "@apollo/client/react";
const client = new ApolloClient({
link: new HttpLink({ uri: "https://api.example.com/graphql" }),
cache: new InMemoryCache(),
});
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
`;
function Profile({ id }: { id: string }) {
const { data, loading, error } = useQuery(GET_USER, { variables: { id } });
// ...
}
// <ApolloProvider client={client}><App /></ApolloProvider>
HyperFetch. The request is defined once, outside components, and needs no provider:
import { Client } from "@hyper-fetch/core";
import { GraphqlAdapter, GraphqlErrorType } from "@hyper-fetch/graphql";
import { useFetch } from "@hyper-fetch/react";
import gql from "graphql-tag";
type User = { id: string; name: string };
export const client = new Client<GraphqlErrorType>({ url: "https://api.example.com/graphql" }).setAdapter(
GraphqlAdapter(),
);
export const getUser = client.createRequest<{ response: { user: User }; payload: { id: string } }>()({
endpoint: gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
`,
});
function Profile({ id }: { id: string }) {
const { data, loading, error } = useFetch(getUser.setPayload({ id }));
// ...
}
The variables are the request payload. With GraphQL Code Generator or
gql.tada you can pass a typed document as endpoint and drop the generics: the response
and variables types come from the document. GraphQL errors in a 200 response come back as error, and
errorPolicy: "all" keeps partial data with the errors in extra.errors. See queries.
Mutations
Apollo's useMutation returns a mutate function, and the normalized cache does the rest when the response includes the
changed object.
In HyperFetch a mutation is another request, sent with useSubmit. You say which queries it affects:
import { useSubmit } from "@hyper-fetch/react";
const renameUser = client.createRequest<{ response: { renameUser: User }; payload: { id: string; name: string } }>()({
endpoint: gql`
mutation RenameUser($id: ID!, $name: String!) {
renameUser(id: $id, name: $name) {
id
name
}
}
`,
});
function RenameButton({ id }: { id: string }) {
const { submit, submitting, onSubmitSuccess } = useSubmit(renameUser);
onSubmitSuccess(() => client.cache.invalidate(getUser.setPayload({ id })));
return (
<button disabled={submitting} onClick={() => submit({ payload: { id, name: "Ada" } })}>
Rename
</button>
);
}
That invalidate line is the cost of not having a normalized cache. In return, nothing changes in your UI that you
didn't ask to change. Mutations and
submitting cover optimistic updates and progress.
Subscriptions
Apollo sends subscriptions through a link. For WebSocket that's GraphQLWsLink, usually combined with HttpLink
through ApolloLink.split so only subscriptions go over the socket. useSubscription reads them.
HyperFetch uses a separate Socket with the GraphqlWsAdapter. It speaks graphql-transport-ws, the protocol of
graphql-ws, and there's no link to split:
import { Socket } from "@hyper-fetch/sockets";
import { GraphqlWsAdapter } from "@hyper-fetch/graphql";
import { useListener } from "@hyper-fetch/react";
const socket = new Socket({ url: "wss://api.example.com/graphql", adapter: GraphqlWsAdapter() });
const onMessage = socket.createListener<{ onMessage: { text: string } }, { room: string }>()({
topic: "OnMessage",
options: {
document: gql`
subscription OnMessage($room: String!) {
onMessage(room: $room) {
text
}
}
`,
},
});
function ChatRoom({ room }: { room: string }) {
const { data, status } = useListener(onMessage.setPayload({ room }));
return <p>{status === "listening" ? data?.onMessage.text : "Connecting..."}</p>;
}
Listeners with the same document and variables share one server subscription, and after a reconnect every subscription is sent again. HyperFetch does not do subscriptions over multipart HTTP. See subscriptions.
Devtools
Apollo Client Devtools live in the browser's inspector and know your normalized cache. That's a real advantage when you debug cache merges.
HyperFetch's devtools are HyperFlow, a desktop app you connect with DevtoolsPlugin.
GraphQL requests are listed by operation name, and you can inspect, invalidate and delete cache entries and stop or
start queues.
Side by side
| Capability | Apollo Client | HyperFetch |
|---|---|---|
| Cache | Normalized, by __typename and id | Per operation and variables |
| Default read policy | cache-first | Cached data, refetched in the background on mount |
| React hooks | useQuery, useMutation, useSubscription | useFetch, useSubmit, useListener |
| Optimistic UI | optimisticResponse | setOptimistic on the request |
| Subscriptions over WebSocket | GraphQLWsLink (graphql-ws) | GraphqlWsAdapter (graphql-transport-ws) |
| Subscriptions over HTTP multipart | Yes | Not supported |
| REST and other backends | GraphQL only | Swap the adapter: fetch, Axios, Firebase, sockets |
| Devtools | Browser extension, VS Code (experimental) | HyperFlow desktop app |
| Frameworks | React, plus community integrations | React |
Which one fits you
Stay on Apollo Client when:
- The same entities show up across many queries and you want mutations to update all of them without extra code.
- You use subscriptions over multipart HTTP, or other Apollo and GraphOS features like the Explorer.
- You want devtools that show the normalized store inside the browser.
- Your team works in Angular, Vue or Svelte as well as React.
Pick HyperFetch when:
- GraphQL is one of several backends. REST, Firebase and WebSockets use the same
createRequest, cache and hooks. - Your queries rarely overlap on the same objects, so a normalized cache adds rules without saving work.
- You want requests to wait while the device is offline and go out when it reconnects. See offline.
- You'd rather invalidate the queries a mutation touched than learn cache merge policies.
For the other libraries people compare, see the overview and HyperFetch vs TanStack Query.
- Apollo Client's normalized cache stores each object once, so one mutation updates every query that shows it.
- HyperFetch caches each operation with its variables, and mutations invalidate the queries they affect.
- Both do GraphQL subscriptions over
graphql-ws. Only Apollo does them over multipart HTTP. - Pick Apollo for entity-heavy GraphQL apps, HyperFetch when GraphQL sits next to REST, sockets or offline needs.
