Next.js Course
Next.js
/
Intermediate

TanStack Query

Definition

Formerly known as React Query. The industry standard library for fetching, caching, synchronizing and updating SERVER state in React applications.

Explain Like I'm New

If you are fetching data in a Client Component (like an infinite scrolling feed), standard `fetch` is a nightmare. TanStack query handles loading states, error states, automatic retries, and background refetching perfectly.

Real World Example

A live sports scoreboard. TanStack query fetches the score, and automatically pings the server every 5 seconds in the background to silently update the UI without the user refreshing the page.

Common Use Cases

  • •Client-side data fetching
  • •Infinite scrolling
  • •Real-time UI sync

Interactive Example

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

// A standard fetch function
const fetchUser = async (id) => {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
};

export function UserProfile({ userId }) {
  // TanStack Query handles all the complexity!
  const { data, isLoading, isError } = useQuery({
    queryKey: ['user', userId], // The cache key
    queryFn: () => fetchUser(userId),
    refetchInterval: 5000, // MAGIC: Refetch in background every 5s!
  });

  if (isLoading) return <p>Loading spinner...</p>;
  if (isError) return <p>Error loading user!</p>;

  return <div>Welcome, {data.name}</div>;
}

Interview Questions

basic

  • What is the primary React hook provided by TanStack Query to fetch data?

intermediate

  • If Next.js has built-in fetching on the Server, why would you ever need TanStack Query?

Flash Cards

Question

Which hook?

Click to reveal answer
Answer

`useQuery`

Question

Why need it?

Click to reveal answer
Answer

Next.js server fetching is great for the *initial* page load. But if you need data to update *after* the page loads (like a user clicking a 'Load More Comments' button), you must fetch that data from the client. TanStack query makes client-fetching robust.