DEV Community

Cover image for How to use React Query and How to fix minor issues from that?
Jaelyn Lee
Jaelyn Lee

Posted on

How to use React Query and How to fix minor issues from that?

Hi Devs,

Today, I want to share my knowledge about an alternative way to fetch data and render it on pages using React Query. I used Redux before to manage states and fetch data but it requires too much code, which can be ridiculous. In contrast, React Query is an excellent alternative that I fell in love with immediately even though I am still learning it.

Let me explain why you should use React Query and how to fix minor issues with it.

Why use React Query?

Caching and retrying are easier!

When you use useEffect to fetch data, you declare error, loading, and data using useState. However, this is not reusable and makes your code too long. You may consider declaring it as a global state, but this approach seems a bit dubious and messy.

React Query can resolve all these issues, including handling cache and retrying.

What is caching, by the way?
In computing, a cache is a high-speed data storage layer that stores a subset of data, typically transient in nature. This allows future requests for that data to be served up faster than accessing the data's primary storage location. Caching enables you to efficiently reuse previously retrieved or computed data.

How can we cache data in React Query?
TanStack Query has excellent documentation that explains everything a newcomer needs to know. What a wonderful library!

Check this link out if you want to deep dive into it and I highly recommend you to read.

https://tanstack.com/query/v4/docs/react/guides/important-defaults

By default, React Query saves data as a stale status, requiring a fresh data check. However, by setting up a staleTime we can define how long it will contain data as a fresh status.

Let's check with actual code.

const {
    isLoading,
    error,
    data: products,
  } = useQuery(
    ['products', checked],
    async () => {
      console.log('...fetching products')
      return fetch(`data/${checked ? 'sale_' : ''}products.json`).then((res) =>
        res.json()
      )
    },
    {
      staleTime: 1000 * 60 * 5, //5 mins
    }
  )

Enter fullscreen mode Exit fullscreen mode

In this code sample, the staleTime is set as a third parameter when fetching data, which saves the data as defined.

By installing the dev tool provided by React Query, you can check the data status and which data is updated. This makes it easy to manage bugs and debug errors, and prevents unnecessary network requests.

While I have briefly covered React Query today, I plan to explore it more in-depth and cover other related topics as well.

Thank you for taking the time to read this, and happy coding! 😎

Top comments (0)