React Query

React Query

ยท

2 min read

Table of contents

No heading

No headings in the article.

React Query is a lightweight library for fetching, caching, and updating data in your React applications. It was designed to be easy to use, flexible, and scalable, making it a great choice for developers who want to manage data in their React apps.

One of the key benefits of React Query is its ability to automatically cache and invalidate data. When you fetch data from an API, React Query stores it in a cache and automatically updates the cache whenever the data changes. This can help improve the performance of your app by reducing the number of unnecessary API requests.

To use React Query, you first need to install it using npm or yarn. Once you've done that, you can start using the library in your React components. To fetch data, you can use the useQuery hook, which takes a key and a function that returns a promise. The key is used to identify the query and the function is called when the query is made.

import { useQuery } from 'react-query'

function UserList() {
  const { data, status } = useQuery('users', () =>
    fetch('https://my-api.com/users').then(res => res.json())
  )

  if (status === 'loading') {
    return <p>Loading...</p>
  }

  if (status === 'error') {
    return <p>Error: {error.message}</p>
  }

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

In this example, the useQuery hook is used to fetch a list of users from an API. The hook returns an object with two properties: data and status. The data property contains the fetched data and the status property contains the current status of the query (either loading, error, or success).

In the component, we use the status property to show a loading indicator while the data is being fetched and to display an error message if the request fails. Once the data has been fetched successfully, we render a list of users.

React Query also makes it easy to manage multiple queries. You can use the useMultiQuery hook to fetch data from multiple sources and keep track of the status of each request. This can be useful when you need to fetch data from multiple APIs or when you want to update multiple queries at the same time.

Here's an example of how you might use the useMultiQuery hook:

import { useMultiQuery } from 'react-query'

function UserProfile() {
  const { data: [user, posts], status } = useMultiQuery(
    ['user', userId],
    () => fetch(`https://my-api.com/users/${userId}`).then(res => res.json()),
    ['posts', userId],
    () => fetch(`https://my-api.com/users/${userId}/posts`).then(res => res.json())
  )

  if (status === 'loading') {
    return <p>Loading...</p>
  }

  if (status === 'error') {
ย