Blog>
Snippets

Custom React Query Hook for Reusable Data Fetching Logic

Create a custom React Query hook that encapsulates fetching, error handling, and loading state for products in an e-commerce app to promote code reuse across components.
import { useQuery } from 'react-query';
import axios from 'axios';
Imports necessary for running React Query and performing HTTP requests.
const fetchProducts = async () => {
  const { data } = await axios.get('/api/products');
  return data;
};
Defines an asynchronous function 'fetchProducts' to fetch products data from the server using Axios.
export const useProducts = () => {
  return useQuery('products', fetchProducts);
};
Creates a custom React Query hook named 'useProducts' that uses 'useQuery' to fetch, cache, and update the products data. 'products' is a unique key for caching and fetching mechanism.