Skip to main content

Command Palette

Search for a command to run...

Getting Started with React -query: A Beginner's Guide

Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte

Published
•5 min read•View as Markdown
Getting Started with React -query: A Beginner's Guide
U

I'm a passionate developer with a love for all things tech. Join me as I explore the latest trends and share my insights on the world of coding and programming.

Introduction

React Query is a popular data-fetching library for React that simplifies the management of asynchronous data in your application. It provides a powerful and flexible API that makes it easy to handle complex data fetching scenarios such as caching, pagination, and server-side rendering.

If you're a React developer, you know that fetching data from an API can be a tedious and error-prone task. You need to handle loading, error, and success states, implement caching and pagination, and deal with stale data. Fortunately, React Query is here to simplify data fetching in React.

React Query is built on top of the new React Hooks API, which allows you to write more readable and maintainable code. It's designed to work seamlessly with React Suspense and concurrent mode, providing a smooth user experience.

Advantages of using react-query

(1.) Improves application performance with data caching.

(2.) Allows for data to be fetched in the background whenever there is an update(background updating), refetches data when a window is refocused, and also provides defaults that retry a failed query request three times in cases where there is an error.

(3.) Easy to use and integrate: React Query is easy to use and integrate with existing React applications. It has a small API surface and can be easily integrated with other libraries and tools such as Redux, TypeScript, and more.

Installing and Setting Up React Query

To get started with React Query, you need to install it in your React project. You can do this using either NPM or Yarn. Let’s install react-query version 4.29.1 with npm or yarn

$ npm i @tanstack/react-query
      or
$ yarn add @tanstack/react-query

Tanstack Query, formerly known as React Query v3 (react-query), aims to make the React Query async state manager, available to frameworks beyond React and comes with a variety of new features.

For example, Tanstack Query exists now for:

  • React @tanstack/react-query (React Query v4)

  • Svelte @tanstack/svelte-query

  • Solid @tanstack/solid-query

  • Vue @tanstack/vue-query

Once you've installed React Query, you need to wrap your application in a QueryClientProvider. This provider will give your application access to QueryClient, which is the central hub for all data fetching in React-Query.

$ Index.js 

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {QueryClientProvider,QueryClient} 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>
);

Basic Concepts of React Query

React Query has a few basic concepts that you need to understand before you can start using it. Here's a brief overview:

  • Queries: A query is a function that fetches data from an API endpoint. It returns a Promise that resolves to the data.

  • Mutations: A mutation is a function that updates data on the server. It returns a Promise that resolves to the updated data.

  • Query Keys: A query key is a unique identifier for a query. It's used for caching and data invalidation.

Fetching Data with React Query

To fetch data with React Query, you use the useQuery hook. This hook takes a query key and a function that fetches data from an API endpoint. Here's an example of how to use the useQuery hook.

$ App.js

import React from 'react'
import {useQuery,useMutation, QueryClient} from "@tanstack/react-query"
import GetApiData from "./Api/GetApiData"

const App = () => {
   const {isLoading,isError,error,data} = useQuery({
    queryKey: ["getData"],
    queryFn: GetApiData
  })

  if(isLoading) <h1>Loading</h1>
  if(isError) <h1>Error: {error.message}</h1>
 return (
       <ol>
      {data?.map((item) => (
          <li key={item.id} style={{margin: "11px"}}>{item.title}</li> 
      ))}
      </ol>
 )
}

export default App;

Fetching data with axios :

$ Api/GetApiData.js

import axios from "axios"

const GetApiData = async () => {
      const{data}= 
      await axios.get("https://jsonplaceholder.typicode.com/posts")
      return data;
}
export default GetApiData;

In this example, the useQuery hook fetches data from the function GetApiData and returns the result as an array of posts. The isLoading, isError, data, and error variables are used to handle loading, error, and success states.

How To Post Data Using React-query

To update data with React Query, you use the useMutation hook. This hook takes a mutation function that updates data on the server. Here's an example of how to use the useMutation hook:

$ App.js

import React from 'react'
import {useMutation, QueryClient} from "@tanstack/react-query"
import PostApiData from './Api/PostApiData'

const App = () => {
  const queryClient = new QueryClient();

  const mutation = useMutation({
    mutationFn: PostApiData,
    onSuccess : (data) => {
      console.log("my-data :",data);
    },
    onError: () => {
      alert("there was an error")
    },
  })

  return (
    <div>
    <button style={{
          padding: "12px 18px",
          backgroundColor: '#6D597A',
          color: "white",
          margin: "15px",
          borderRadius: 8,
          cursor:"pointer"
        }} 
    onClick={() => {
          mutation.mutate({
            name: "Johny"  ,
            age: Math.ceil(Math.random()*100),
            title: 'Do Laundry',
          })
        }}>Post New Data</button>
    </div>
  )
}

export default App

Posting data with axios

Let’s jump in and create the component called PostApiData.js responsible for posting data, We are going to use a dummy rest api called jsonplaceholder for the post request with axios.

$ PostApiData.js

import axios from "axios"

const PostApiData = async (data) => {
   const result = await axios.post("https://jsonplaceholder.typicode.com/posts",data)
   return result.data;
}

export default PostApiData;

Conclusion

React Query is a powerful library for managing asynchronous data fetching and caching in React applications. It simplifies data management, improves performance, provides real-time updates, supports server-side rendering, and is easy to use and integrate with other libraries and tools. By leveraging React Query, developers can focus on building features rather than managing complex data fetching and caching logic. Overall, React Query is a valuable addition to any React developer's toolkit and can significantly improve the performance and user experience of React applications.

D

Great work bro keep up the good work

1
P

Nice

1
P
Piyush3y ago

superbb bro keep posting this type of information

1