Best practices for using Sanity, Gatsby, and Netlify together
Great question! The good news is you don't need to worry about making hundreds or thousands of API calls with the Gatsby + Sanity setup. Gatsby is indeed "smarter" than that, and here's how it actually works:
How gatsby-source-sanity Actually Works
The gatsby-source-sanity plugin only makes two API requests during the entire build process, regardless of how many GraphQL queries you have in your components. Here's what happens:
- First request: Fetches the GraphQL schema definitions from Sanity's deployed GraphQL API
- Second request: Streams all accessible documents from your Sanity project using the export endpoint
This data is then loaded into Gatsby's local GraphQL data layer (an in-memory datastore). All your page queries, static queries, and component queries are executed against this local data layer at build time—not against Sanity's API.
The Answer to Your Question
You don't need to fetch everything at the top and pass it down through props. In fact, that's not the Gatsby way! Instead:
- Use page queries in your page components to fetch the specific data each page needs
- Use
useStaticQueryorStaticQueryin your regular components for component-specific data - Each query executes against Gatsby's local data layer (no additional API calls)
The only limitation is that useStaticQuery and StaticQuery cannot accept variables—they must be static queries. If you need variables (like getting data based on a page slug), use page queries instead.
Best Practices
For the Gatsby + Sanity + Netlify stack:
- Let each page/component query exactly what it needs
- Don't worry about "over-querying"—it's all local after the initial source
- Use page queries when you need dynamic data based on URL params
- Use
useStaticQueryfor static component data (like site metadata, navigation, etc.) - Enable
watchMode: truein development for real-time content updates without rebuilding
The plugin architecture is specifically designed to be efficient, so embrace Gatsby's data layer rather than trying to work around it!
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.