Table of Contents
hello everyone
Home Web Front-end JS Tutorial How To Use TanStack (React Query)

How To Use TanStack (React Query)

Jul 20, 2024 am 08:48 AM

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)
}
Copy after login

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();
}
Copy after login

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>post</h1>
      <div>
        {isLoading ? (
          <div>Loading...</div>
        ) : (
          <div>
            <h3>{data.title}</h3>
            <p>{data.body}</p>
            <p>the number is {data.id}</p>
          </div>
        )}
      </div>
    </main>
  );
}
Copy after login

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);
},
Copy after login

});

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
</main>
Copy after login

);
}`

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles