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.
Video hosted on egghead.io.
Here is an example of a
Header component using
StaticQuery, you can colocate a component with its data. It is no longer required to, say, pass data down from
There’s also a React hooks version of StaticQuery: check out the documentation on
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:
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.