Caching Sanity client-side requests in Next.js without repeat calls
Great question! For client-side caching of Sanity queries in React/Next.js, React Query (now TanStack Query) is an excellent choice and commonly recommended in the Sanity community.
Here's why React Query works well for your use case:
Automatic Request Deduplication & Caching React Query will automatically cache your Sanity queries based on query keys. If you make the same query multiple times (like when a user toggles between selections), it'll serve the cached data instantly without hitting Sanity again.
Basic Implementation Example
import { useQuery } from '@tanstack/react-query'
import { client } from './sanityClient'
function useProducts(category, filters) {
return useQuery({
queryKey: ['products', category, filters], // Cache key based on user selections
queryFn: () => client.fetch(YOUR_GROQ_QUERY, { category, filters })
})
}Cache Persistence Across Next.js Page Transitions
React Query actually does persist cache across Next.js <Link> transitions by default! Since Next.js doesn't unmount the entire React tree during client-side navigation, React Query's cache stays alive. This gives you that bonus feature you mentioned.
Other Options to Consider
- SWR (by Vercel) - Similar to React Query but lighter weight. Also works great with Sanity
- Plain React state management - If your needs are simple,
useState+ a custom cache object could work
Important Note
The sanityFetch helper from next-sanity you might have seen is specifically for server-side caching in Next.js App Router. Since you're making client-side requests based on user interactions, React Query is the right tool for the job.
React Query also gives you nice loading states, error handling, background refetching, and tons of other features that make building interactive UIs much easier. Definitely worth checking out!
Show original thread1 reply
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.