Data queries and response data are typical places where theme users may wish to override the default data in place. For instance, consider one of the most common queries issued by Gatsby: a query to fetch site metadata such as the site title and description. A theme can provide a default query that pulls from metadata the user set in the gatsby-config.js file of the site that is using the theme.
Gatsby themes allow the use of hooks to issue arbitrary static queries at any point in other code throughout the Gatsby site. For instance, here’s an example of a hook, useSiteMetadata
, that issues a static query (which doesn’t need a particular component type as it can be executed anywhere) to fetch the required information from the surrounding site’s Gatsby configuration file:
// gatsby-theme-minimal/src/hooks/use-site-metadata.js
import
{
graphql
,
useStaticQuery
}
from
"gatsby"
export
default
function
useSiteMetadata
()
{
const
data
=
useStaticQuery
(
graphql
`
{
site {
siteMetadata {
title
social {
twitter
github
instagram
}
}
}
}
`
)
return
data
.
site
.
siteMetadata
}
This hook can then be used in the context of other components within the theme, such as a shared header component that can also be accessed within the Gatsby site. Because we’ve used a static query, this hook could feasibly be used anywhere in our theme and on any site that has the theme installed:
// gatsby-theme-minimal/src/components/header.js
import
React
from
"react"
import
{
Link
}
from
"gatsby"
import
useSiteMetadata
from
"../hooks/use-site-metadata"
export
default
function
Header()
{
const
{
title,
social
}
=
useSiteMetadata()
return
(
<header>
<Link
to="/">{title}</Link>
<nav>
<a
href={`:
<a
href={
<a
href={`
</nav>
</header>
)
}
When we run gatsby develop
in the example folder, we can see the installed theme functioning correctly. These sorts of hooks can be used to override and provide defaults for a variety of data querying needs, allowing you to separate concerns between the data queries that drive your site as a whole and the unique rendering mechanisms you provide for the data you need.
Leave a Reply