search
HomeWeb Front-endJS TutorialHow To Use TanStack (React Query)

In today modern web development, HTTP request is very crucial for applications, so the need for efficient data management becomes increasingly critical. This article will expose you to Tanstack, it`s key features and how to get started.

Tanstack

Tanstack is an amazing library for data management in applications, it addresses data management issues for asynchronous data operations. It helps developers to carryout HTTP requests easily.

What is HTTP request?

HTTP request (Hypertext Transfer Protocol) is usually a message sent by a browser to the server to initiate a communication and to request data or actions. HTTP is very important to the World Wide Web, it is a fundamental part of the web. Without it, we might not have applications.

HTTP request allows frontend applications to perform GET, POST, PUT, DELETE, PATCH etc actions on the server through an endpoint.

Benefits of using Tanstack

Caching and Data Synchronization: With built-in caching mechanisms, tanstack optimizes the performance of your application by storing data locally. This reduces the number of requests, which will make your application to be much faster.

Optimistic Updates: Tanstack facilitates optimistic updates, this enables developers to update the UI accordingly. It has amazing states like, the error, isLoading. You can use these to conditionally render a loading state while the data is loading.

Automatic Pagination and Infinite Loading: Handling large datasets becomes effortless with tanstack’s support for automatic pagination and infinite loading. Developers can seamlessly fetch and display data in chunks, enhancing application performance and user experience.
How to use Tanstack

First, we have to install tanstack by running npm i react-query on our terminal.

We have to inject the QueryClientProvider in our application so that we can be able to use Tanstack. We will also provide it with the queryClient as a prop. You can create this in the index.js file of your application.


import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import Nav from "./Nav";
import { BrowserRouter } from "react-router-dom";
import { QueryClientProvider, QueryClient } from "react-query";

const root = ReactDOM.createRoot(document.getElementById("root"));
const queryClient = new QueryClient();
root.render(








);

reportWebVitals();

How To Fetch Data With Tanstack

Now, we are going to fetch some data from an endpoint using Tanstack. We need to import useQuery from react-query (Tanstack).

import { useQuery } from "react-query";

Then we will destructure it and get the isLoading, data and the error states from it. These states will enable us to carryout the optimistic UI updates. This will enable us to conditionally render different UI based on the state of the data.


const id = useParams()
const { isLoading, data, error } = useQuery(["post", id.id], () =>
getSignleQueryFunc(id.id)
)

Then we have to pass a query, a query is a declarative dependency on an asynchronous source of data that is tied to a unique key. This query will help us to fetch data. In our case, we have an array of a string (post) an the id of each post. It doesn`t really matter, just make sure that it is unique.

Here is an example from the Tanstack documentation.

import { useQuery } from 'react-query'

function App() {
  const info = useQuery('todos', fetchTodoList)
}

Next, we have to include the query function, this query function enables us to fetch the data from an endpoint. In our case, we created our function in a separate file and imported it. Here is our query function

export async function getSignleQueryFunc(id) {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${id}`
  );
  return response.json();
}

This is the final result

import { useQuery } from "react-query";

import { getSignleQueryFunc } from "./getSignlePost";
import { useParams } from "react-router-dom";

export default function Posts() {
  const id = useParams();
  const { isLoading, data, error } = useQuery(["post", id.id], () =>
    getSignleQueryFunc(id.id)
  );

  if (error && data == undefined) return <p>Error fetching post</p>;

  return (
    <main>
      <h1 id="post">post</h1>
      <div>
        {isLoading ? (
          <div>Loading...</div>
        ) : (
          <div>
            <h3 id="data-title">{data.title}</h3>
            <p>{data.body}</p>
            <p>the number is {data.id}</p>
          </div>
        )}
      </div>
    </main>
  );
}

As you can clearly see how easy it is to use Tanstack (react query) to fetch data. You don`t need to use useStates anymore to determine the state of your data. In this example, we fetched single posts.

React query

Mutations

Mutations enables you to create, delete and update data. Tanstack has useMutation which you will use to create, delete and update data.

We have to pass the mutation function to the useMutation, and then supply the function with the necessary parameters for the specific mutation operation you want to perform. In our case, we will be updating the posts.

Here is how it is done
`
import { editPostFunc } from "./editPost";
import { useQuery, useMutation } from "react-query";
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { getSignleQueryFunc } from "./getSignlePost";

export default function UpdatePost() {
const id = useParams();
const { data } = useQuery(["post", id.id], () => getSignleQueryFunc(id.id));
const [title, setTitle] = useState("");
const [body, setBody] = useState("");

useEffect(() => {
if (data) {
setTitle(data.title || "");
setBody(data.body || "");
}
}, [data]);

const itemUpdate = useMutation(editPostFunc, {
onSuccess: () => {

  console.log("Post updated successfully");
},
onError: (error) => {

  console.error("Error updating post:", error);
},

});

const handleSubmit = (e) => {
e.preventDefault();
const updatedData = {
id: id.id,
title: title,
body: body,
userId: data.userId,
};
itemUpdate.mutate(updatedData);
};

return (

hello everyone



type="text"
placeholder="first input"
name="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
type="text"
placeholder="second input"
name="body"
value={body}
onChange={(e) => setBody(e.target.value)}
/>
click


);
}`

How To Use TanStack (React Query)

Here is how our editPostFunc looks like


export async function editPostFunc(updatedData) {
const res = await fetch(
https://jsonplaceholder.typicode.com/posts/${updatedData.id}`,
{
method: "PUT",
body: JSON.stringify({
id: updatedData.id,
title: updatedData.title,
body: updatedData.body,
userId: updatedData.userId,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
}
);
return res.json();
}
`

As you can see, we are fetching each post and storing the values in the useStates so that we can be able to edit them in the input fields. Once we are done editing it, we call the handleSubmit function. In this function, we are creating an object with the necessary property values, this includes the states we updated.

We will then send the object to the mutation function for the update. We also check if the edit was successful or not by console logging the result we are getting whenever we try to update a post.

You can clearly see how easy it is to carryout HTTP requests with Tanstack.

Difference between useQuery and useMutation

Use cases: useQuery is used to fetch data while useMutation is used for modifying data.

Conclusion

HTTP request is a very essential part of modern web development, it allow browsers to initiate a communication with a server to perform some actions like GET, POST, PUT, DELETE, PATCH etc. Tanstack on the other hand helps to make things easier for developers, it has some many benefits like optimistic UI updates, simplified data fetching etc.

I believe you have seen how easy it is to use Tanstack to handle HTTP requests and data management. Check out the Tanstack documentation here for more understanding and to explore other features of Tanstack.

Happy coding!

The above is the detailed content of How To Use TanStack (React Query). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools?How do I debug JavaScript code effectively using browser developer tools?Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

jQuery Matrix EffectsjQuery Matrix EffectsMar 10, 2025 am 12:52 AM

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of ​​the picture and uses jQuery to calculate the average color of each area. Then, use

How to Build a Simple jQuery SliderHow to Build a Simple jQuery SliderMar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

How to Upload and Download CSV Files With AngularHow to Upload and Download CSV Files With AngularMar 10, 2025 am 01:01 AM

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft