useStaticQuery
provides the ability to use a React Hook to query Gatsby’s GraphQL data layer at build time. It allows your React components to retrieve data via a GraphQL query that will be parsed, evaluated, and injected into the component.
useStaticQuery
is a React Hook. All the Rules of Hooks apply.
It takes your GraphQL query and returns the requested data. That’s it!
Basic exampleLet’s create a Header
component that queries for the site title from gatsby-config.js
:
useStaticQuery
hooks
One of the most compelling features of hooks is the ability to compose and re-use these blocks of functionality. useStaticQuery
is a hook. Therefore, using useStaticQuery
allows us to compose and re-use blocks of reusable functionality. Perfect!
A classic example is to create a useSiteMetadata
hook which will provide the siteMetadata
to be re-used in any component. It looks something like:
Then import your newly created hook, like so:
Differences between page queries & static queriesStatic queries differ from Gatsby page queries in a number of ways. For pages, Gatsby is capable of handling queries with variables because of its awareness of page context. However, page queries can only be made in top-level page components.
In contrast, static queries do not take variables. This is because static queries are used inside specific components, and can appear lower in the component tree. Data fetched with a static query won’t be dynamic (i.e. they can’t use variables, hence the name “static” query), but they can be called at any level in the component tree.
Static queries thus have these limitations:
useStaticQuery
does not accept variables (hence the name “static”), but can be used in any component, including pagesuseStaticQuery
in a filesrc
directory
useStaticQuery
must be used in files that are nested below your site’s top-level src
directory. For example:
useStaticQuery
works in these files:
<SITE_ROOT>/src/my-page.js
<SITE_ROOT>/src/components/my-component.js
useStaticQuery
does not work in these files:
<SITE_ROOT>/other-components/other-component.js
<SITE_ROOT>/other-library/other-component.js
Start building today on
Netlify!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4