How to create custom hooks in Gatsby
© https://www.mariokandut.com

How to create custom hooks in Gatsby

Composing custom useStaticQuery hooks

ByMario Kandut

honey pot logo

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

How to use useStaticQuery hooks

Gatsby v.2.1.0 introduced a new feature that provides the ability to use a React Hook to query with GraphQL at build time - useStaticQuery.

It allows your React components to retrieve data via a GraphQL query that will be parsed, evaluated, and injected into the component.

Basic Example

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

This example is taken from the official Gatsby Docs. It shows an example of a Header component using the useStaticQuery hook.

import React from 'react';
import { useStaticQuery, graphql } from 'gatsby';
export default function Header() {
  const data = useStaticQuery(graphql`
    query HeaderQuery {
      site {
        siteMetadata {
          title
          siteUrl
          logo
        }
      }
    }
  `);
  return (
    <header>
      <h1>{data.site.siteMetadata.title}</h1>
    </header>
  );
}

Composing custom useStaticQuery hooks

The compelling feature of React hooks is that you can easily compose and re-use wherever you need this specific functionality. This feature is also possible with hooks in Gatsby and you get the ability to compose and re-use these blocks of functionality. useStaticQuery is a hook. Hence, we can compose and re-use blocks of functionality. 😎

Let's make a composition from the useSiteMetadata example above.

Create a folder and a file for the hook:

md hooks
cd hooks
touch use-site-metadata.js

Create the custom hook:

import { useStaticQuery, graphql } from 'gatsby';
export const useSiteMetadata = () => {
  const { site } = useStaticQuery(
    graphql`
      query SiteMetaData {
        site {
          siteMetadata {
            title
            siteUrl
            logo
          }
        }
      }
    `,
  );
  return site.siteMetadata;
};

Then just import your newly created hook:

import React from 'react';
import { useSiteMetadata } from '../hooks/use-site-metadata';
export default function Home() {
  const { title, siteUrl } = useSiteMetadata();
  return <h1>welcome to {title}</h1>;
}

Limitations

  • useStaticQuery does not accept variables (hence the name “static”)
  • Only a single instance of useStaticQuery can be used in a file. The reason for that is how queries in Gatsby currently work.

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

Scroll to top ↑