Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท GraphQL Data Layer

Page Queries and useStaticQuery

Get data into Gatsby components with page queries, query variables from page context, the useStaticQuery hook and StaticQuery, and learn when to use each one.

Knowing the GraphQL language is half of the story. The other half is where you write a query so that its result reaches a component. Gatsby offers two main places: a page query, which belongs to a page and can use variables, and a static query, which belongs to any component but cannot take variables. Choosing the right one avoids most data-fetching confusion.

Real queries are read-only. Stand-ins model how results are delivered as props and as hook values.

Page queries

A page (a file in src/pages or a template component used by createPage) can export a constant named query containing a tagged graphql template. Gatsby runs it at build time and passes the result as the data prop:

JSX
// src/pages/blog.js (real Gatsby, read-only)
import * as React from "react"
import { graphql, Link } from "gatsby"

const BlogPage = ({ data }) => (
  <main>
    <h1>Blog</h1>
    <ul>
      {data.allMarkdownRemark.nodes.map((post) => (
        <li key={post.id}>
          <Link to={post.fields.slug}>{post.frontmatter.title}</Link>
          <span> {post.frontmatter.date}</span>
        </li>
      ))}
    </ul>
  </main>
)

export const query = graphql`
  query {
    allMarkdownRemark(sort: { frontmatter: { date: DESC } }) {
      nodes {
        id
        fields { slug }
        frontmatter { title date(formatString: "MMM D, YYYY") }
      }
    }
  }
`

export default BlogPage

Rules:

  • The export must be called query (any name works as long as the query is the graphql tag, but query is the convention) and Gatsby statically extracts it, so it cannot be built from variables or string concatenation.
  • Only top-level page components can have page queries. A child component cannot export one.
  • The result arrives as props.data.

Query variables from page context

Template pages created in gatsby-node.js pass a context object (creating pages). Every key becomes a GraphQL variable:

JSX
// src/templates/post.js (real Gatsby, read-only)
export const query = graphql`
  query ($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter { title }
    }
  }
`

If the page was created with context: { slug: "/espresso/" }, then $slug is "/espresso/". The same context object is also available as props.pageContext. A page query is the only way to query by a dynamic value, and this is why it matters.

useStaticQuery

Components that are not pages (a header, a SEO helper) cannot use page queries. They use the useStaticQuery hook:

JSX
// src/components/seo.js (real Gatsby, read-only)
import * as React from "react"
import { useStaticQuery, graphql } from "gatsby"

const useSiteMetadata = () => {
  const data = useStaticQuery(graphql`
    query {
      site { siteMetadata { title description siteUrl } }
    }
  `)
  return data.site.siteMetadata
}

export default useSiteMetadata

Limitations, and why they exist:

  • No variables. Gatsby replaces the hook call with the result at build time; there is nothing to vary.
  • One useStaticQuery per file is clearest. Gatsby allows several, but a custom hook like above is easier to reuse.
  • Cannot be called conditionally or outside React components and hooks.

The older <StaticQuery query={graphql...} render={data => ...} /> component does the same for class components. New code should use the hook.

Page query or static query?

Page query Only on pages, accepts variables
useStaticQuery Any component, no variables

Variables mean page query. Reusable shared data means static query.

1 / 2

Page query or static query: a decision table

Question Page query useStaticQuery
Needs $variables from page context Yes No
Can live in a small shared component No Yes
Result passed as props.data hook return value
Good for lists, post content, templates site title, menus, footer data
flowchart TD
  Q["Need data in a component"] --> V{"Depends on the page?"}
  V -->|"Yes, uses a variable"| P["Page query"]
  V -->|"No, same on every page"| S["useStaticQuery"]

Does the answer change per page? Then use a page query.

Stand-in: page queries deliver props

This stand-in is not Gatsby. A "runner" evaluates each page's query against the data and passes the result as data, together with pageContext, just like the build does.

JS Stand-in: query results become props

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: a static query hook

JS Stand-in: useStaticQuery in a shared component

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If you try to build a query with a template variable, such as graphql{ post(id: "${id}") }, the build fails: Gatsby extracts queries without running your code. Use a page query and $variables instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which query type accepts variables from page context?

    Page queries receive context keys as GraphQL variables.
  2. 2. Where does the result of a page query appear?

    Gatsby passes the result to the page component as the data prop.
  3. 3. Which is the right tool for a site title in a footer component?

    Shared components without variables use useStaticQuery.
  4. 4. Why can't you build a query by string concatenation?

    Queries are parsed at build time without running code, so they must be literal.

Summary

  • A page query is exported from a page and delivered as props.data.
  • Context keys from createPage become $variables in the page query.
  • useStaticQuery serves any component but cannot use variables.
  • Queries must be literal graphql templates; Gatsby extracts them statically.
  • Per-page data: page query; shared site data: static query.

Next: GraphiQL and the Data Layer