Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 78

TanStack Query: Data Fetching, Caching, and Invalidation

Recommended resources

Hello! Let's build on our theoretical foundation from the last lesson and put TanStack Query into practice.

In our previous session, we established the "why" behind TanStack Query, differentiating between client and server state and outlining the core concepts of QueryClient, useQuery, and useMutation.

Today, we transition from theory to application. Our goal is to use TanStack Query to manage data fetching, caching, and invalidation. We will write the code to fetch data, handle its lifecycle, and ensure our UI stays perfectly in sync with the server after we make changes.

1. Fetching Data with useQuery

Let's start by replacing a traditional useEffect-based fetch with the useQuery hook. Recall from the last lesson that useQuery needs at least a queryKey and a queryFn.

Here's a typical component structure for displaying a list of posts:

// api.ts
import axios from 'axios';

export interface Post {
  id: number;
  userId: number;
  title: string;
  body: string;
}

export const fetchPosts = async (): Promise<Post[]> => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
// PostsList.tsx
import { useQuery } from '@tanstack/react-query';
import { fetchPosts } from './api';

function PostsList() {
  const { data, isPending, isError, error } = useQuery({
    queryKey: ['posts'],
    queryFn: fetchPosts,
  });

  if (isPending) {
    return <span>Loading...</span>;
  }

  if (isError) {
    return <span>Error: {error.message}</span>;
  }

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

This code is clean and declarative. We're not manually managing state with useState; we're simply describing our data dependency and letting TanStack Query handle the state transitions.

Queries | TanStack Query React Docs

The official documentation provides a clear breakdown of the states a query can be in. It's essential to understand these to build robust UIs.

Review this short section on query states. Notice the three primary states: pending, error, and success. TypeScript is smart enough to know that if isPending and isError are false, data must be available.


2. Caching and the staleTime Configuration

By default, TanStack Query is aggressive about keeping your data fresh. As soon as you fetch data, it's immediately considered stale. This means if you refocus the window or remount the component, TanStack Query will refetch the data in the background.

This is a powerful "stale-while-revalidate" strategy, but sometimes you don't need data to be that fresh. For data that doesn't change often (e.g., a list of countries), you can tell TanStack Query to consider it fresh for a longer period using the staleTime option.

TanStack Query - How to Master God-Tier React Query

This video provides an excellent visual explanation of the fresh vs. stale data concept and how staleTime influences it.

Watch from 02:44 to 06:39. Pay close attention to how the staleTime option prevents network requests for data that is still considered fresh. The video's cache visualization makes this concept very clear.

Let's modify our query to keep the posts data fresh for 5 minutes:

const { data, isPending, isError, error } = useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts,
  staleTime: 1000 * 60 * 5, // 5 minutes in milliseconds
});

Now, for 5 minutes after the data is fetched, TanStack Query will simply pull from the cache without making a network request, even if you remount the component or refocus the window. This is a fundamental performance optimization.


3. Mutations and Query Invalidation

Reading data is only half the story. What happens when we change it? This is where useMutation and query invalidation come together to create a seamless user experience.

Imagine we have a form to create a new post. After the POST request succeeds, our list of posts is out of date. We need to tell TanStack Query to refetch it.

TanStack Query - How to Master God-Tier React Query

The same video has a fantastic section demonstrating this exact scenario. It shows the problem (UI not updating) and the solution (invalidation).

Watch from 10:28 to 13:50. This demonstrates the core pattern of using useMutation and invalidateQueries to synchronize your UI after a data change. Notice how invalidation is what triggers the useQuery hook to refetch.

The process is:

  1. Get an instance of the queryClient.
  2. Define a mutation using useMutation.
  3. In the onSuccess callback of the mutation, call queryClient.invalidateQueries.

Here's what it looks like in code:

// AddPostForm.tsx
import { useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { Post } from './api';

const createPost = async (newPost: { title: string; body: string; userId: number }): Promise<Post> => {
  const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', newPost);
  return data;
};

function AddPostForm() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: createPost,
    onSuccess: () => {
      // Invalidate the 'posts' query to trigger a refetch
      console.log("Post created successfully! Invalidating posts query...");
      queryClient.invalidateQueries({ queryKey: ['posts'] });
    },
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const title = formData.get('title') as string;
    const body = formData.get('body') as string;
    mutation.mutate({ title, body, userId: 1 });
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form inputs for title and body */}
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? 'Creating...' : 'Create Post'}
      </button>
      {mutation.isError && <span>Error: {(mutation.error as Error).message}</span>}
    </form>
  );
}

