Data Fetching In React Using React-Query

Engineering May 12, 2021
Data Fetching In React Using React-Query

Unless you are building a static application, you need to work with external data and make HTTP request to fetch or update those data.

React, by default, doesn’t ship with support for things like data fetching and that's where React Query helps us to standardise the process of working with remote state.(data fetching)

In this blog, you will learn how to set up react query to fetch data in your applications written in javascript or typescript, the basics of ReactQuery, and its advantages.

What is ReactQuery?

React-Query is an NPM package that provides some custom hooks for fetching, caching, and updating asynchronous data in React. According to their official documentation

‘React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronising and updating server state in your React applications a breeze’

Lets dive in

Whenever you are building any application, you will work with external data. So first of all let's  see an example of data fetching in a typical React App and then compare it by using React Query.

import React, {useEffect, useState} from "react";
import axios from 'axios';

export default function App() {
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [postData, setPostData] = useState(null);
  
  useEffect(() => {
    async function getUserData() {
      try {
        setIsLoading(true);
        const {data} = 
        await axios.get(`https://jsonplaceholder.typicode.com/posts/1`);
        setPostData(data);
        setIsLoading(false);
      } catch (error) {
        setIsLoading(false);
        setIsError(error);
      }
    }
    getUserData();
  }, []);
  
  return (
    <div>
      {isLoading && (<div> ...Loading </div>)}
      {isError && (<div>An error occured: {isError.message}</div>)}
      {postData && (<div>Post Details : {postData.title}</div>)}
    </div>
  )
}

As you can see we are using three different state here to handle the data fetching logic and this pattern replicates across your all components.As your app grows with time all of these server state will live together with your UI/local state.

React query helps us to separate the server state from our local state.

Moreover, this data is not cached, so for every request it will reach to the server to get the data.But in some cases you may not need to query the DB everytime, you can cache the data locally and invalidate that cache whenever needed. React Query helps us to achieve that too.

Now let us see how to make this same request using React-Query:

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

export default function App() {
  const { isLoading, error, data } = useQuery("posts", 
      () => axios("https://jsonplaceholder.typicode.com/posts/1/")
  );
  
  return (
    <div>
      {isLoading && <div> ...Loading </div>}
      {error && <div>An error occured: {error.message}</div>}
      {data && <div>Post Details : {data.title}</div>}
    </div>
  );
}

As you can see, in the above code snippet we are not using any local state and this code does not require useState & useEffect hooks also, all the data fetching logic is handle by useQuery hook provided by React-Query library. This simplifies a lot of thing and helps to write cleaner code.

Also, React Query stores the remote data in the cache and we can configure the stale time for the cache depending on our need, hence improving performance of our app.

Similarly, React-Query also provides a useMutation() hook to handle create/update/delete remote data.

Advantages Of React Query

ReactQuery refines the user experience to a great extent by serving the data from its cache first and then updating the data in the background once the configured stale time is over.

Using these hooks for managing data requests completely removes the need to put your remote data inside the global state and hence helps us to separate our UI state from server state.

In brief, React Query is the best solution for making requests but also constructively managing the data that is returned for our HTTP requests across our app's components.

You can configure React-Query to do much more. You can also do paginated queries efficiently using react-query. Look at the official documentation to explore more and start using React-Query.

Tags

Dipankar Barman

Full Stack JavaScript Developer

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.