Static Queries
Learn how to use Gatsby's useStaticQuery hook to fetch data in non-page components.
We'll cover the following
Overview
We have learned how to fetch the data our page components need using an exported page query. Now, we look at how to fetch data for non-page components using GraphQL queries and the useStaticQuery
hook. Queries made this way are called component or static queries. They are called static because they do not accept variables, unlike page queries.
The useStaticQuery
hook
This hook is provided to us by Gatsby for calling static queries. Previously, this was done with the StaticQuery
component that accepts a query
prop for the query, and a render
prop for the JSX component to render. We will not be looking at this component. Starting from Gatsby v2.1.0
, we can now use the useStaticQuery
hook.
Usage
Let’s look at how we can use this hook in our application.
Note: We have an existing implementation of this hook in the
Footer
andSeo
components.
The first thing to note is that this is a React hook, and so can only be used in React function-based components. The second thing is that we must run on React and ReactDOM version 16.8.0
or later. We can upgrade our React and ReactDOM versions by running the command below:
Get hands-on with 1400+ tech skills courses.