When invalidateQueries({ queryKey: ['posts'] }) is called, TanStack Query finds all queries whose keys start with ['posts'], marks them as stale, and refetches them if they are active on the page. This elegantly and automatically updates our PostsList component.

Query Invalidation | TanStack Query React Docs

The official docs on Query Invalidation provide further detail on the flexibility of this API.

Read the sections "Query Invalidation" and "Query Matching with invalidateQueries". This will show you how you can invalidate queries with more precision, for example by matching an exact key or using a predicate function.

Test your understanding!

You have two queries in your application:

  1. A query to fetch all posts: useQuery({ queryKey: ['posts'], ... })
  2. A query to fetch a single post by its ID: useQuery({ queryKey: ['posts', postId], ... })

After a user edits and saves a post with id: 5, you want to refetch the data for that specific post and also refetch the entire list of posts. How would you configure invalidateQueries inside your onSuccess callback to achieve this?

Show answer

You would call invalidateQueries with the ['posts'] key.

onSuccess: (updatedPost) => {
  // This invalidates both ['posts'] and ['posts', 5]
  queryClient.invalidateQueries({ queryKey: ['posts'] });
}

Because invalidateQueries matches by prefix by default, passing ['posts'] invalidates all queries whose keys start with ['posts']. This includes ['posts'] itself and also ['posts', 5], ['posts', 10], etc. This single call efficiently achieves both goals.


4. Advanced: Manually Updating the Cache

Invalidation is great, but it still requires a network round-trip to get the updated data, which means the user might see a brief loading state. For an even faster experience, you can manually update the cache with the result of your mutation using queryClient.setQueryData.

This bypasses the need for an immediate refetch because you are telling TanStack Query, "I already have the newest data right here."

Learn React Query In 50 Minutes

Let's see a demonstration of how setQueryData can be used to manually populate the cache.

Watch from 36:49 to 39:04. The video shows how to use setQueryData to place the data from a successful mutation directly into the cache for a specific query key. This prevents a loading state when navigating to the page for the newly created item.

Here's how we could apply this to our createPost mutation to add the new post to our ['posts'] list immediately:

// ... inside the useMutation options
onSuccess: (newPost) => {
  // Option 1: Just invalidate (good)
  // queryClient.invalidateQueries({ queryKey: ['posts'] });

  // Option 2: Manually update the cache (better UX)
  queryClient.setQueryData(['posts'], (oldData: Post[] | undefined) => {
    // If oldData exists, add the new post to the beginning.
    // Otherwise, create a new array with the new post.
    return oldData ? [newPost, ...oldData] : [newPost];
  });
},

By using setQueryData, the UI updates instantly. You might still want to call invalidateQueries afterward to ensure the cache eventually syncs with the definitive server state, but the perceived performance for the user is immediate.

This pattern is a stepping stone to the next level of user experience: optimistic updates, which we will cover in our next lesson.


Conclusion

In this lesson, we bridged the gap from theory to practice. We've seen how to implement the full server state lifecycle using TanStack Query's powerful and declarative hooks.

Key Takeaways:

  • Fetching Data: useQuery simplifies data fetching by managing isPending, isError, and data states for you.
  • Caching Strategy: The staleTime option is your primary tool for controlling how long data is considered fresh, allowing you to optimize performance by avoiding unnecessary network requests.
  • Data Invalidation: The combination of useMutation, onSuccess, and queryClient.invalidateQueries is the standard pattern for keeping your client's view of server state synchronized after a create, update, or delete operation.
  • Manual Cache Updates: For an even faster user experience, queryClient.setQueryData allows you to update the cache directly with new data, eliminating the refetch loading state.

Preview of the Next Lesson:
Manually updating the cache on success is a fantastic improvement. But what if we could update the UI before we even know if the mutation was successful? In the next lesson, we will explore optimistic updates, a technique where we update the UI instantly as if the server request has already succeeded, providing the fastest possible perceived performance.