Querying Data in Components using StaticQuery
Gatsby v2 introduces StaticQuery
, a new API that allows components to retrieve data via a GraphQL query.
In this guide, you’ll see an example using StaticQuery
, and learn about the difference between a StaticQuery and a page query.
How to use StaticQuery
in components
Video hosted on egghead.io.
Basic example
Here is an example of a Header
component using StaticQuery
:
By using StaticQuery
, you can colocate a component with its data. It is no longer required to, say, pass data down from Layout
to Header
.
useStaticQuery
There’s also a React hooks version of StaticQuery: check out the documentation on useStaticQuery
Typechecking
With the above pattern, you lose the ability to typecheck with PropTypes. To regain typechecking while achieving the same result, you can change the component to:
How StaticQuery differs from page query
StaticQuery can do most of the things that page query can, including fragments. The main differences are:
- page queries can accept variables (via
pageContext
) but can only be added to page components - StaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages
- StaticQuery does not work with raw React.createElement calls; please use JSX, e.g.
<StaticQuery />
Edit this page on GitHub