Fetching Data using React-Query

Fetching Data using React-Query

React Query is a React library used for managing the server state. Moreover, it is also used for fetching, caching, synchronising and updating the server state.

Why use react-query?

React is used to manage the UI state. Moreover, whatever data is fetched has to be used in multiple other components in the application. Ideally, the solution is to pass them as props or manage them in a global state which leads to a complex code structure. And it becomes even more complex when we deal with dedupe requests, caching, and background data updates. That’s why we need to use react-query as it provides various features like:

  • Fetching and caching of the data

  • Mutations

  • Pagination and lazy loading

  • Increase in memory performance by removing data which is not used.

Now let’s see how we can fetch data using useQuery.

Step 1: Install react-query.

npm i @tanstack/react-query

Step 2: Wrap QueryClientProvider to the root of the application and provide queryClient as a prop.

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

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Posts />
    </QueryClientProvider>
  )
}

Step 3: Fetch the data using useQuery.

Here, the first argument of useQuery() is a unique key to identify that particular query, to cache and re-fetch the data and the second argument is a data fetching function that returns a promise that resolves data or throws an error.


import { useQuery } from 'react-query';

function Posts() {
  function getPosts() {
    await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );
  return data;
  }

  const { isLoading, isError, data, error } = useQuery('todos', getPosts)

  if (isLoading) {
    return <span>Loading...</span>
  }

  if (isError) {
    return <span>Error: {error.message}</span>
  }

  return (
    <>
     <div>
      <p>Post</p>
     </div>
     {data.map(item => {
       return (
         <div>
           <p>Title:{" "}<span>{item.title}</span></p>
           <p>Body:{" "} <span>{item.body}</span></p>
         </div>
      );
    }
    )}
  </>
  )
}

export default Posts;

In response to the query, we get 3 states.

  1. isLoading — signifies that data is still in the loading state.

  2. isError — signifies that query has encountered an error.

  3. data — signifies that query is successful and data has been retrieved.

Although useQuery provides other configurations to control the data fetching. To know, please visit the React Query Documentation.

Conclusion:

React Query really comes handy when it comes to handle the server state, caching, handling dedupe requests and synchronising the data. We can also fetch data from anywhere in the application without using the global state.

Stay tuned and don’t forget to follow me. Thank you for reading.