apollo-client
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
Top Related Projects
A reference implementation of GraphQL for JavaScript
Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
The Fullstack Tutorial for GraphQL
Code-First, Type-Safe, GraphQL Schema Construction
Quick Overview
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It can be used to fetch, cache, and modify application data, all while automatically updating your UI.
Pros
- Powerful caching mechanism that reduces network requests and improves app performance
- Seamless integration with React and other popular frameworks
- Excellent developer tools for debugging and inspecting queries
- Strong TypeScript support for enhanced type safety
Cons
- Steep learning curve for developers new to GraphQL
- Can be overkill for small projects or simple API interactions
- Requires careful configuration to avoid overfetching or underfetching data
- Performance can degrade with very large datasets if not optimized properly
Code Examples
- Setting up Apollo Client:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
- Executing a query:
import { gql, useQuery } from '@apollo/client';
const GET_DOGS = gql`
query GetDogs {
dogs {
id
breed
}
}
`;
function Dogs() {
const { loading, error, data } = useQuery(GET_DOGS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.dogs.map(({ id, breed }) => (
<p key={id}>{breed}</p>
));
}
- Performing a mutation:
import { gql, useMutation } from '@apollo/client';
const ADD_TODO = gql`
mutation AddTodo($type: String!) {
addTodo(type: $type) {
id
type
}
}
`;
function AddTodo() {
const [addTodo, { data }] = useMutation(ADD_TODO);
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addTodo({ variables: { type: input.value } });
input.value = '';
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}
Getting Started
To start using Apollo Client in your project:
-
Install the necessary packages:
npm install @apollo/client graphql
-
Set up Apollo Client in your app:
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://your-graphql-endpoint.com', cache: new InMemoryCache() }); function App() { return ( <ApolloProvider client={client}> <YourApp /> </ApolloProvider> ); }
-
Start using Apollo Client hooks in your components to fetch and manage data.
Competitor Comparisons
A reference implementation of GraphQL for JavaScript
Pros of graphql-js
- Reference implementation of GraphQL specification
- Language-agnostic, can be used with any JavaScript runtime
- Provides low-level GraphQL parsing and execution utilities
Cons of graphql-js
- Requires more setup and configuration for client-side usage
- Less opinionated, may require additional libraries for full-featured client implementation
- Steeper learning curve for beginners
Code Comparison
graphql-js:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
hello: String
}
`);
const rootValue = { hello: () => 'Hello world!' };
graphql({ schema, source: '{ hello }', rootValue }).then((response) => {
console.log(response);
});
apollo-client:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
client.query({
query: gql`{ hello }`
}).then(result => console.log(result));
Summary
graphql-js is the reference implementation of GraphQL, offering low-level utilities and flexibility. It's ideal for server-side implementations and custom client setups. Apollo Client, on the other hand, provides a more opinionated and feature-rich solution for client-side GraphQL integration, with built-in caching and state management capabilities.
Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
Pros of Graffle
- Lightweight and minimalistic approach to GraphQL client implementation
- Focuses on simplicity and ease of use for basic GraphQL operations
- Potentially faster setup and integration for small to medium-sized projects
Cons of Graffle
- Less comprehensive feature set compared to Apollo Client
- Smaller community and ecosystem, which may result in fewer resources and third-party integrations
- May lack advanced caching and state management capabilities
Code Comparison
Apollo Client:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
Graffle:
import { createClient } from 'graffle';
const client = createClient({
url: 'https://api.example.com/graphql'
});
Both Apollo Client and Graffle provide GraphQL client solutions for JavaScript applications. Apollo Client offers a more robust and feature-rich ecosystem, with advanced caching, state management, and a wide range of integrations. It's well-suited for large-scale applications with complex data requirements.
Graffle, on the other hand, takes a more minimalistic approach, focusing on simplicity and ease of use. It may be a good choice for smaller projects or developers who prefer a lightweight solution with less overhead.
The code comparison shows that Graffle has a simpler setup process, while Apollo Client requires additional configuration for caching. This reflects the difference in their approaches, with Apollo Client providing more out-of-the-box features at the cost of increased complexity.
The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
Pros of urql
- Lightweight and modular, with a smaller bundle size
- Simpler API and easier to learn for beginners
- More flexible and customizable through its plugin system
Cons of urql
- Less mature ecosystem and fewer community resources
- Limited built-in features compared to Apollo Client
- May require additional setup for advanced caching scenarios
Code Comparison
urql:
import { createClient, Provider, useQuery } from 'urql';
const client = createClient({
url: '/graphql',
});
function App() {
return (
<Provider value={client}>
<MyComponent />
</Provider>
);
}
Apollo Client:
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: '/graphql',
cache: new InMemoryCache()
});
function App() {
return (
<ApolloProvider client={client}>
<MyComponent />
</ApolloProvider>
);
}
Both libraries offer similar setup processes, but urql's API is generally more concise. Apollo Client provides more built-in features out of the box, while urql focuses on a minimal core with extensibility through plugins. The choice between the two often depends on project requirements, team familiarity, and the need for specific features or ecosystem support.
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
Pros of GraphQL Engine
- Provides an instant GraphQL API over existing databases
- Offers real-time subscriptions and live queries out of the box
- Includes a powerful authorization system with role-based access control
Cons of GraphQL Engine
- Primarily focused on backend, lacking client-side data management features
- Less flexible for custom server-side logic compared to Apollo Client's integration capabilities
- Steeper learning curve for developers new to Hasura's ecosystem
Code Comparison
Apollo Client:
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
const GET_USERS = gql`
query GetUsers {
users {
id
name
}
}
`;
GraphQL Engine:
tables:
- table:
schema: public
name: users
select_permissions:
- role: user
permission:
columns:
- id
- name
filter: {}
GraphQL Engine focuses on defining backend structures and permissions, while Apollo Client emphasizes client-side query management and caching. GraphQL Engine excels in rapidly creating APIs from existing databases, whereas Apollo Client shines in managing complex client-side data flows and state management.
The Fullstack Tutorial for GraphQL
Pros of How to GraphQL
- Comprehensive learning resource for GraphQL beginners
- Covers multiple languages and frameworks
- Community-driven with contributions from various experts
Cons of How to GraphQL
- Not a production-ready library like Apollo Client
- Less frequent updates compared to Apollo Client
- Limited to educational content, not a full-featured GraphQL implementation
Code Comparison
How to GraphQL (example query):
query {
allPersons {
name
age
posts {
title
}
}
}
Apollo Client (example query):
const GET_PERSONS = gql`
query GetPersons {
allPersons {
name
age
posts {
title
}
}
}
`;
Summary
How to GraphQL is an educational resource focused on teaching GraphQL concepts across various technologies. It's ideal for beginners but lacks the production-ready features of Apollo Client. Apollo Client, on the other hand, is a robust GraphQL client library for building applications. While How to GraphQL provides a broader overview of GraphQL ecosystems, Apollo Client offers a more specialized and feature-rich solution for implementing GraphQL in JavaScript applications.
Code-First, Type-Safe, GraphQL Schema Construction
Pros of Nexus
- Provides a code-first approach to GraphQL schema definition, offering better type safety and developer experience
- Offers powerful plugin system for extending functionality and integrating with other tools
- Includes built-in schema visualization and introspection tools
Cons of Nexus
- Steeper learning curve compared to Apollo Client's more straightforward setup
- Less extensive ecosystem and community support
- Primarily focused on server-side GraphQL, while Apollo Client is a complete client-side solution
Code Comparison
Nexus (schema definition):
import { objectType, queryType, makeSchema } from 'nexus'
const User = objectType({
name: 'User',
definition(t) {
t.string('id')
t.string('name')
},
})
const Query = queryType({
definition(t) {
t.list.field('users', {
type: 'User',
resolve: () => [{ id: '1', name: 'John' }],
})
},
})
const schema = makeSchema({
types: [User, Query],
})
Apollo Client (query execution):
import { ApolloClient, gql } from '@apollo/client'
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
})
const GET_USERS = gql`
query GetUsers {
users {
id
name
}
}
`
client.query({ query: GET_USERS }).then((result) => {
console.log(result.data.users)
})
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Announcement:
Join 1000+ engineers at GraphQL Summit for talks, workshops, and office hours, Oct 8-10 in NYC. Get your pass here ->
Apollo Client is a fully-featured caching GraphQL client with integrations for React, Angular, and more. It allows you to easily build UI components that fetch data via GraphQL.
âï¸ Apollo Client User Survey |
---|
What do you like best about Apollo Client? What needs to be improved? Please tell us by taking a one-minute survey. Your responses will help us understand Apollo Client usage and allow us to serve you better. |
Documentation
All Apollo Client documentation, including React integration articles and helpful recipes, can be found at:
https://www.apollographql.com/docs/react/
The Apollo Client API reference can be found at:
https://www.apollographql.com/docs/react/api/apollo-client/
Learn how to use Apollo Client with self-paced hands-on training on Odyssey, Apollo's official learning platform:
https://odyssey.apollographql.com/
Maintainers
Name | Username |
---|---|
Ben Newman | @benjamn |
Alessia Bellisario | @alessbell |
Jeff Auriemma | @bignimbus |
Hugh Willson | @hwillson |
Jerel Miller | @jerelmiller |
Lenz Weber-Tronic | @phryneas |
Who is Apollo?
Apollo builds open-source tools and commercial services to make application development easier, better, and accessible to more people. We help you ship faster with:
- GraphOS - The platform for building, managing, and scaling a supergraph: a unified network of your organization's microservices and their data sourcesâall composed into a single distributed API.
- Apollo Federation â The industry-standard open architecture for building a distributed graph. Use Apolloâs gateway to compose a unified graph from multiple subgraphs, determine a query plan, and route requests across your services.
- Apollo Client â The most popular GraphQL client for the web. Apollo also builds and maintains Apollo iOS and Apollo Kotlin.
- Apollo Server â A production-ready JavaScript GraphQL server that connects to any microservice, API, or database. Compatible with all popular JavaScript frameworks and deployable in serverless environments.
Learn how to build with Apollo
Check out the Odyssey learning platform, the perfect place to start your GraphQL journey with videos and interactive code challenges. Join the Apollo Community to interact with and get technical help from the GraphQL community.
Top Related Projects
A reference implementation of GraphQL for JavaScript
Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
The Fullstack Tutorial for GraphQL
Code-First, Type-Safe, GraphQL Schema Construction
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot