How to use the useQuery hook for data fetching with React-Query



Image not found!!

To use the useQuery hook for data fetching with React-Query, you first need to define a query function that fetches the data you need. Then, you can use the useQuery hook in your React components to fetch and manage that data. Here's a step-by-step guide:

  1. Install React-Query: If you haven't already, install React-Query in your project.
bash
npm install react-query
  1. Define Your Query Function: Define a function that fetches the data you need. You can use any method to fetch data, such as fetch, Axios, or any other HTTP library.

For example, let's create a query function that fetches a list of users from an API:

javascript
const fetchUsers = async () => { const response = await fetch('https://api.example.com/users'); if (!response.ok) { throw new Error('Failed to fetch users'); } return response.json(); };
  1. Use the useQuery Hook in Your Component: Import the useQuery hook from React-Query and use it in your component to fetch and manage the data.
javascript
import { useQuery } from 'react-query'; const UsersComponent = () => { const { data, isLoading, error } = useQuery('users', fetchUsers); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> <h1>Users</h1> <ul> {data.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> </div> ); }; export default UsersComponent;

In this example:

  • We use the useQuery hook to fetch data from the 'users' query key using the fetchUsers function.
  • The isLoading variable indicates whether the query is currently loading.
  • The error variable contains any error that occurred during data fetching.
  • If the data is still loading, we display a loading indicator. If an error occurs, we display an error message. Otherwise, we render the list of users.
  1. Handle Data Refetching and Caching: React-Query automatically handles data refetching and caching for you. By default, it caches the data for 5 minutes and automatically refetches the data when the component remounts or when the cache becomes stale. You can configure caching behavior and other options as needed.

With this setup, your React components will fetch and manage data using the useQuery hook from React-Query, providing a powerful and efficient way to manage data fetching in your application.