DEV Community

Cover image for Apollo Client with GraphQL: State Management for GraphQL Made Easy
Keyhole Software for Keyhole Software

Posted on

Apollo Client with GraphQL: State Management for GraphQL Made Easy

In this post, we will explore Apollo Client integrated with a React application and how it provides an abstraction layer between a JavaScript application and a GraphQL server. The features Apollo Client offers make it a prime choice for devs also using GraphQL.

We’ll begin by discussing what Apollo Client is and how it can be advantageous over other state management libraries. And finally, we will look at some example React queries for retrieving and mutating data.

Let’s get started.

Originally published on Keyholesoftware.com by Braden Niswonger on 1/16/23.

What is Apollo Client?

Apollo Client is a popular state management library built for JavaScript applications that interact with a GraphQL server. It allows easy solutions for handling GraphQL data including data fetching, caching, real-time subscriptions, and error handling. Additionally, Apollo Client has a large and active community with many resources and support for developers.

Apollo Client can be used in many different JavaScript libraries including Angular, Vue.JS, and React. This allows for easy integration into new and existing projects without having to rewrite code.

Why Use Apollo Client?

When using a GraphQL server, Apollo Client is a great choice for a front-end state management tool. The advantage of Apollo Client over other libraries such as Redux or Recoil is that it provides features specifically designed for GraphQL. Some of these features include:
Data Management: Apollo Client provides API for querying and modifying data, allowing for easy state management of an application.

  • Built-In Caching: By caching query results, Apollo Client can reduce the refetching of data that has already been retrieved.
  • Error Handling: Apollo Client has built-in error handling when querying or updating data. This helps simplify both error handling and error display to users.
  • Optimistic UI: Apollo Client will temporarily display the result of a mutation before the server has confirmed the change. Once the operation is complete, it will replace the optimistic data. This can make an application feel more responsive.
  • Developer Tooling: Apollo has a suite of developer tools that can be utilized for debugging and application support.

Set Up

The following command will install the Apollo Client and GraphQL dependencies needed.

npm install @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

Next, we will define a function to return an Apollo Client with reference to a GraphQL server. This will also set up an in-memory cache.

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

const client = new ApolloClient({
    uri: 'https://path-to-graphql-server.com/',
    cache: new InMemoryCache(),
});
Enter fullscreen mode Exit fullscreen mode

To finish setup, we have to wrap the React app with an ApolloProvider. This will allow any subcomponent access to the GraphQL data.

Wrapping can be done at any level, but I recommend putting it somewhere high in the component tree, above any component that will need to utilize it.

import { ApolloProvider } from '@apollo/client';
⋮
<ApolloProvider client={client}>
    <App />
</ApolloProvider>
Enter fullscreen mode Exit fullscreen mode

Queries

Now that dependencies have been installed and the application is properly set up, the application is equipped to start querying.

Apollo Client provides several custom React hooks for querying GraphQL data. For the sake of brevity in this post, we will only cover useQuery (used for retrieving data) and useMutation (used for modifying data).

useQuery
Enter fullscreen mode Exit fullscreen mode

The useQuery hook allows a GraphQL query to be executed inside a functional component. When using the hook, it will provide an object containing the dataset returned from the query, as well as some other metadata such as any loading and error states.

On component render, the hook will execute the given query. It will return the results in the data property, the current loading state in the loading property, and any errors in error.

    import { useQuery, gql } from '@apollo/client';
    ⋮
const { loading, error, data } = useQuery(gql`
    query {
        user {
            name
            email
        }
    } 
`);
Enter fullscreen mode Exit fullscreen mode
useMutation
Enter fullscreen mode Exit fullscreen mode

The useMutation hook is used for executing a GraphQL mutation in a functional component. The response is made of two parts.

The first is the mutation function that executes the mutation against the given GraphQL server. The second part is the object containing the results of the mutation, as well as the loading and error states.

The mutation function can be called with variables and options, and it returns a Promise that will resolve the mutation result.

import { useMutation, gql } from '@apollo/client';
    ⋮
const [createUser, { data, loading, error }] = useMutation(gql`
    mutation createUser($name: String!) {
        createUser(name: $name) {
            id
            name
            completed
        }
    }
`);
Enter fullscreen mode Exit fullscreen mode

Conclusion

For continued reading on Apollo Client or more example code, here are some resources I found helpful.

Top comments (0)