If you've ever found yourself tangled in the web of managing server state in your React applications, you know how challenging it can be. Thankfully, TanStack Query, formerly known as React Query, is here to simplify data fetching, caching, synchronization, and more in your React applications. The best part is it's easy to set-up.
Why TanStack Query
Simplified Data Fetching
TanStack Query abstracts away the complexities of data fetching and caching, allowing you to focus on building your application. It handles everything from caching to background updates and refetching on intervals, providing a powerful yet simple API.
Automatic Caching and Refetching
One of the standout features of TanStack Query is its ability to automatically cache and refetch data. This means your app will always have the latest data without you having to write additional code.
Synchronized Data
TanStack Query ensures your data is synchronized across your application, making it easier to manage and reducing the risk of stale data. It also provides tools for optimistic updates, background synchronization, and automatic retries.
Developer Experience
By combining TanStack Query's built in dev tools with the community package React Query Rewind, you'll receive insights into your queries, mutations, and cache. This helps in debugging and optimizing your data fetching strategies.
Getting Started
Installation
To get started with TanStack Query, you need to install the library:
npm install @tanstack/react-query
Install the dev tools as dev dependencies:
npm install -D react-query-rewind @tanstack/react-query-devtools
Install the React Query Rewind Chrome Extension.
Code
In your application, you need to set up the QueryClient and provide it to your application using the QueryClientProvider.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { ReactQueryRewind } from 'react-query-rewind';
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryRewind />
<ReactQueryDevtools initialIsOpen />
</QueryClientProvider>
);
Fetching Data with useQuery
Now, let's fetch some data using the useQuery hook. Here's an example of fetching user data from an API.
import { useQuery } from '@tanstack/react-query';
const fetchUser = async () => {
const response = await fetch('https://api.example.com/user');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
const UserComponent = () => {
const { data, error, isLoading } = useQuery(['user'], fetchUser);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
</div>
);
};
Mutations with useMutation
For performing mutations, such as creating or updating data, you can use the useMutation hook.
import { useMutation } from '@tanstack/react-query';
const createUser = async (newUser) => {
const response = await fetch('https://api.example.com/user', {
method: 'POST',
body: JSON.stringify(newUser),
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
const CreateUserComponent = () => {
const mutation = useMutation(createUser);
const handleSubmit = async (event) => {
event.preventDefault();
const newUser = {
name: event.target.elements.name.value,
email: event.target.elements.email.value,
};
mutation.mutate(newUser);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" placeholder="Name" required />
<input type="email" name="email" placeholder="Email" required />
<button type="submit">Create User</button>
</form>
);
};
Debugging
Once you've started your application, open the Chrome developer tools and click on the React Query Rewind tab. This tab will show a visual representation of your state data and allow you to see how this data is modified over time.
The other devtools will appear in the bottom half of your screen and show when state data is fresh or stale.
For a complete overview of TanStack query and these dev tools, check out the complete docs:
Top comments (3)
Thanks John. Im quite new in the dev space. I’ve started using tanstack query in my both vite and even next JS projects. I’m trying to establish a standard way of fetching and mutating data regardless of what JS framework or database I use. So far I’ve used it for basic fetching of data from simple APIs to even using it with supabase. Is what I’m aiming to do sensible? I’m open to any feedback - thanks! 🙏
Hi Marc - that all makes sense to me! All the tools I outlined here should work well in Vite and NextJS (though the exact name of the libraries you install for Vite will be slightly different).
I haven't used TanStack Query much in NextJS myself, but I'd look into TanStack Query's integration with Server Components since retrieving data directly from your database, without a server, is one of the biggest benefits of NextJS (and it's not too complicated to get started!). The docs go through this, but the integration between TanStack and NextJS Server Components may be overkill if you're starting out and working on smaller, personal projects. tanstack.com/query/latest/docs/fra...
Hope my 2 cents is helpful!
Very helpful!