What is React Query and how does it simplify data fetching

· Category: React

Short answer

TanStack Query (formerly React Query) manages server state by providing hooks like useQuery and useMutation that handle caching, deduping, and background refetching automatically.

How it works

You define a query function that returns a promise. The library caches results by key, refetches on window focus, and keeps stale data visible while fetching fresh data in the background.

Example

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

function Posts() {
  const { data, isLoading } = useQuery({
    queryKey: ['posts'],
    queryFn: fetchPosts,
  });

  if (isLoading) return <p>Loading...</p>;
  return <ul>{data.map(post => <li key={post.id}>{post.title}</li>)}</ul>;
}

Tips

  • Keep query keys consistent and predictable.
  • Use staleTime and cacheTime to balance freshness with server load.
  • Combine with React Query Devtools to inspect cache state.