NashTech Blog

Fetching and Caching API Data in React Using TanStack Query 

Table of Contents
tanstack logo

If you’ve ever managed API calls in React with useEffect and useState, you know it gets messy fast — loading states, error handling, and caching all over the place. 

That’s where TanStack Query (formerly React Query) comes in. It’s a simple tool that helps you fetch, cache, and sync data in React without the headaches. 

Let’s learn how to get started with it. 

What is TanStack Query? 

TanStack Query is a library that helps React apps talk to APIs more easily. It handles: 

  • Fetching data 
  • Caching responses 
  • Managing loading and error states 
  • Auto-refetching in the background 
  • Pagination and more 

And the best part? You don’t need to write any reducers or context. 

Step 1: Install the Package 

First, add it to your project: 

npm install @tanstack/react-query 

or if you’re using Yarn: 

yarn add @tanstack/react-query 

Step 2: Set Up the Query Client 

In your root file (like App.tsx or main.tsx), wrap your app with QueryClientProvider: 

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; 
 
const queryClient = new QueryClient(); 
 
function App() { 
 return ( 
   <QueryClientProvider client={queryClient}> 
     {/* Your app here */} 
   </QueryClientProvider> 
 ); 

 

This sets up the global client that handles all your queries. 

Step 3: Fetch Data with useQuery 

Let’s say you want to fetch a list of users from an API: 

import { useQuery } from '@tanstack/react-query'; 
 
function Users() { 
 const { data, isLoading, error } = useQuery({ 
   queryKey: ['users'], 
   queryFn: () => 
     fetch('https://jsonplaceholder.typicode.com/users').then((res) => 
       res.json() 
     ), 
 }); 
 
 if (isLoading) return <p>Loading...</p>; 
 if (error) return <p>Something went wrong!</p>; 
 
 return ( 
   <ul> 
     {data.map((user) => ( 
       <li key={user.id}>{user.name}</li> 
     ))} 
   </ul> 
 ); 

 

Done! You just made an API call with automatic caching and loading states handled for you. 

Step 4: Refetching and Background Updates 

TanStack Query also: 

  • Refetches data when the window regains focus 
  • Lets you manually refetch anytime 
  • Avoids duplicate API calls for the same query 

Example: 

const { data, refetch } = useQuery({ 
 queryKey: ['users'], 
 queryFn: fetchUsers, 
}); 
 
// Call refetch() when needed 
 

Bonus: Cached Data = Faster Apps 

TanStack Query automatically caches your API responses. This means: 

  • Your app loads faster 
  • Less API calls = better performance 
  • Offline support becomes possible with advanced config 

You Also Get… 

  • Built-in pagination 
  • Mutation support (for POST, PUT, DELETE) 
  • Devtools to inspect queries in your browser 

Conclusion

If you’re still using useEffect for data fetching, give TanStack Query a try. It’s simple, powerful, and saves you from writing a ton of boilerplate code. 

Whether you’re building a dashboard, blog, or e-commerce site, it just works — and lets you focus more on building features, not handling loading states.
Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency

Picture of Anuj

Anuj

As a skilled web developer, I specialize in React and Angular frameworks, proficiently utilizing various JavaScript libraries to create dynamic and seamless online experiences. My dedication to staying abreast of industry trends ensures that I deliver innovative solutions. With a focus on optimal user interfaces and functionality, I thrive in collaborative environments, bringing creativity and efficiency to web development projects. My expertise lies in crafting engaging digital solutions that align with the evolving landscape of web technologies. Let's embark on a journey of creating remarkable and user-centric online platforms.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top