A Beginner’s Guide to TanStack Query with Examples
If you're a React developer looking for a better way to handle API calls, caching, background updates, and more — TanStack Query (formerly known as React Query) is your new best friend. This guide will help you get started with TanStack Query and provide some easy-to-follow examples.
A Beginner’s Guide to TanStack Query with Examples
If you're a React developer looking for a better way to handle API calls, caching, background updates, and more — TanStack Query (formerly known as React Query) is your new best friend. This guide will help you get started with TanStack Query and provide some easy-to-follow examples.
🌐 What is TanStack Query?
TanStack Query is a powerful data-fetching and state management library for React, Vue, Solid, and other frameworks. It helps you:
Fetch, cache, and update data efficiently
Automatically refetch in the background
Handle loading, error, and success states
Reduce boilerplate code for data fetching
For React developers, TanStack Query eliminates the need to manually manage state with useState
, useEffect
, and axios
everywhere.
🚀 Why Use TanStack Query?
Simplified Data Fetching: Clean hooks instead of repetitive logic
Auto Caching: Saves API results and reduces unnecessary calls
Auto Background Refresh: Keeps UI data fresh
Built-in Devtools: Inspect queries and states
Pagination & Infinite Scrolling Support
Prefetching & Mutation Handling
🔧 Installation
First, install TanStack Query:
npm install @tanstack/react-query
Add the Query Client Provider in your app root:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourRoutesOrApp />
</QueryClientProvider>
);
}
📃 Basic Example: Fetching Data
Let’s fetch a list of users from an API:
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchUsers = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/users');
return data;
};
function Users() {
const { data, isLoading, isError } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
});
if (isLoading) return <p>Loading...</p>;
if (isError) return <p>Error fetching users</p>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
✉️ Mutations: Posting Data
import { useMutation, useQueryClient } from '@tanstack/react-query';
const addUser = async (newUser) => {
const { data } = await axios.post('/api/users', newUser);
return data;
};
function AddUserForm() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: addUser,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries(['users']);
},
});
const handleSubmit = () => {
mutation.mutate({ name: 'Ashish' });
};
return <button onClick={handleSubmit}>Add User</button>;
}
⌛ Query Invalidation & Refetching
You can manually invalidate queries to refetch updated data:
queryClient.invalidateQueries(['users']);
This is helpful after mutations or external updates.
🧰 DevTools
Install the devtools for better debugging:
npm install @tanstack/react-query-devtools
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourRoutesOrApp />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}
🌟 Conclusion
TanStack Query makes data fetching in React apps efficient, scalable, and easy to manage. Whether you're building a blog, job portal, or e-commerce site, it removes much of the manual effort from working with remote data.
Give it a try in your next project, and you'll never want to go back to useEffect
spaghetti code!
Written by Ashish Kamat
Developer, learner, and builder from Nepal
Article Summary
This article covers building scalable React applications with TypeScript, including project structure, component patterns, state management, performance optimization, and testing strategies.
Tags
Get the latest articles and tutorials delivered to your inbox.
Subscribe Now