DEV Community

Pramahadi Tama Putra
Pramahadi Tama Putra

Posted on • Edited on

Simplify Data Handling in React with TanStack Query and TypeScript!

If you're dealing with asynchronous data in React and TypeScript, you know how complicated managing fetching, caching, and all the other details can be. Luckily, there's a cool tool that can make your life easier: TanStack Query (formerly known as React Query). This article will show you how TanStack Query can make data management super simple and fun, complete with an example using TypeScript!

What Is TanStack Query?

TanStack Query is like a superhero for managing asynchronous data in JavaScript apps, especially React. With TanStack Query, you can handle async data in a much simpler way, letting you focus on your app’s logic instead of writing boilerplate code that can get pretty tedious.

Why Should You Try TanStack Query?

1. Easy Data Fetching
TanStack Query makes data fetching from APIs or other sources a breeze. Just use hooks like useQuery and useMutation, and it takes care of all the fetching, error handling, and loading states for you.

2. Automatic Caching That Saves Time
One of the coolest features of TanStack Query is automatic caching. It stores the data you fetch locally, so you don’t have to keep hitting the server. This makes your app faster and more responsive.

3. Hassle-Free Status Management
Forget about dealing with loading, error, or success states manually. TanStack Query handles all of this in a super straightforward way. You just focus on your business logic, and let TanStack Query take care of the rest.

4. Pagination and Infinite Query? Easy Peasy!
If your app needs to handle a lot of data, TanStack Query has built-in support for pagination and infinite queries. This means you can fetch data in chunks or endlessly with ease.

5. Optimistic Updates: Makes Your UI Snappy
TanStack Query also offers optimistic updates. This means your UI can update before the server has fully processed changes, making your app feel faster and more interactive.

Simple Example

Let’s dive into how to use TanStack Query in a React app with TypeScript. We’ll fetch user data from an API and display it in a component.

Step 1: Installation
First, install TanStack Query:

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

or

yarn add @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode

Step 2: Setup Provider
Add QueryClient and QueryClientProvider at the top level of your app:

// index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';

// Create a QueryClient instance
const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Step 3: Using useQuery in a Component
Here’s a component that fetches and displays user data:

// App.tsx
import React from 'react';
import { useQuery } from '@tanstack/react-query';

// Define the interfaces for the API response
interface Address {
  street: string;
  suite: string;
  city: string;
  zipcode: string;
  geo: {
    lat: string;
    lng: string;
  };
}

interface Company {
  name: string;
  catchPhrase: string;
  bs: string;
}

interface ApiResponse {
  id: number;
  name: string;
  username: string;
  email: string;
  address: Address;
  phone: string;
  website: string;
  company: Company;
}

// Define the user data type we want in our application
interface User {
  id: number;
  name: string;
  email: string;
  phone: string;
}

// Function to map the API response to our User interface
const mapApiResponseToUser = (apiResponse: ApiResponse): User => {
  return {
    id: apiResponse.id,
    name: apiResponse.name,
    email: apiResponse.email,
    phone: apiResponse.phone,
  };
};

// Function to fetch user data and map it to the User interface
const fetchUser = async (): Promise<User> => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  const apiResponse: ApiResponse = await response.json();
  return mapApiResponseToUser(apiResponse);
};

const App: React.FC = () => {
  // Use useQuery to fetch data
  const { data, error, isLoading } = useQuery<User, Error>(['user'], fetchUser);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Oops, there was a problem: {error.message}</div>;

  return (
    <div>
      <h1>User Info</h1>
      <p><strong>Name:</strong> {data?.name}</p>
      <p><strong>Email:</strong> {data?.email}</p>
      <p><strong>Phone:</strong> {data?.phone}</p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Conclusion

TanStack Query is an awesome tool for managing asynchronous data in React apps. With features like caching, easy status management, and support for pagination, TanStack Query makes data handling simpler and faster. Plus, if you use TypeScript, you get the added benefit of type safety and maintainable code. So, if you haven’t tried it yet, now’s the perfect time to upgrade your data management game with TanStack Query!

Top comments (0)