Contact


Blog

Advantages of using TanStack Query with REST API in React.js

Posted by

Elavarasu S on 21 Mar 2024

1035
0

React.js has become one of the most popular JavaScript libraries for building user interfaces. Its flexibility and scalability have made it a go-to choice for many developers.

While REST APIs are widely used and have many benefits, there are some disadvantages, such as overfetching or underfetching, lack of real-time updates, complex state management, and overhead of multiple network requests, which affect user experiences when used with React.js.

When working with REST APIs, React developers are often challenged with managing data fetching, caching, and state management. Such problems can now be solved effectively with the help of TanStack Query (FKA React Query), a popular and powerful data fetching and state management library specifically designed for TS/JS, React, Solid, Vue, and Svelte applications. It simplifies the process of fetching, caching, updating, and synchronizing remote data.

 

Key features of TanStack Query

Before discussing how TanStack Query works with the REST API in React, let’s touch upon some of its key features.

Declarative API: TanStack Query provides a declarative API that allows developers to define data fetching and mutation operations using hooks and query keys, which makes it easy to fetch data and manage the state concisely and intuitively.

Background Data Refetching: TanStack Query supports background data refetching, ensuring that stale data is automatically updated in the background while still displaying the existing data. It provides a smooth user experience and keeps the application data up-to-date.

Query Invalidation and Refetching: TanStack Query allows developers to invalidate easily and refetch data based on events or triggers. For example, you can invalidate and refetch a query when a user submits a form or a specific event occurs, ensuring the data is always fresh and accurate.

Dev Tools and Debugging: TanStack Query offers a set of developer tools and debugging capabilities, providing insights into queries, caching, and network requests. These tools help identify performance bottlenecks and debug data-related issues.

 

Benefits of TanStack Query with REST API

We will explore the advantages of using TanStack Query with REST API in React.js and how it can streamline your development process.

Simplified Data Fetching

Fetching data from a REST API can involve handling complex scenarios such as pagination, filtering, sorting, and caching. TanStack Query simplifies this process by providing a declarative API that allows you to define your data-fetching logic using hooks. With TanStack Query, you can easily fetch, cache, and update data without dealing with the complexities of managing requests and responses manually. The following code fetches data using React-query:

 

// Data fetching using React-query
import { useQuery } from 'react-query';

