Jalan Technologies > Blog >

Data fetching in React using React Query

Discover the power of React Query for efficient data fetching in JavaScript and TypeScript apps. Simplify state management, cache data, and enhance user experiences with React Query's hooks, all while separating server and UI states. Unlock the benefits of streamlined HTTP requests.

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 React Query?

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 frequently characterized as the essential data-fetching tool for React. In more precise technical terms, it streamlines the processes of fetching, caching, synchronizing, and updating server state within your React applications, simplifying complex operations.’

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.

What’s the biggest thing you’re struggling with right now that we as a technology consulting company can help you with? Feel free to Contact us. We hope our assistance will help!

Disclaimer: The statements and opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Jalan Technologies.

Table of Contents

Hire Our Development Experts.




    Want to raise the bar for your organization?

    Subscribe to our newsletter to receive latest insights on how technology can help turn your goals into reality. By subscribing, you’ll get access to thought-provoking articles, case studies, and resources to help accelerate your impact.

    Get the latest updates straight to your inbox

      Related Blogs
      technology consultant
      Business Insights
      All you need to know about technology consultant

      Technology consultant experts like Jalan Technologies, empowers businesses to strategically leverage technology for success. Services encompass strategic planning, system integration,

      Scroll to Top

      Subscribe Now

        Never Miss Another Post