Q. React Query Package

npm i react-query
yarn add react-query

What is React Query?

React Query is a JavaScript library that provides a powerful and flexible way to manage and fetch data in React applications. It simplifies the process of making asynchronous API calls, caching, and synchronizing data, and provides built-in functionality for handling loading, error, and refetching states. React Query is commonly used alongside React to enhance the data fetching and management capabilities of React applications.

Initial Setup for React Query

import React from 'react';
import {Route, Routes, Link} from 'react-router-dom';
import {ReactQueryDevtools} from "react-query/devtools";
import {QueryClientProvider,QueryClient} from "react-query";
import './App.css';
import {HomePage} from './components/Home.page';
import {SuperHeroesPage} from './components/SuperHeroes.page';
import {RQSuperHeroesPage} from './components/RQSuperHeroes.page';
import {Navigation} from "./components/Navigation";
const queryClient = new QueryClient();
function App() {

    return (
        <QueryClientProvider client={queryClient}>
        <div>
            <Navigation/>
            <Routes>
                <Route path='/' element={<HomePage/>}/>
                <Route path='/super-heroes' element={<SuperHeroesPage/>}/>
                <Route path='/rq-super-heroes' element={<RQSuperHeroesPage/>}/>
            </Routes>
        </div>
            <ReactQueryDevtools initialIsOpen={false} position={"bottom-right"}/>
        </QueryClientProvider>
    );
}

export default App;

How to use React Query in component

import {useQuery} from "react-query";
import axios from "axios";

const fetchSuperHeroes = () => {
    return axios.get('<http://localhost:4000/superheroes>')
}

export function RQSuperHeroesPage() {
    const {isLoading, isFetching, data, isError, error} = useQuery("super-heroes", fetchSuperHeroes)
    if (isLoading) {
        return <h2>Loading...</h2>
    }
    if (isError) {
        return <h2>{error.message}</h2>
    }
    return (
        <>
            <h1>RQ Superheroes Page</h1>
            {data?.data?.map((hero) => {
                return <div key={hero.name}>{hero.name}</div>
            })}
        </>
    )

React Query Devtools

React Query Devtools is a browser extension that provides a graphical interface for debugging and inspecting the state of React Query in your application. It allows you to monitor the queries being made, view their status, and inspect the cached data. With React Query Devtools, you can easily track and analyze the data fetching and caching process, helping you debug issues and optimize your React Query implementation.

How the React query devtools look.

How the React query devtools look.

React Query Cache

React Query Cache is a built-in caching system provided by React Query. It allows you to store and manage the data fetched by your queries in memory. The cache acts as a centralized data store that can be accessed and updated from different components in your application. By utilizing the cache, React Query can intelligently handle data synchronization and re-fetching, reducing unnecessary network requests and improving performance.

const { isLoading, isFetching, data, isError, error } = useQuery(
  "super-heroes",
  fetchSuperHeroes,
  {
    cacheTime: 5000,
  }
);

Stale Time

Stale time in React Query is the time duration in milliseconds that determines how long the cached data is considered valid or "fresh" before it is considered stale. When the data is stale, React Query will automatically refetch the data from the server in the background. By setting a longer stale time, you can reduce the frequency of unnecessary network requests and improve the performance of your application.

const { isLoading, isFetching, data, isError, error } = useQuery(
  "super-heroes",
  fetchSuperHeroes,
  {
    staleTime: 30000,
  }
);

The data holds for 30 seconds and reduces the network request. The default stale time is 0 seconds.

The data holds for 30 seconds and reduces the network request. The default stale time is 0 seconds.

Refetch on Mount

Refetch on Mount is a feature in React Query that automatically triggers a data refetch when a component is mounted or rendered. It ensures that the most up-to-date data is fetched and displayed when the component is initially loaded. This feature is useful when you want to ensure that the data is always fresh and reflects the latest changes from the server without requiring any additional user interactions.