useSiteMetadata()

Note: This hook is intended for people who work with the Gatsby.js framework.

Gatsby v2 introduces StaticQuery, a new API that allows components to retrieve data via a GraphQL query.

Instead use StaticQuery everywhere in yours components, fetch static query in a custom hook to access it using only one-line in yours components.

In the following example, I need for example the sitename (AKA: title) in the header as well as in the footer, and surely I would like to display it elsewhere.

Of course you can use this trick with all data type, enjoy!

1// In gatsby-config.js
2module.exports = {
3 siteMetadata: {
4 title: `useHooks.ts`,
5 description: `Simple React hooks ready to use written in typescript.`,
6 siteUrl: `https://usehooks-typescript.com`,
7 author: `juliencrn`,
8 },
9}

The Hook

1import { graphql, useStaticQuery } from 'gatsby'
2
3export interface SiteMetadata {
4 title: string
5 description: string
6 siteUrl: string
7 author: string
8}
9
10function useSiteMetadata(): SiteMetadata {
11 const data = useStaticQuery(graphql`
12 {
13 site {
14 siteMetadata {
15 title
16 description
17 siteUrl
18 author
19 }
20 }
21 }
22 `)
23
24 // Return directly wanted data
25 return data.site.siteMetadata
26}
27
28export default useSiteMetadata

Usage

1import React from 'react'
2
3import useSiteMetadata from './useSiteMetadata'
4
5export default function Component() {
6 const { title } = useSiteMetadata()
7
8 return (
9 <header>
10 <h1>{title}</h1>
11 </header>
12 )
13}

See a way to make this page better?
Edit there »