Beginners Guide for React Query Library

Spread the love

Introduction

A full-stack application can only be considered complete when its components can exchange data. Being a full-stack app, it should be capable of performing Create, Read, Update, and Delete (CRUD) operations. The most significant factor in a full-stack application is the capability to exchange data, which can be done in multiple ways, such as using theFetch API”, creating your own custom “useFetch hook, utilizing the “Axios library”, and more. “React Query” is a library that can help you in implementing CRUD operations in your React application, enabling you to manage state, synchronization, caching, and error handling efficiently.

What is the React Query library? 

React Query is a popular open-source library that simplifies data fetching and management in React applications. It provides a set of hooks and utilities that allow you to easily query, cache, and update data from various sources, such as REST APIs, GraphQL APIs, and web sockets.

React Query is designed to be flexible and scalable, allowing you to handle complex data requirements with ease. It provides features like caching, pagination, optimistic updates, and more, which can help you optimize your application’s performance and user experience.

One of the key benefits of React Query is its ability to manage and update data in real-time. It provides a flexible and efficient data synchronization mechanism that enables your application to respond to changes in the data source as they happen, without requiring a full page reload.

Overall, React Query is a powerful tool that can help you simplify and streamline data management in your React applications, allowing you to focus on building great user experiences.

 

key features:

 

  1. Data fetching: React Query provides an easy-to-use API to fetch data from various sources such as REST APIs, GraphQL endpoints, and more. It also supports several data fetching options like polling, caching, and deduplication.

 

  1. Caching: React Query has an intelligent caching system that caches data and automatically updates it when changes occur. This ensures that data is always up-to-date and reduces the number of network requests.

 

  1. Global state management: React Query provides a global store to manage data that can be accessed across components. This makes it easier to share data between components without passing props down through the component tree.

 

  1. Error handling: React Query provides error handling out of the box, making it easy to handle errors and display error messages to users.

 

  1. Pagination: React Query supports pagination and infinite scrolling, making it easier to handle large datasets.

 

  1. Automatic query management: React Query automatically manages queries, so developers don’t have to worry about canceling or debouncing requests.

 

  1. Server-side rendering: React Query has support for server-side rendering, making it easier to render data on the server before sending it to the client

 

Why use React Query?

There are several reasons why you might want to use React Query:

 

  1. Improved performance: React Query’s caching and data fetching capabilities can greatly improve the performance of your application by reducing the number of unnecessary network requests and minimizing the amount of time it takes to load and display data.

 

  1. Simplified data management: With React Query, you can easily manage complex data dependencies and handle the various states of data (loading, error, success) in a simple and intuitive way.

 

  1. Real-time updates: React Query supports real-time data updates through mechanisms like polling, caching and subscriptions, allowing your app to stay up-to-date with the latest data without needing to refresh the page.

 

  1. Integration with other libraries: React Query can be easily integrated with other libraries like Redux, Apollo Client, and Axios, making it a versatile tool for managing data in any React-based application.

 

  1. Developer Experience: React Query has a great developer experience, it has a small API surface that is easy to use and intuitive to reason about, providing clear feedback during development, and it also has great documentation, allowing you to get up and running quickly.

 

Getting started with React Query

  • Installation and setup:

 

To use React Query in your React application, you need to first install it as a dependency. You can do this by running the following command in your terminal:

 

npm install react-query

# or

yarn add react-query

 

Once you’ve installed React Query, you can import it in your application like this:

 

import { QueryClient, QueryClientProvider } from ‘react-query’

  • Creating a query client:

 

To set up React-Query in a React app, it is necessary to wrap the App.js component within the “QueryClientProvider” component from React-Query. This will provide access to all the hooks from react-query, as all data fetching will be performed there.To start, we will replace our *index.js* file with the below code:

 

import React from ‘react’;

import ReactDOM from ‘react-dom/client’;

import ‘./index.css’;

import App from ‘./App’;

import reportWebVitals from ‘./reportWebVitals’;

import { QueryClient, QueryClientProvider } from ‘@tanstack/react-query’ ;

const queryClient = new QueryClient();

const root = ReactDOM.createRoot(document.getElementById(‘root’));

root.render(

 <React.StrictMode>

   <QueryClientProvider client= {queryClient}>

   <App />

   </QueryClientProvider>

 </React.StrictMode>

);

reportWebVitals();

 

After setting up the development area, clear the returned JSX in “App.js”

 

import ‘./App.css’;

function App() {

 return (

   <div className=“App”>

<h1> React Query</h1>

   </div>

 );

}

export default App;

  • Fetching data:

 

To fetch data from an API, we will follow these steps, where we use the “use-query” hook from React Query. This function replaces the traditional use of the useEffect hook in React for data fetching. If you have experience with data fetching in React, you may be familiar with the useEffect hook, which can retrieve data and refresh the page. However, React Query differs in that it first returns the previously retrieved data and then proceeds to re-fetch the data.

 

