Why Gatsby needs GraphQL?
Tags: react, gatsby, beginners, graphql
Published: 2021-03-15 09:12:43

This blog post is going to describe why Gatsby needs GraphQL and how it uses it.

If you read this post, you are probably already familiar with [Gatsby](https://www.gatsbyjs.com/docs/tutorial/) (React framework for generating static websites) and [GraphQL](https://www.howtographql.com/) (query language for web APIs). If you are not familiar with those, I strongly insist on learning those first (I added links to documentation on both of these technologies).

When I decided to build my portfolio using Gatsby, i didn't know that its not that easy :) Well, nothing is easy in a tech world, but I still hoped that if it's a framework and it uses React, i will have my portfolio built in no time. Well, nope. 

It appeared that for some reasons (which were unknown to me at the beginning), Gatsby uses GraphQL to make queries. That was what official documentation and tutorials told me. 
But it was still unclear WHY it uses GraphQL. So here Im trying to explore this question.

## How Gatsby is Managing Data

Gatsby framework is structured the way, that allows to build websites using all parts for that - HTML, CSS, JavaScript and data. The first 3 parts are covered by React, and the data is the rest what lives outside React component. 

It is possible to build a website using only React components and everything that is being put *inside* (texts, images etc.). But sometimes it's necessary to get data from *outside* the React component or to store it *outside* and then bring it *inside*. 

Gatsby’s data layer allows to **pull data** directly into the components from the following sources:
- WordPress
- filesystems (markdown, JSON etc.)
- headless CMS
- Drupal
- Netlify CMS
- APIs
- databases

## Gatsby and GraphQL: The Mechanism

**GraphQL** is a query language, which Gatsby is using to *pull* data to React components. It's absolutely *not necessary* to use GraphQL to source the data, there are [other ways](https://www.gatsbyjs.com/docs/how-to/querying-data/using-gatsby-without-graphql/) to do that. But because GraphQL is already configured for Gatsby framework and because it's same Facebook technology, it is recommended to use it for data sourcing. 

Now that we are figured out, WHY we use GraphQL here, let's see HOW exactly we use it. 

When we start the project with Gatsby, we can see our website at `localhost:8000` port. If we navigate to `localhost:8000__graphQL`, we will see all available queries for the website:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jb1yswdd04v18874ts90.png)

The names of the queries on the left are keywords for Gatsby to understand where to get data from. 

Alright, let's get to practice! let's consider that we have a Gatsby projects with 3 React components - Layout, Home and About. Both of them want to use the same `title` info. We can store this info in one location and reference that location from other files.

Below is **step-by-step guide** with an example of how to do that:

####1.Create React components:

src/components/layout.js
```react
import React from "react"
import { Link } from "gatsby"

export default function Layout({ children }) {
 return (
    <div>
      <Link to={`/`}>
        <h3> My Awesome Blog </h3>
      </Link>
      <Link to={`/about/`} > About </Link>
      {children}
    </div>
  )
}
```
src/pages/index.js
```react
import React from "react"
import Layout from "../components/layout"

export default function Home() {
  return (
    <Layout>
      <h1>Amazing Blog which Im creating with Gatsby</h1>
      <div>
        <img
          src="#"
          alt="Group of pandas eating bamboo"
        />
      </div>
    </Layout>
  )
}
```
src/pages/about.js
```react
import React from "react"
import Layout from "../components/layout"

export default function About() {
  return (
    <Layout>
      <h1>About My Awesome Blog</h1>
      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </p>
    </Layout>
  )
}
```

####2.Open *gatsby-config.js* file.
The place for common pieces of data is the `siteMetadata` object in the *gatsby-config.js* file. Add site title to this file:

```react
module.exports = {
  siteMetadata: {
    title: "My Awesome Blog"
  },
  plugins: [],
};
```

####3.Create the query
After we have added data to `siteMetadata` object, we can make the query with GraphQL to pull this data to the component which need it. 

To write the query, we will use `useStaticQuery`, a new Gatsby feature that provides the ability to use a React Hook to query with GraphQL at build time. Here we should pause and learn the difference between [the static query and the page query](https://www.gatsbyjs.com/docs/how-to/querying-data/static-query/#how-staticquery-differs-from-page-query) in case we are not familiar with this. 

Let's open `Layout.js` file, import GraphQL there and create a query which we save to `data` variable:

```react
import React from "react"
import { Link, graphql, useStaticQuery } from "gatsby"

export default function Layout({ children }) {

const data = useStaticQuery(
    graphql`
      query {
        site {  
          siteMetadata {
            title
          }
        }
      }
    `
 return (
    <div>
      <Link to={`/`}>
        <h3> My Awesome Blog </h3>
      </Link>
      <Link to={`/about/`} > About </Link>
      {children}
    </div>
  )
}
```
####4.Use the data inside the component
We have created a variable `data` and saved the result of the query in it. The keyword `site` in the query points Gatsby where to look for the data during the build. Gatsby sees **site** keyword, goes to *gatsby-config.js*, finds the object `siteMetadata`, pulls out `title` and stores it to variable `data`. 

Now all we need to do is to use `data` where we want it (in our case - instead of hard-coded `h3` tag:

```react
import React from "react"
import { Link, graphql, useStaticQuery } from "gatsby"

export default function Layout({ children }) {

const data = useStaticQuery(
    graphql`
      query {
        site {  
          siteMetadata {
            title
          }
        }
      }
    `
 return (
    <div>
      <Link to={`/`}>
        <h3> {data.site.siteMetadata.title} </h3>
      </Link>
      <Link to={`/about/`} > About </Link>
      {children}
    </div>
  )
}
```
Since our `Home` and `About` components are wrapped up with `Layout` component, the title will appear in every of them. 
If we decide to change the title, all we have to do is to change `siteMetadata` object property `title`. 

GraphQL is certainly not required, but the benefits of adopting GraphQL are significant. GraphQL will simplify the process of building and optimising pages, so it’s considered a best practice for structuring and writing Gatsby applications.

Thank you for reading my blog. Feel free to connect on [LinkedIn](https://www.linkedin.com/in/olenadrugalya/) or [Twitter](https://twitter.com/OlenaDrugalya) :)

<a href='https://ko-fi.com/J3J42JOOA' target='_blank'><img height='12' width=30% style='border:0px;height:12px;' src='https://cdn.ko-fi.com/cdn/kofi1.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>