How to efficiently query and group Sanity articles by category?
Great question! You definitely don't need to make separate queries for each category. There's a much better approach that lets you fetch all articles in a single query and then group them by category on the client side.
The most efficient pattern is to fetch all articles once with their category information, then group them in your application code. Here's how:
*[_type == "article"] {
_id,
title,
slug,
category->{
_id,
title
}
}This single query gets all your articles with their category references resolved. Then in your JavaScript/TypeScript code, you can group them:
const articlesByCategory = articles.reduce((acc, article) => {
const categoryId = article.category._id;
if (!acc[categoryId]) {
acc[categoryId] = {
category: article.category,
articles: []
};
}
acc[categoryId].articles.push(article);
return acc;
}, {});Why this is better:
- Single network request - Much faster than 4+ separate queries
- Better caching - CDN can cache one response instead of multiple
- More efficient - The query engine processes one query plan instead of several
If you have a massive number of articles and need to optimize further, you could add filtering or pagination to the initial query, but for most use cases, fetching all articles and grouping client-side will be the fastest and simplest approach.
The key insight from GROQ query optimization best practices is that moving logic to a single efficient query is almost always better than multiple queries, and client-side grouping is essentially free compared to network overhead.
Show original thread4 replies
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.