React Query - The basics

React Query is a powerful library for managing the caching and fetching of data in a React application. It provides a set of hooks that can be used to easily fetch and cache data, as well as automatically manage the stale-while-revalidate caching strategy.

One of the main features of React Query is its caching functionality. By default, React Query will cache the data for each unique query that is made and automatically serve the cached data if the same query is made again. Additionally, React Query will automatically check for updates to the data and refresh the cache if necessary.

To use React Query in a React application, you first need to install the library.

npm install react-query

Then you can use the useQuery hook to fetch and cache data.

import { useQuery } from 'react-query'

function MyComponent() {
  const { data, status } = useQuery('users', async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/users')
    return response.json()
  })

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

  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 a JSON placeholder API. The first argument passed to useQuery is the key of the query, and the second argument is a function that returns a promise that resolves with the data.

React Query also provides a way to manually update the cache using the refetch function.

function MyComponent() {
  const { data, status, refetch } = useQuery('users', async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/users')
    return response.json()
  })

  return (
    <div>
      <button onClick={() => refetch()}>Refetch</button>
      ...
    </div>
  )
}

In this example, the refetch function is passed to a button's onClick, which will allow the user to manually refresh the data.

React Query also provides a lot of other functionality such as manual invalidation of cache, setting custom cache policies etc. With React Query, it becomes easy to handle caching and fetching of data in a React application, resulting in better performance and user experience.