const { isLoading, isFetching, error, data, status } = useQuery();

 

This makes our code a lot simpler and easy to maintain, as aforementioned. We will fetch a list of names from a public API (JSONPLACEHOLDER) by using Axios. We need to follow these steps:

 

  • Create a FetchApi.js file, where you will create an Asynchronous function that fetches the data from the base URL using Axios, then we export and import it into our main App.js
  • Use React Query to make API calls. First, we import UseQuery from React-query; here is how we use it in our component

 

const { isLoading, isFetching, error, data, status } = useQuery();

 

The isLoading displays while the Async-function runs, and we throw an error if there is one. The useQuery() will return two arguments, the first one is a unique key to differentiate what is being fetched from our API, and the second is Async-function from our “FetchApi.js”

 

  • Return a response: the data (names of users)
  • Inside the JSX, we return a list of names by mapping through the users

 

//FetchApi.js

import axios from “axios”;

async function Fecthapi() {

   const { data } = await axios.get(‘https://jsonplaceholder.typicode.com/users’)

   return data

}

  

export default Fecthapi;

 

//App.js

import ‘./App.css’;

import{useQuery} from‘@tanstack/react-query’;

import Fecthapi from ‘./Components/Fetchapi’;

import Form from ‘./Components/Form’;

function App() {

 const {data, error, isError, isLoading} = useQuery([‘users’], Fecthapi);

 if (isLoading) {

   return  <div> Loading </div>

 }

 if (isError){

   return <div> Error! + {error.message} </div>

 }

 return (

   <div className=“App”>

<table>

       <tr>

         <th>Name</th>

         <th>User Name</th>

         <th>Email</th>

       </tr>

       {data.map((users, id) => {

         return (

           <tr users={users}>

             <td>{users.name}</td>

             <td>{users.username}</td>

             <td>{users.email}</td>

           </tr>

         )

       })}

     </table>

     

   </div>

 );

}

export default App;

 

This is what we get after fetching data:

 

Supposedly, if we take off the *fetchpost* from amongst the arguments passed in useQuery, we will get an error; this shows the error was also cached.

Updating server data using the useMutation hook

 

  • We will need to create a component called Form.js

 

  • We will use the useMutation() hook, which returns an isLoading, error, and mutate function that will be used to make requests and enfold values while requests are made. It also has an Asynchronous function as an argument. The isLoading and error handle the mutation function as they are displayed during the API call process.

 

 

  • We will import the useState() hook to update the state of the input elements.

 

import { useState } from “react”;

import { useMutation} from “@tanstack/react-query”;

import axios from “axios”;

function Form(id, data) {

 const [name, setName] = useState(“”);

 const [username, setUsername] = useState(“”);

 const [email, setEmail] = useState(“”);

 const { mutate, isLoading } = useMutation

   (newUser) =>

     axios.post(“https://jsonplaceholder.typicode.com/users”, newUser),

   {

     onSuccess: (data) => {

       console.log(“New user added successfully!”, data);

     },

   }

 );

 const handleSubmit = (e) => {

   e.preventDefault();

   const newUser = {

     name,

     username,

     email,

    

   };

   mutate(newUser);

 };

 return (

   <form onSubmit={handleSubmit}>

     <label>

       Name:

       <input type=“text” value={name} onChange={(e) => setName(e.target.value)} />

     </label>

     <label>

       Username:

       <input type=“text” value={username} onChange={(e) => setUsername(e.target.value)} />

     </label>

     <label>

       Email:

       <input type=“email” value={email} onChange={(e) => setEmail(e.target.value)} />

     </label>

    

     <button type=“submit” disabled={isLoading}>

       Add New User

     </button>

   </form>

 );

}

export default Form;

 

We can now import this component to our main App.js component.

 

import ‘./App.css’;

import{useQuery} from‘@tanstack/react-query’;

import Fecthapi from ‘./Components/Fetchapi’;

import Form from ‘./Components/Form’;

function App() {

 const {data, error, isError, isLoading} = useQuery([‘users’], Fecthapi);

 if (isLoading) {

   return  <div> Loading </div>

 }

 if (isError){

   return <div> Error! + {error.message} </div>

 }

 return (

   <div className=“App”>

<table>

       <tr>

         <th>Name</th>

         <th>User Name</th>

         <th>Email</th>

       </tr>

       {data.map((users, id) => {

         return (

           <tr users={users}>

             <td>{users.name}</td>

             <td>{users.username}</td>

             <td>{users.email}</td>

           </tr>

         )

       })}

     </table>

     <Form /> ——- Imported

   </div>

 ); 

}

export default App;

 

We get this:

 

If you counted earlier, you noticed there are ten names in ten IDs. Using the useMutation() hook, we have been able to make a post request and get the User ID updated.

 

Conclusion

As we develop complex applications, it becomes challenging to maintain the server state for various API endpoints. React Query aids in handling data requests, thereby enhancing the maintainability of our application.

 

admin

admin

Leave a Reply

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