Tutorial

Quick Guide to Using Gatsby's useStaticQuery Hook

Published on December 4, 2019
author

Daniel Stout

Quick Guide to Using Gatsby's useStaticQuery Hook

The useStaticQuery React Hook was added to Gatsby.js starting with version 2.1.0, and it’s an incredibly convenient way to make (build-time) GraphQL queries from any component within a Gatsby site. In this quick lesson, we’ll go over how to implement useStaticQuery in your project!

Overview and Requirements

For this simple example, we’re going to add a ContactInfo component to our website. This will just be a re-usable component that fetches and displays some contact info from your Gatsby site’s siteMetadata configuration. Let’s get started!

This lesson only has one requirement: that you already have a Gatsby project set up, and you’re ready to edit along with me! If you need help getting to that point, just follow along with the intro tutorial in the Your First Steps with Gatsby v2 post, and then come back here.

Add Contact Info

To begin, let’s add some extra contact info to the siteMetadata object inside the gatsby-config.js file. To keep it simple, we will just add a phone number and an email address:

gatsby-config.js
siteMetadata: {
  title: "Gator's Empanada Express",
  siteUrl: "https://example-site.com/",
  phone: "(555) 567-0123",
  email: "info@example-site.com",
}
// plugins: { ... }

Create the Component

With our contact data in place, we just need to make a component that fetches and displays it. And of course, we’ll make use of the useStaticQuery Hook to do it!

Let’s create a new file at /components/ContactInfo.js, and then add the following code:

/components/ContactInfo.js
import React from "react";
import { useStaticQuery, graphql } from "gatsby";

const ContactInfo = () => {
  const data = useStaticQuery(graphql`
    query ContactInfoQuery {
      site {
        siteMetadata {
          phone,
          email
        }
      }
    }
  `);

  const { phone, email } = data.site.siteMetadata;

  return (
    <div>
      <h3>Contact Us:</h3>
      <p>phone: {phone}</p>
      <p>
        email: <a href={`mailto:${email}`}>{email}</a>
      </p>
    </div>
  )
};

export default ContactInfo;

See how simple this is? No confusing render props to deal with, and we’re making a GraphQL query within a non-page component! 🎉

You can now include this component anywhere on your site to display the contact info, and anytime you change these settings in siteMetadata they will update site-wide.

Note that this data does not have to come from siteMetaData! You could fetch data from any source where you would make a GraphQL query, such as fetching a list of recent blog posts, customer ratings, or upcoming product releases.

Exceptions

While useStaticQuery is incredibly useful, it currently has two limitations:

  • When using useStaticQuery, you cannot use variables within GraphQL queries. (It’s called useStaticQuery for a reason, after all! 😁) You still have to do those via page-level queries.

  • You can only use one instance of useStaticQuery per component. (But you can make several queries inside it! You could query siteMetadata, recent posts, and more all via one query/instance.)

Conclusion

As you can see, Gatsby’s built-in useStaticQuery Hook is an extremely useful and easy-to-use feature to incorporate into your Gatsby Toolbelt! I use it quite frequently, particularly for things like recent blog posts or product releases. (And yes, I have even used it for meta/contact info! 👍)

For more detailed info and examples, I recommend heading over to Gatsby’s official documentation on useStaticQuery. Like always, their docs are well-written and heavily maintained, so that page will always provide the most up-to-date information and examples!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Daniel Stout

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.