Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

Setting Up TanStack Query

Setting Up TanStack Query

~13 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026

Raw fetch() calls in useEffect (EXACTLY as in chapter 8) scale POORLY – TanStack Query handles caching, refetching on window focus, and loading states, WITHOUT us having to manage that OURSELVES.

Setting up the QueryClient

src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
import './index.css';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000,
      retry: 1,
    },
  },
});

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
);

staleTime: 30_000 means: data counts as "fresh enough" for 30 seconds, WITHIN that time TanStack Query returns the CACHED value IMMEDIATELY, WITHOUT sending a new request.

The DevTools quick start

npm install @tanstack/react-query-devtools
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

// inside QueryClientProvider, NEXT TO <App />:
<ReactQueryDevtools initialIsOpen={false} />

A VISIBLE panel (ONLY in development mode, gets AUTOMATICALLY stripped for production builds) that shows EVERY query status, cache entry, and background refetch LIVE – INDISPENSABLE when debugging the coming chapters.

Why not Redux or Context for server data

TanStack Query solves a DIFFERENT problem than classic state management (Redux, useState+Context): SERVER data is NEVER truly "owned" by the client, it can change AT ANY TIME (even due to OTHER users, EXACTLY as shown in block 8) – TanStack Query CONSISTENTLY treats it as a "cached copy of remote state", not as local application state.

Tipp: For REAL client state (e.g. "is the mobile menu open?"), useState/Context REMAINS the RIGHT choice – chapter 76 uses Context EXACTLY for the auth state, which is NOT a server-data-fetching problem.