Composing custom useStaticQuery hooks
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
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.
💰 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>
);
}
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>;
}
Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.
Never miss an article.