How To Use GraphQL: A Beginner Walk-through
Tags: graphql, react, webdev, beginners
Published: 2023-05-25 13:54:40

# How To Use GraphQL: A Beginner Walk-through

## Introduction

For software developers, it is a common practice to make several HTTP requests to retrieve server data for a single page. The consequence of [making multiple HTTP requests](https://blog.hubspot.com/marketing/reduce-http-requests) may lead to several complications, including server and network overload, as well as complex error handling.

What if I told you there's another way? A smarter way of doing this? Fasten your seatbelt as you ride along with me to discover more. 🚀

In this post, I present to you [GraphQL](https://graphql.org/) - a query language for APIs that has quickly gained popularity. Since its release to the [open-source community](https://github.com/graphql) by [Facebook](https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language/) in [2015](https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language/), GraphQL has significantly grown among the developer community.

In 2019 alone, [according to data by StateOfJS](https://2019.stateofjs.com/data-layer/graphql/), about ten thousand developers indicated interest to use GraphQL in addition to the seven thousand active users of GraphQL.

[![GraphQL 2019 StateOfJS](https://i.imgur.com/SAlqTHA.png)](https://2019.stateofjs.com/data-layer/graphql/)

Image source: [*StateOfJS 2019*](https://2019.stateofjs.com/data-layer/graphql/)

In this article, you will learn what GraphQL is, I will discuss how to use GraphQL and its advantages. I will also take a deep dive into [queries](https://graphql.org/learn/queries/), [mutations](https://graphql.org/learn/queries/), [fragments](https://graphql.org/learn/queries/#fragments), [directives](https://graphql.org/learn/queries/#directives), and best practices to help you use GraphQL effectively. Are you ready to save time and write more efficient code? Let's get started!

## What is GraphQL?

This may not be your first time coming across the term "*GraphQL*", however, if it is, you have nothing to worry about as you would be taking a deep dive into GraphQL in this post.

[GraphQL](https://graphql.org/) stands for **Graph** **Q**uery **L**anguage. It is a query language for APIs. It allows clients to request specific data from an API, rather than receiving all of the data that is available. This makes [GraphQL](https://graphql.org/) more efficient and flexible than traditional REST APIs.

> A GraphQL query is a string that is sent to a server to be interpreted and fulfilled, which then returns JSON to the client. - [Engineering at Meta](https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language/)

![GraphQL](https://i.imgur.com/4Xfkrkr.png)

## Why use [GraphQL](https://graphql.org/)?

With [GraphQL](https://graphql.org/), you can fetch all the necessary data with a single request. No more multiple HTTP requests!

There are several reasons why you might want to use [GraphQL](https://graphql.org/):

* **Efficiency**: GraphQL only returns the data that you request, which can improve performance.
* **Flexibility**: GraphQL allows you to request data in any order or format, which gives you more control over your application.
* **Scalability**: GraphQL can be used to scale your application as your needs grow.
* **Avoid unnecessary issues peculiar to REST API:** The REST API architecture is known for the following issues such as:
  * **Over-fetching**: When the server sends unneeded data to the client, it is referred to as over-fetching within an API. The API is established prior, and the client only needs to comply with the API documentation. However, this approach has a downside in that it results in bandwidth being squandered.
  * **Under-fetching:** Insufficient data being sent to an endpoint during an API call, which requires another call, is referred to as under-fetching. The response time of your application or website is prolonged by the addition of each supplementary API call, leading to an increase in precious processing time for every interaction.
  * **Dependent requests**: Dependency constraints are usually present in REST APIs that limit the combinations of two or more parameters to form valid API calls.
  * **Multiple round trips**: Multiple round trips in REST API refer to the need for a client to make multiple requests to the server to retrieve all the required data, instead of retrieving everything in a single request/response cycle. It's a process where the client requests data from the server in multiple trips, frequently requiring several iterations to complete the process.

## GraphQL vs REST

GraphQL is a newer technology than REST, but it is quickly gaining popularity. Here are some of the key differences between [GraphQL](https://graphql.org/) and REST:

* **GraphQL is a query language**, while **REST is an architectural style**.
* GraphQL allows you to request specific data, while REST returns all of the data that is available.
* GraphQL is more flexible than REST, but it can be more complex to implement.

[![Graph](https://i.imgur.com/ZkkEam3.jpg "GraphQL structure")](https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language)

Image source: [*Engineering at Meta*](https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language/)

For an even more in-depth comparison between GraphQL and REST architecture, please check out this post - [GraphQL vs REST: Differences, Similarities, and Why to Use Them](https://memphis.dev/blog/graphql-vs-rest-differences-similarities-and-why-to-use-them/).

## Getting Started with GraphQL

To get started with GraphQL, you will need to choose any of these methods of implementation:

1. [Using AWS AppSync: The Fully managed GraphQL Service](https://levelup.gitconnected.com/an-introduction-to-aws-appsync-the-fully-managed-graphql-service-9f429a664e2f)
2. [Open-source GraphQL libraries](https://hasura.io/blog/10-popular-open-source-graphql-projects-and-tools-you-have-to-try/)
3. Self-managed service in your web application

In this post, you will learn how to setup GraphQL locally:

To get started, install the following:

* **A [GraphQL server](https://graphql.org/code/#language-support)**: This is the software that will respond to GraphQL queries.
* **A [GraphQL client](https://graphql.org/graphql-js/graphql-clients/)**: This is the software that will send GraphQL queries to the server. A popular one is [Apollo Client](https://www.apollographql.com/docs/react/).

Once you have installed a GraphQL server and client, you can start writing GraphQL queries.

## Getting Started as a React Developer with GraphQL

In this article, I will quickly walk you through how to get started with GraphQL as a front-end developer. To quickly see what GraphQL looks like, take a look at the [GraphQL playground](https://graphqlpokemon.favware.tech/).

### The [GraphQL PlayGround](https://graphqlpokemon.favware.tech/)

[GraphQL playground](https://graphqlpokemon.favware.tech/) is an interactive web-based interface that allows developers to explore and test GraphQL APIs. It provides a user-friendly environment for executing queries, viewing results, and testing [mutations](https://graphql.org/learn/queries/#mutations). It also offers features such as auto-completion, error highlighting, and documentation to make it easier for developers to work with GraphQL APIs. The GraphQL Playground is commonly used during the development process to test and debug APIs before they are deployed to production.

[![GraphQL Playground](https://i.imgur.com/HKm7NOg.png)](https://graphqlpokemon.favware.tech/ "GraphQL Playground")

## Apollo Studio

[Apollo Studio](https://studio.apollographql.com/) is a web-based service for monitoring and managing your GraphQL APIs. With [Apollo Studio](https://studio.apollographql.com/), you can track your API performance, set up access controls, and version your schemas. It also comes with a built-in GraphQL Playground, so you can test your queries and mutations right from the browser. In this article, we'll take a look at how to install and get started with [Apollo Studio](https://studio.apollographql.com/).

### Use Apollo Client to Fetch Data in React

[Apollo Client](https://www.apollographql.com/docs/react/) is a JavaScript library that is used for managing the state of data in web applications. It is an [open-source](https://github.com/apollographql/apollo-client) GraphQL client that allows you to easily manage data in your applications by providing a simple and intuitive API. Apollo Client can be used with any JavaScript framework and is compatible with most modern browsers.

It is used for data handling, fetching, and caching in web applications. It provides a unified API for fetching data from multiple sources, including REST APIs, GraphQL APIs, and local data sources. With Apollo Client, you can easily manage the state of data in your application, including caching, pagination, and real-time updates.

To get started with Apollo Client, you need to install both the main Apollo Client dependency, as well as GraphQL:

```bash
npm install @apollo/client graphql
```

The primary idea of Apollo Client is to leverage its functionality across the entire application, accomplished by using a distinct `ApolloProvider` component, which passes the created Apollo client down the complete component hierarchy.

It is important to define the `uri` value, which represents a GraphQL endpoint, and to specify a cache when creating the Apollo Client. The in-memory cache of Apollo Client is utilized to locally store and regulate queries along with their pertinent data.

```js

// index.js

import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client";

import App from "./App";

const client = new ApolloClient({
  uri: "https://spacex-production.up.railway.app/",
  cache: new InMemoryCache()
});

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  rootElement
);
```

In the snippet above, I specified the `uri` as `https://spacex-production.up.railway.app/` which provides data about SpaceX and its past missions.

Once you've set up the Provider and client within your `App` component, you can use all of the different React hooks that Apollo Client gives you for all the different GraphQL operations. These include **queries**, **mutations**, and **subscriptions**. You can even use the created Apollo Client directly using a custom hook called `useApolloClient`.

Since you're just querying data here, you will use the `useQuery` hook.

You will include a GraphQL query as its first argument to write your query. You'll use the function `gql`, which does several things, such as giving you editor syntax highlighting and the auto-formatting functionality if you use the tool Prettier for your project.

Once you execute this query, you get back the values `data`, `loading`, and `error`:

```js

// App.js

import React from "react";
import { useQuery, gql } from "@apollo/client";

const FILMS_QUERY = gql`
  {
    launchesPast(limit: 10) {
      id
      mission_name
    }
  }
`;

export default function App() {
  const { data, loading, error } = useQuery(FILMS_QUERY);

  if (loading) return "Loading...";
  if (error) return <pre>{error.message}</pre>

  return (
    <div>
      <h1>SpaceX Launches</h1>
      <ul>
        {data.launchesPast.map((launch) => (
          <li key={launch.id}> {launch.id}: {" "} {launch.mission_name}</li>
        ))}
      </ul>
    </div>
  );
}
```

To ensure a smooth display of data and missions, it is important to manage the loading state beforehand. During the loading state, the query is fetched from the remote endpoint (the `uri` specified).

Any occurrence of errors should also be handled efficiently. For instance, errors can be simulated by creating a syntax error in the query, such as requesting a non-existent field. In such cases, returning and displaying a message from `error.message` can be quite convenient.

When you run the above app and navigate to `localhost:3000`, you should see a list of 10 recent Space launches and their ids, like so:

![Screenshot of app](https://i.imgur.com/e7o0vij.png)

## Other Resources to Accompany this Tutorial

This tutorial comes with an accompanying GitHub repository where the codes for the react-select-tutorial app that I built for this tutorial are hosted. I also included some additional YouTube video tutorials.

* [GitHub repo](https://github.com/Eunit99/graphql-app.git)
* [YouTube tutorial video](https://www.youtube.com/watch?v=Zg4XIpnLWQg)
* [Live site on Vercel](https://graphql-app-three.vercel.app)

## Other Methods of Fetching Data in React from a GraphQL API

* [Urql](https://formidable.com/open-source/urql/)
* [React Query](https://tanstack.com/query/v3/) + [GraphQL Request](https://www.npmjs.com/package/graphql-request)

## Conclusion

GraphQL is a powerful and flexible query language that can be used to improve the performance, flexibility, and scalability of your APIs. If you are looking for a way to improve your APIs, GraphQL is a great option to consider.

Follow me on [Twitter](https://twitter.com/eunit99) [@eunit99](https://twitter.com/eunit99) let's keep in touch 🚀

## Further Readings

* [An Introduction to GraphQL](https://www.digitalocean.com/community/tutorials/an-introduction-to-graphql)
* [5 Reasons to use GraphQL at Your Company](https://codersociety.com/blog/articles/graphql-reasons)
* [Basics Tutorial - Introduction to GraphQL](https://www.howtographql.com/basics/0-introduction/)
* [GraphQL: A data query language](https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language/)