DEV Community

Alex Spinov
Alex Spinov

Posted on

TanStack Query Has a Free Data Fetching Library That Replaces useEffect

TanStack Query handles caching, deduplication, background refresh, and optimistic updates. Stop writing useEffect for API calls.

The useEffect Problem

Every React developer writes this pattern:

const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  fetch('/api/users')
    .then(r => r.json())
    .then(setData)
    .catch(setError)
    .finally(() => setLoading(false));
}, []);
Enter fullscreen mode Exit fullscreen mode

No caching. No deduplication. No background refresh. No retry. No pagination. No optimistic updates.

TanStack Query solves ALL of this with one hook.

What You Get for Free

import { useQuery } from '@tanstack/react-query';

function Users() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['users'],
    queryFn: () => fetch('/api/users').then(r => r.json()),
  });
}
Enter fullscreen mode Exit fullscreen mode

This one hook gives you:

  • Caching — data stored by queryKey, shared across components
  • Deduplication — 10 components request same data → 1 fetch
  • Background refresh — stale data shows immediately, fresh data fetches in background
  • Retry — failed requests retry 3 times automatically
  • Window focus refetch — user tabs back → data refreshes
  • Garbage collection — unused cache entries are cleaned up

Mutations (Creating/Updating Data)

const mutation = useMutation({
  mutationFn: (newUser) => fetch('/api/users', {
    method: 'POST',
    body: JSON.stringify(newUser),
  }),
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['users'] });
  },
});

mutation.mutate({ name: 'Alice', email: 'alice@test.com' });
Enter fullscreen mode Exit fullscreen mode

After mutation succeeds → users list refetches automatically.

Works with Any Framework

TanStack Query supports: React, Vue, Svelte, Solid, Angular. Same API, different adapters.

DevTools

import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
// Add <ReactQueryDevtools /> to your app
Enter fullscreen mode Exit fullscreen mode

Visual panel showing all queries, their status, cache state, and timing.

If you're writing useEffect + useState for data fetching — you're reinventing what TanStack Query does better.


Need web scraping or data extraction? Check out my tools on Apify — get structured data from any website in minutes.

Custom solution? Email spinov001@gmail.com — quote in 2 hours.

Top comments (0)