const UsersList = () =>
  // Fetch user data using useQuery hook from React Query
  const { data, isLoading, error } = useQuery('users', () =>
    fetch('https://api.example.com/users').then((res) => res.json())
  );

  // Display a loading message while data is being fetched
  if (isLoading) {
    return <div>Loading...</div>;
  }

  // Display an error message if there is an error during data fetching
  if (error) {
    return <div>Error: {error.message}</div>;
  }

  // Display the Users List once data has been successfully fetched
  return (
    <div>
      <h1>User List</h1>
      <ul>
        {/* Map through the user data and display each user's name */}
        {data.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

 

Automatic Caching

Caching is crucial for improving performance and reducing unnecessary network requests. TanStack Query comes with built-in caching capabilities that automatically handle caching of API responses. It manages the cache by storing the fetched data and automatically updating it when necessary, eliminating the need for manual caching implementation and saving developers valuable time and effort.

import { useQueryClient, useQuery } from 'react-query';

const UserProfile = ({ userId }) => {
  // Access the queryClient, a React Query hook for managing queries
  const queryClient = useQueryClient();

  // useQuery hook to fetch user data from the API
  const { data, isLoading, error } = useQuery(['user', userId], () =>
    fetch(</`https://api.example.com/users/${userId}`).then((res) => res.json())
  );

  // If data is still loading, display a loading message
  if (isLoading) {
    return <div>Loading...</div>;
  }

  // If there's an error during data fetching, display an error message
  if (error) {
    return <div>Error: {error.message}</div>;
  }

  // Display the user data
  return (
    <div>
      <h2>{data.name}</h2>
      <p>Email: {data.email}</p>

      {/* Update the user data in the cache when a refresh button is clicked */}
      <button
        onClick={() => {
          // Invalidate the query in the cache, triggering a refetch
          queryClient.invalidateQueries(['user', userId]);
        }}
      >
        Refresh
      </button>
    </div>
  );
};

In the above example, React Query’s useQuery hook fetches user data, automatically storing it in a cache identified by the query key ([‘user’, userId]). It handles loading and error states, and a “Refresh” button triggers a fresh data fetch by clearing the cache for that specific user. This user-friendly approach simplifies data fetching in React, ensuring smooth performance and consistent data updates.

 

Efficient Data Management

Managing data in a complex React.js application can be challenging, especially when dealing with multiple components and states. TanStack Query introduces a powerful concept called ‘query invalidation’ that helps you manage data updates efficiently. It automatically detects changes to the underlying data. triggering a refetch or updating the cache accordingly, which ensures that your application always displays the latest data without any manual intervention.

 

Real-time Updates

In addition to efficient caching and data management, TanStack Query provides seamless integration with real-time updates. By combining TanStack Query with technologies like WebSocket or server-sent events, you can easily incorporate real-time data updates into your React.js application. This allows you to build dynamic and responsive applications that react to changes in the data source in real-time.

 
import { useQuery, useQueryClient } from 'react-query';
const RealTimeUpdates = ({ postId }) => {
  const queryClient = useQueryClient();
  const { data, isLoading, error } = useQuery(['post', postId], () =>
    fetch(`https://api.example.com/posts/${postId}`).then((res) => res.json())
  );
  // Subscribe to real-time updates using WebSocket
  useEffect(() => {
    const socket = new WebSocket('wss://api.example.com/ws');
    socket.onmessage = (event) => {
      const updatedPost = JSON.parse(event.data);
      // Update the post data in the cache when a new update is received
      queryClient.setQueryData(['post', postId], updatedPost);
    };
    return () => {
      socket.close();
    };
  }, [postId, queryClient]);
  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Error: {error.message}</div>;
  }
  return (
    <div>
      <h2>{data.title}</h2>
      <p>{data.content}</p>
    </div>
  );
};

 
Now, let’s have a look at how TanStack Query exemplifies efficiency by looking at examples with raw fetching versus with TanStack Query.

 

Fetch calls without TanStack Query

Here’s an example of making a fetch call without TanStack Query:

 
import React, { useEffect, useState } from 'react';

 
const UsersList = () => {
  // State to store the fetched users
  const [users, setUsers] = useState([]);

 
  // State to manage loading state
  const [isLoading, setIsLoading] = useState(true);

 
  // State to handle errors during data fetching
  const [error, setError] = useState(null);

 
  useEffect(() => {
    // Fetch data from the randomuser.me API
    fetch('https://randomuser.me/api/?results=500')
      .then((response) => response.json())
      .then((data) => {
        // Update the state with the fetched users
        setUsers(data);

 
        // Set loading to false as data has been successfully fetched
        setIsLoading(false);
      })
      .catch((error) => {
        // Handle errors by updating the error state and setting loading to false
        setError(error);
        setIsLoading(false);
      });
  }, []);

 
  // Display a loading message while data is being fetched
  if (isLoading) {
    return <div>Loading...</div>;
  }

 
  // Display an error message if there is an error during data fetching
  if (error) {
    return <div>Error: {error.message}</div>;
  }

 
  // Display the Users List once data has been successfully fetched
  return (
    <div>
      <h1>Users List</h1>
      <ul>
        {/* Map through the users array and display each user's title */}
        {users.map((user) => (
          <li key={user.id}>{user.title}</li>
        ))}
      </ul>
    </div>
  );
};

 
In the above example, without Tanstack Query, we manually manage the state, handle the loading and error states, and perform the fetch call in the `useEffect` hook. This approach requires more code and manual handling of data and error states.

 

Fetch calls with TanStack Query

Below is an example of making a fetch call with TanStack Query:

import { useQuery } from 'react-query';

 
const UsersList = () => {
  // useQuery hook to fetch users data
  const { data, isLoading, error } = useQuery('users', () =>
    fetch('https://randomuser.me/api/?results=500').then((response) => response.json())
  );

 
  // Display a loading message while data is being fetched
  if (isLoading) {
    return <div>Loading...</div>;
  }

 
  // Display an error message if there is an error during data fetching
  if (error) {
    return <div>Error: {error.message}</div>;
  }

 
  // Display the Users List once data has been successfully fetched
  return (
    <div>
      <h1>Users List</h1>
      <ul>
        {/* Map through the users array and display each user's title */}
        {data.map((user) => (
          <li key={user.id}>{user.title}</li>
        ))}
      </ul>
    </div>
  );
};

 
In the above example with TanStack Query, we use the `useQuery` hook to handle data fetching and caching automatically. TanStack Query abstracts away the loading and error states, as well as the caching mechanism. It simplifies the code and provides a more declarative approach to fetching data.

 

Conclusion

Using TanStack Query with REST API in React.js brings numerous advantages to your development workflow. From simplifying data fetching to providing automatic caching and efficient data management, TanStack Query streamlines the process of working with REST APIs. Real-time updates and developer-friendly features further enhance the overall development experience. By leveraging the power of TanStack Query, you can build highly performant and scalable React.js applications that handle data fetching and management effortlessly. Our Top React Development Services enable you build fast and intuitive applications. Get in touch with our experts to learn more about how to get the best performance from your applications.

 

References

Overview | TanStack Query Docs
React



Share On

Tags

Advantages of TanStack Query

react development

TanStack Query with REST API

Highlights

Download Blog

Download Blog

    Leave a Reply

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

    hire dedicated resource

    Talk to Our Experts

      Get in Touch with us for a Walkthrough