Cache Operations in React

From the TanStack Query cheat sheet · Cache Management · verified Jul 2026

Cache Operations

Working with the QueryClient cache

typescript
import { useQueryClient } from '@tanstack/react-query'

function CacheControls() {
  const queryClient = useQueryClient()

  // Invalidate queries
  const handleInvalidate = () => {
    // Invalidate all queries
    queryClient.invalidateQueries()

    // Invalidate specific queries
    queryClient.invalidateQueries({ queryKey: ['posts'] })

    // Invalidate with exact match
    queryClient.invalidateQueries({
      queryKey: ['post', 1],
      exact: true
    })
  }

  // Prefetch data
  const handlePrefetch = () => {
    queryClient.prefetchQuery({
      queryKey: ['post', 2],
      queryFn: () => fetchPost(2),
      staleTime: 1000 * 60 * 5
    })
  }

  // Direct cache manipulation
  const handleCacheUpdate = () => {
    // Set data directly
    queryClient.setQueryData(['user'], { name: 'John' })

    // Get cached data
    const cachedUser = queryClient.getQueryData(['user'])

    // Remove from cache
    queryClient.removeQueries({ queryKey: ['old-data'] })
  }

  return (
    <div>
      <button onClick={handleInvalidate}>Invalidate</button>
      <button onClick={handlePrefetch}>Prefetch</button>
      <button onClick={handleCacheUpdate}>Update Cache</button>
    </div>
  )
}
💡 Invalidation marks data stale and triggers refetch
⚡ Prefetch data before users need it for instant loading
📌 setQueryData for optimistic updates without server call
🟢 Use exact: true for precise cache key matching
cacheinvalidationprefetch
Back to the full TanStack Query cheat sheet