Using React Query for Fetching and Caching Data and State Management

Categories:

React Query is a powerful library that simplifies data and state management in React applications. It provides easy-to-use hooks for fetching and caching data, handling errors, and keeping the UI in sync with the data.

React Query is a powerful library that helps you manage your application's data and state, providing an easy way to fetch and cache data, handle errors, and keep your UI in sync with your data. In this blog post, we will explore how to use React Query to handle all your data and state management needs, with code examples to help you get started.

Fetching Data

One of the most important features of React Query is its ability to easily fetch data from your API. To fetch data, you can use the useQuery hook, which takes a query key and an options object as arguments. The query key is a unique identifier for your query, and the options object can contain options such as queryFn, config, and initialData.

import { useQuery } from 'react-query'

function MyComponent() {
  const { data, status } = useQuery('my-query-key', async () => {
    const response = await fetch('https://my-api.com/data')
    const json = await response.json()
    return json
  })
  if (status === 'loading') {
    return <div>Loading...</div>
  }
  if (status === 'error') {
    return <div>Error: {error.message}</div>
  }
  return <div>{data}</div>
}

In this example, we are using the useQuery hook to fetch data from an API endpoint. The hook returns an object with the data, status, and error properties. We can use the status property to render the appropriate UI for each state, such as a loading spinner or an error message.

Caching Data

React Query also provides an easy way to cache your data, so that when you make the same query multiple times, it doesn't need to go to the API again. By default, React Query will cache your data for the duration of the session, but you can configure the cache to expire after a certain amount of time, or when a certain event occurs.

import { useQuery } from 'react-query'

function MyComponent() {
  const { data, status } = useQuery('my-query-key', async () => {
    const response = await fetch('https://my-api.com/data')
    const json = await response.json()
    return json
  }, {
    cacheTime: 60000,
    onSuccess: (data, key) => {
      localStorage.setItem(key, JSON.stringify(data))
    }
  })
  if (status === 'loading') {
    return <div>Loading...</div>
  }
  if (status === 'error') {
    return <div>Error: {error.message}</div>
  }
  return <div>{data}</div>
}

In this example, we are passing an options object to the useQuery hook, with a cacheTime of 60000 milliseconds (1 minute). This means that the data will be cached for 1 minute, and after that, the query will be refetched. We are also passing an onSuccess function, which is called when the query is successful. In this case, we are storing the data in localStorage so that it can be accessed even when the user refreshes the page or closes the browser.

Managing State

React Query also provides a way to manage your component's state, so that you don't have to manually keep track of it. You can use the useMutation hook to update your data and the useIsFetching hook to keep track of the loading state.

import { useQuery, useMutation, useIsFetching } from 'react-query'

function MyComponent() {
  const [name, setName] = useState('')
  const { data, status } = useQuery('my-query-key', async () => {
    const response = await fetch('https://my-api.com/data')
    const json = await response.json()
    return json
  })
  const [updateName] = useMutation(async (name) => {
    const response = await fetch('https://my-api.com/data', {
      method: 'PUT',
      body: JSON.stringify({ name })
    })
    const json = await response.json()
    return json
  })
  const isFetching = useIsFetching()
  if (status === 'loading') {
    return <div>Loading...</div>
  }
  if (status === 'error') {
    return <div>Error: {error.message}</div>
  }
  return (
    <div>
      <input value={name} onChange={e => setName(e.target.value)} />
      <button disabled={isFetching} onClick={() => updateName(name)}>Update Name</button>
      <div>Name: {data.name}</div>
    </div>
  )
}

In this example, we are using the useMutation hook to update the name of the data, and the useIsFetching hook to keep track of the loading state of the mutation. We are also disabling the update button when the mutation is in progress, so the user doesn't accidentally make multiple updates at once.

React Query is a powerful library that can help you manage your application's data and state in a simple and efficient way. With its easy-to-use hooks and powerful caching capabilities, it can help you improve the performance and user experience of your application.

Note: The above code is for illustrative purposes only, and may not work as expected in a real-world application.

In conclusion React Query is a powerful library for managing the state and data of your React application. It makes it easy to fetch and cache data, handle errors, and keep your UI in sync with your data. With its simple, easy-to-use hooks and powerful caching capabilities, it can help you improve the performance and user experience of your application.

In addition to the features mentioned above, React Query also has other advanced features such as:

  • useInfiniteQuery for pagination,
  • queryCache.setQueryData to set data to a specific query key,
  • queryCache.removeQueries to remove specific queries from cache,
  • queryCache.clear to clear the entire cache,
  • queryCache.subscribe to subscribe to changes in the cache.

Using React Query in your React application can help you simplify your data and state management, making it more efficient and easy to maintain. It can help you improve the performance and user experience of your application by reducing the number of API requests and keeping your UI in sync with your data.

As a conclusion, React Query is an essential tool for any React developer, who wants to simplify and improve the data and state management of their application. It's easy to use, flexible and provides a lot of powerful features out of the box. With React Query, you can focus on building your application and leave the data and state management to the library.