What is React-query, How is work React-query?
React-query is a library for React that provides simple, lightweight, and powerful tools for fetching, caching, and updating asynchronous data in React applications. It was designed to help developers build efficient and flexible data-fetching logic for their apps, with a focus on performance, ease of use, and robustness.
React-query allows you to declaratively fetch and cache data in your React components, using a simple and intuitive API. It provides automatic updates to your UI when the data changes, and makes it easy to handle loading, error, and re-fetching states. It also includes a powerful set of tools for managing and fine-tuning the caching and fetching behavior of your data, including the ability to cache data on the client or server, set expiration times, and control how data is invalidated and refetched.
React-query is often used in combination with REST APIs or GraphQL servers to fetch data from a backend, but it can be used with any asynchronous data source. It is a popular choice for building efficient, performant, and scalable data-fetching logic in modern React applications.
Here are some examples of using React Query to perform different HTTP operations:
GET
To perform a GET request using React Query, you can define a function that uses the fetch
function to send a GET request to an API endpoint, and pass this function to the useQuery
hook:
import { useQuery } from 'react-query';
function MyComponent() {
const { data, error, isLoading } = useQuery('key', () =>
fetch('https://my-api.com/endpoint').then(response => response.json())
)
if (isLoading) {
return <p>Loading...</p>
}
if (error) {
return <p>An error occurred: {error.message}</p>
}
return <div>{data.name}</div>
}
POST
To perform a POST request using React Query, you can define a function that uses the fetch
function to send a POST request to an API endpoint, along with the data you want to send in the request body. You can use the JSON.stringify
function to convert the data to a JSON string:
import { useMutation } from 'react-query';
function MyComponent() {
const [mutate, { error, isLoading }] = useMutation(
(data) =>
fetch('https://my-api.com/endpoint', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json()),
{
onSuccess: (data) => {
// do something on success
}
}
)
const handleSubmit = (event) => {
event.preventDefault()
mutate({ name: 'John' })
}
if (isLoading) {
return <p>Loading...</p>
}
if (error) {
return <p>An error occurred: {error.message}</p>
}
return <button onClick={handleSubmit}>Send POST request</button>
}
Here is the example of a PUT request using React Query that I previously provided:
import { useMutation } from 'react-query';
function MyComponent() {
const [mutate, { error, isLoading }] = useMutation(
(data) =>
fetch('https://my-api.com/endpoint/1', {
method: 'PUT',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json()),
{
onSuccess: (data) => {
// do something on success
}
}
)
const handleSubmit = (event) => {
event.preventDefault()
mutate({ name: 'John' })
}
if (isLoading) {
return <p>Loading...</p>
}
if (error) {
return <p>An error occurred: {error.message}</p>
}
return <button onClick={handleSubmit}>Send PUT request</button>
}
This example uses the useMutation
hook from React Query to perform a PUT request to the https://my-api.com/endpoint/1
endpoint, with the data { name: 'John' }
in the request body. The useMutation
hook returns a tuple with two elements: a mutate function that you can call to trigger the request, and an object with the error
and isLoading
status of the request.
You can use the error
and isLoading
variables to display an error message or a loading spinner while the request is being processed, and the onSuccess
option to specify a callback function that will be called when the request succeeds.
PATCH
To perform a PATCH request using React Query, you can define a function that uses the fetch
function to send a PATCH request to an API endpoint, along with the data you want to update in the request body. You can use the JSON.stringify
function to convert the data to a JSON string:
import { useMutation } from 'react-query';
function MyComponent() {
const [mutate, { error, isLoading }] = useMutation(
(data) =>
fetch('https://my-api.com/endpoint/1', {
method: 'PATCH',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json()),
{
onSuccess: (data) => {
// do something on success
}
}
)
const handleSubmit = (event) => {
event.preventDefault()
mutate({ name: 'John' })
}
if (isLoading) {
return <p>Loading...</p>
}
if (error) {
return <p>An error occurred: {error.message}</p>
}
return <button onClick={handleSubmit}>Send PATCH request</button>
}