A fully-featured caching GraphQL client with React integration and intelligent query management.
npx @tessl/cli install tessl/npm-apollo--client@4.0.0Apollo Client is a comprehensive GraphQL client library with intelligent caching, React integration, and extensive link system for customizable data fetching. It provides zero-configuration caching with intelligent query result storage and normalization, extensive React hooks for data fetching and state management, support for advanced GraphQL features like subscriptions and mutations with optimistic updates, and comprehensive developer tooling including DevTools extension and VS Code integration. The library is designed for maximum reusability across web applications requiring GraphQL data management, provides full TypeScript support with automatic type generation, and maintains high performance through efficient caching strategies and bundle optimization.
npm install @apollo/client graphqlimport { ApolloClient, InMemoryCache, gql } from "@apollo/client";For React applications:
import { ApolloProvider, useQuery, useMutation, useSubscription } from "@apollo/client/react";For CommonJS:
const { ApolloClient, InMemoryCache, gql } = require("@apollo/client");import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
// Create Apollo Client instance
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
// Define a query
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;
// Execute query
client.query({
query: GET_USERS
}).then(result => {
console.log(result.data.users);
});
// React usage
import { useQuery } from "@apollo/client/react";
function UsersList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Apollo Client is built around several key components:
ApolloClient class manages GraphQL operations, cache coordination, and link chain executionInMemoryCache provides normalized caching with intelligent updates and reactive queriesuseQuery, useMutation, useSubscription) with Suspense supportTypedDocumentNode for end-to-end type safetyCentral client functionality for executing GraphQL operations with caching and link management. The ApolloClient class provides the foundation for all GraphQL operations.
class ApolloClient<TCacheShape = NormalizedCacheObject> {
constructor(options: ApolloClientOptions<TCacheShape>);
query<T = any, TVariables = OperationVariables>(
options: QueryOptions<TVariables, T>
): Promise<ApolloQueryResult<T>>;
mutate<TData = any, TVariables = OperationVariables>(
options: MutationOptions<TData, TVariables>
): Promise<FetchResult<TData>>;
subscribe<T = any, TVariables = OperationVariables>(
options: SubscriptionOptions<TVariables, T>
): Observable<FetchResult<T>>;
}Intelligent caching with normalization, reactive updates, and flexible policies. The caching system provides automatic normalization and reactive updates for GraphQL data.
class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
constructor(config?: InMemoryCacheConfig);
readQuery<QueryType, TVariables = any>(
options: Cache.ReadQueryOptions<QueryType, TVariables>
): QueryType | null;
writeQuery<TData = any, TVariables = any>(
options: Cache.WriteQueryOptions<TData, TVariables>
): void;
modify(options: Cache.ModifyOptions): boolean;
}
function makeVar<T>(value: T): ReactiveVar<T>;React hooks for GraphQL operations with Suspense support and comprehensive state management. Provides declarative data fetching for React applications.
function useQuery<TData = any, TVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: QueryHookOptions<TData, TVariables>
): QueryResult<TData, TVariables>;
function useMutation<TData = any, TVariables = OperationVariables>(
mutation: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: MutationHookOptions<TData, TVariables>
): MutationTuple<TData, TVariables>;
function useSubscription<TData = any, TVariables = OperationVariables>(
subscription: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: SubscriptionHookOptions<TData, TVariables>
): SubscriptionResult<TData>;
// Advanced hooks for concurrent rendering
function useBackgroundQuery<TData, TVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: BackgroundQueryHookOptions<TData, TVariables>
): UseBackgroundQueryResult<TData, TVariables>;
function useReadQuery<TData, TVariables>(
queryRef: QueryRef<TData, TVariables>
): UseReadQueryResult<TData, TVariables>;
function useSuspenseQuery<TData, TVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: SuspenseQueryHookOptions<TData, TVariables>
): UseSuspenseQueryResult<TData, TVariables>;Modular transport and middleware system for GraphQL operations. The link system provides customizable request/response processing with support for multiple transports.
abstract class ApolloLink {
static from(links: (ApolloLink | RequestHandler)[]): ApolloLink;
static split(
test: (op: Operation) => boolean,
left: ApolloLink | RequestHandler,
right: ApolloLink | RequestHandler
): ApolloLink;
abstract request(operation: Operation): Observable<FetchResult> | null;
}
class HttpLink extends ApolloLink {
constructor(options?: HttpOptions);
}
function createHttpLink(options?: HttpOptions): ApolloLink;Mock implementations for testing GraphQL operations and React components. Provides comprehensive testing support for Apollo Client applications.
class MockLink extends ApolloLink {
constructor(mockedResponses: MockedResponse[], addTypename?: boolean);
addMockedResponse(mockedResponse: MockedResponse): void;
}
interface MockedProvider {
mocks?: MockedResponse[];
addTypename?: boolean;
defaultOptions?: DefaultOptions;
cache?: ApolloCache<any>;
resolvers?: Resolvers;
typeDefs?: string | string[] | DocumentNode | DocumentNode[];
childProps?: object;
children?: ReactNode;
}Comprehensive error handling for GraphQL operations and transport failures. Provides structured error types and handling mechanisms.
class ApolloError extends Error {
message: string;
graphQLErrors: readonly GraphQLError[];
protocolErrors: readonly GraphQLError[];
clientErrors: readonly Error[];
networkError: Error | null;
extraInfo: any;
}
class ServerError extends Error {
response: Response;
result: Record<string, any>;
statusCode: number;
}Helper functions and utilities for GraphQL operations, cache management, pagination, and development workflows. Provides essential tools for working with GraphQL documents and Apollo Client internals.
function getMainDefinition(queryDoc: DocumentNode): OperationDefinitionNode | FragmentDefinitionNode;
function isReference(obj: any): obj is Reference;
function concatPagination<T>(keyArgs?: FieldPolicy['keyArgs']): FieldPolicy<T[]>;
function offsetLimitPagination<T>(keyArgs?: FieldPolicy['keyArgs']): FieldPolicy<T[]>;
function relayStylePagination<T>(keyArgs?: FieldPolicy['keyArgs']): FieldPolicy<T>;
class DocumentTransform {
constructor(transform: DocumentTransformFunction, options?: DocumentTransformOptions);
transformDocument(document: DocumentNode): DocumentNode;
}Type-safe fragment management with GraphQL Code Generator integration. Provides compile-time verification that components only access fragment data they explicitly declare.
type FragmentType<TFragmentData> = TFragmentData & {
readonly __fragmentType: unique symbol;
};
type Unmasked<TData> = TData extends FragmentType<infer U> ? U : TData;
type MaybeMasked<TData> = TData | Unmasked<TData>;
function maskFragment<TData>(fragment: DocumentNode, data: TData): FragmentType<TData>;
function useFragment<TData>(fragment: DocumentNode, data: FragmentType<TData>): TData;interface OperationVariables {
[key: string]: any;
}
interface ApolloQueryResult<T> {
data: T;
loading: boolean;
networkStatus: NetworkStatus;
error?: ApolloError;
}
interface FetchResult<TData = Record<string, any>, TContext = Record<string, any>, TExtensions = Record<string, any>> {
data?: TData | null;
extensions?: TExtensions;
context?: TContext;
}
type ErrorPolicy = 'none' | 'ignore' | 'all';
type FetchPolicy = 'cache-first' | 'cache-only' | 'cache-and-network' | 'network-only' | 'no-cache' | 'standby';
enum NetworkStatus {
loading = 1,
setVariables = 2,
fetchMore = 3,
refetch = 4,
poll = 5,
ready = 6,
error = 7,
}