React Query - Caching 🎯

beginner
16 min

React Query - Caching 🎯

Welcome to the React Query Caching tutorial! This lesson is designed to help you understand and master the caching mechanism in React Query. Let's dive in!

Introduction 📝

In this tutorial, we'll explore React Query's caching system, which helps you manage and optimize data fetching in your React applications. By the end of this lesson, you'll be able to use caching to improve performance and create smoother user experiences.

Why Caching is Important? 💡

  • Improves app performance by reducing network calls and data loading times
  • Enhances user experience by providing faster responses and smoother interactions
  • Helps manage concurrent data fetching and avoid multiple requests for the same data

React Query Caching Basics 📝

Query Objects 📝

At the heart of React Query are query objects, which represent data fetches. Query objects are created using the useQuery hook.

javascript
import { useQuery } from 'react-query'; function UserProfile() { const { data, isLoading, error } = useQuery('userProfile', fetchUserProfile); // ... }

In the above example, the useQuery hook creates a query object for the userProfile key. The fetchUserProfile function is responsible for fetching the user profile data.

Cache Key 📝

The cache key is a unique identifier for each query. It determines which data is cached and when to refetch data. The cache key can be a string, a function, or an object.

javascript
const { data, isLoading, error } = useQuery(['user', userId], fetchUserProfile);

In the example above, the cache key is ['user', userId], which represents the user with the specified userId.

Caching Mechanism 💡

React Query provides several caching strategies to manage data efficiently.

Stale-While-Revalidate (SWR) 💡

Stale-While-Revalidate is the default caching strategy in React Query. With SWR, the initial data is returned from the cache, and asynchronously, a new request is made to refetch the data. The new data replaces the stale data when it arrives.

javascript
import { useQuery } from 'react-query'; function UserProfile() { const { data, isLoading, isError } = useQuery('userProfile', fetchUserProfile); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error!</div>; return <div>{data.name}</div>; }

In the example above, the user profile data is initially loaded from the cache. If the data is stale, React Query will automatically refetch the data in the background without disrupting the user experience.

Stale-While-Fresh (SWF) 💡

Stale-While-Fresh is an optimistic caching strategy that returns the most recent data from the cache, but always refetches the data immediately. With SWF, the app may display stale data for a brief period, but it ensures that the data is always up-to-date.

javascript
import { useQuery, useQueryClient } from 'react-query'; function UserProfile() { const queryClient = useQueryClient(); const { data, isLoading, isError } = useQuery('userProfile', fetchUserProfile, { staleTime: 60 * 1000 // Cache data for 1 minute }); const refetchData = () => queryClient.refetchQuery('userProfile'); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error!</div>; return ( <> <div>{data.name}</div> <button onClick={refetchData}>Refetch Data</button> </> ); }

In the example above, the user profile data is loaded from the cache and immediately refetched using the refetchData function. The staleTime option determines how long the data should be cached before being considered stale.

Quiz

Quick Quiz
Question 1 of 1

What is the default caching strategy in React Query?

Wrapping Up 📝

By understanding and utilizing caching in React Query, you can build efficient, performant applications that provide a smooth user experience. In this lesson, we covered the basics of query objects, cache keys, and the caching mechanism, including Stale-While-Revalidate (SWR) and Stale-While-Fresh (SWF).

As you continue to learn and use React Query, remember to always prioritize performance and user experience. Happy coding! 🤖🚀