Integrating GraphQL with React.js: A Practical Guide

Kevin Diesenberg
2 min readJun 14, 2023

--

GraphQL is a powerful alternative to REST that lets client applications specify their own typed data requirements. Apollo Client is a popular library for integrating GraphQL in JavaScript applications, including React. In this post, we’ll guide you through setting up Apollo Client in a React app and executing GraphQL queries and mutations.

Setting Up Apollo Client

Install the Apollo Client libraries with npm:

npm install @apollo/client graphql

Set up the Apollo Client in your app:

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

const client = new ApolloClient({
uri: "https://your-graphql-endpoint.com/graphql",
cache: new InMemoryCache(),
});

function App() {
return (
<ApolloProvider client={client}>
{/* Your app components */}
</ApolloProvider>
);
}

Querying Data

With Apollo Client, you can write GraphQL queries as tagged template literals:

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 }) => (
<div key={id}>
<p>
{id}: {breed}
</p>
</div>
));
}

Mutating Data

You can use the useMutation hook to execute GraphQL mutations:

import { gql, useMutation } from "@apollo/client";

const ADD_DOG = gql`
mutation AddDog($breed: String!) {
addDog(breed: $breed) {
id
breed
}
}
`;

function AddDog() {
let input;
const [addDog, { data }] = useMutation(ADD_DOG);

return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addDog({ variables: { breed: input.value } });
input.value = "";
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Add Dog</button>
</form>
</div>
);
}

Conclusion

GraphQL and Apollo Client bring a new level of efficiency and flexibility in data management for your React apps. This guide covers just the basics, and there’s much more to learn about error handling, caching, local state management, and more.

In the next post, we’ll explore how to implement server-side rendering in React.js applications. Until then, happy coding!

--

--

Kevin Diesenberg
Kevin Diesenberg

Written by Kevin Diesenberg

Software Engineer | JavaScript | React | Ruby | Rails | SQL | Skydiver | Outdoor Enthusiast | Paramotor Pilot | Cyclist | Edible Mushroom Hunter