DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

How to create custom hooks in Gatsby

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

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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>;
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)