Getting Started with TanStack Query

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.

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.

Installation

To get started with TanStack Query, you need to install the library:

npm install @tanstack/react-query
Enter fullscreen mode
Exit fullscreen mode

Install the dev tools as dev dependencies:

npm install -D react-query-rewind @tanstack/react-query-devtools
Enter fullscreen mode
Exit fullscreen mode

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>
);
Enter fullscreen mode
Exit fullscreen mode

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>
 );
};
Enter fullscreen mode
Exit fullscreen mode

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>
 );
};
Enter fullscreen mode
Exit fullscreen mode

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:


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

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

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top