Fetch Data In React With GraphQL
Introduction
GraphQL was developed internally by Facebook in 2012 and became open-source in 2015. Since that time, the community around GraphQL has grown rapidly. A lot of companies have adopted it. It’s used by teams of all sizes in many different environments and languages to power mobile apps, websites, and APIs.
If you’re not familiar with REST API, I highly recommend reading the How To Fetch Data In React From REST API article first as it can help with understanding below concepts.
In a nutshell, GraphQL is a query language for APIs. It provides a runtime for fulfilling those queries. The idea behind GraphQL is to describe the data, ask for what you want, and get predictable results.
Let’s go on a journey to explore how we can use GraphQL in React.
Get what you want
The beauty of GraphQL comes from a single endpoint. You don’t need to create dozens of API endpoints with specific payloads to fit the UI needs. By using the query, you define exactly the fields you need and get only those from the API.
The Query
Let’s start from the building block of GraphQL which is a query. It describes the shape of data you want to receive from the server. Here is an example using the GitHub GraphQL API:
query {
viewer {
login
name
bio
avatarUrl
location
url
}
}
The query above describes the shape of data we want. We ask for the viewer (which represents the currently authenticated user) and specific fields like login, name, bio, avatarUrl, location, and url.
The response will contain exactly those fields - nothing more, nothing less. This is one of the key advantages of GraphQL over REST APIs.
How to use the Query?
To use a GraphQL query in a React application, we typically use a client library. One of the most popular ones is Apollo Client. Here’s how you can fetch data using it:
import { useQuery, gql } from "@apollo/client";
const GET_VIEWER = gql`
query {
viewer {
login
name
bio
avatarUrl
location
url
}
}
`;
const Profile = () => {
const { loading, error, data } = useQuery(GET_VIEWER);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const { login, name, bio, avatarUrl, location, url } = data.viewer;
return (
<div>
<img src={avatarUrl} alt={name} />
<h2>{name}</h2>
<p>{login}</p>
<p>{bio}</p>
<p>{location}</p>
<a href={url}>GitHub Profile</a>
</div>
);
};
export default Profile;
The useQuery hook from Apollo Client handles loading, error states, and the data response for us. It’s a clean, declarative way to fetch data.
Example Application
Below is an embedded example showing GraphQL data fetching in action:
import React from "react";
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql,
} from "@apollo/client";
const client = new ApolloClient({
uri: "https://api.github.com/graphql",
cache: new InMemoryCache(),
headers: {
authorization: `Bearer YOUR_GITHUB_TOKEN`,
},
});
const GET_VIEWER = gql`
query {
viewer {
login
name
bio
avatarUrl
location
url
}
}
`;
const Profile = () => {
const { loading, error, data } = useQuery(GET_VIEWER);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const { login, name, bio, avatarUrl, location, url } = data.viewer;
return (
<div>
<img src={avatarUrl} alt={name} width={100} />
<h2>{name}</h2>
<p>@{login}</p>
<p>{bio}</p>
<p>{location}</p>
<a href={url}>View GitHub Profile</a>
</div>
);
};
const App = () => (
<ApolloProvider client={client}>
<Profile />
</ApolloProvider>
);
export default App;
The key takeaway here is that we wrap our app with ApolloProvider to make the client available throughout the component tree. Then, any component can use useQuery to fetch exactly the data it needs.
GraphQL also supports mutations (for modifying data) and subscriptions (for real-time updates), but queries are the foundation you need to understand first.
Summary
GraphQL provides a powerful alternative to REST APIs. Here are the key points:
- Single endpoint - Unlike REST, where you might need multiple endpoints, GraphQL uses one endpoint for all data needs
- Request exactly what you need - The query defines the shape of the response, preventing over-fetching or under-fetching
- Strongly typed - GraphQL schemas define the types available, making the API self-documenting
- Great developer experience - Tools like Apollo Client provide hooks that handle loading, error states, and caching out of the box
If you haven’t already, check out the How To Fetch Data In React From REST API article to understand the differences between REST and GraphQL approaches.
For more learning, explore the official GraphQL documentation and the Apollo Client docs.
Ready to level up your coding skills?
Build real projects and grow your portfolio with BigDevSoon.
Start 7-Day Free Trial
Creator of BigDevSoon
Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.
Related Posts
Fetch Data In React As User Types Or Clicks
Let's dive into a bit more complex examples of real-world scenarios. Fetching data from an API as a user types or clicks is a common pattern in modern web applications.
How To Fetch Data In React From REST API
Let's learn how to fetch data in React using fetch, axios, and react-query.
8 Useful React Components
There is a lot of pre-built, reusable, abstracted, encapsulated, and tested code available to use nowadays.