DEV Community

Cover image for Day 13 of #100DaysOfCode — Understanding TanStack Query
M Saad Ahmad
M Saad Ahmad

Posted on

Day 13 of #100DaysOfCode — Understanding TanStack Query

TanStack Query is one of those libraries that instantly makes your life easier when working with server-side data. Whether you're fetching user info, working with dashboards, or building something real-time like a chat app, TanStack Query takes away a lot of the repetitive code we usually write in React.

Today, in my Day 13 of #100DaysOfCode, I dug deeper into TanStack Query — and here’s everything I learned, explained in a simple and practical way.


What Exactly Is TanStack Query?

TanStack Query (formerly React Query) is a powerful data-fetching and server-state management library.
Client state (local UI state) is easy to manage with things like useState and useReducer, but server state is completely different.

Server state:

  • Comes from a remote API
  • Needs data synchronization
  • May change without your UI knowing
  • Requires caching, refetching, invalidation, and often polling

TanStack Query handles all of these for you.


When Should You Use TanStack Query?

You should consider using it when your application needs to:

✔️ Fetch data from an API

TanStack Query gives you a clean, declarative way to fetch server data.

✔️ Avoid repetitive loading/error boilerplate

You don't need to manually handle isLoading, isError, or re-fetch logic.

✔️ Cache data efficiently

It automatically caches responses so your app doesn’t keep hammering your API with redundant requests.

✔️ Keep data fresh automatically

Background refetches ensure your UI always has up-to-date information.

✔️ Handle complex invalidation logic

This is especially useful when multiple components depend on the same API response.


Example: Fetching User Data With TanStack Query

Here's a simple example fetching user data:

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

function UserProfile() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user'],
    queryFn: () => fetch('/api/user').then(res => res.json())
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Hello, {data.name}!</div>;
}
Enter fullscreen mode Exit fullscreen mode

What’s happening here?

  • queryKey uniquely identifies this query
  • queryFn defines where the data comes from
  • useQuery automatically creates:

    • loading state
    • error state
    • caching logic
    • background refetching
    • retries
    • synchronization

All without you needing to write extra code.


🥴 Without TanStack Query (The Traditional Way)

If we try to do the same thing manually, the code becomes much more verbose:

function UserProfile() {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

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

This is manageable for one component…
But when your app grows, this becomes repetitive, hard to maintain, and error-prone.


A Real-Life Example: Chat App User Status

Imagine a chat application.

Only the server knows whether a user is:

  • online
  • offline
  • idle
  • typing

This information must come from the server and update regularly.

TanStack Query fits perfectly here because:

  • It can poll or refetch user status automatically
  • It handles real-time-like updates using refetch intervals
  • It keeps your UI in sync with your backend
  • It caches data so you don’t over-fetch
  • It prevents unnecessary re-renders

So instead of manually calling the API repeatedly, handling timers, errors, and caching — TanStack Query does it all for you.


Final Thoughts

TanStack Query is more than a data-fetching tool — it's a complete solution for managing server state in modern web applications. It removes boilerplate, improves performance through caching, and keeps your UI consistent with your backend data.

After exploring it, I can confidently say this is one of those libraries that instantly upgrades your workflow when working with React.

Happy coding!

Top comments (0)