Blog>
Snippets

Custom Hook for Data Fetching

Create a custom React hook that utilizes useQuery for fetching data, encapsulating the fetching logic and error handling to be reused across different components.
import { useQuery } from 'react-query';
import axios from 'axios';
Import useQuery from React Query and axios for making HTTP requests.
const fetchData = async (url) => {
  const { data } = await axios.get(url);
  return data;
};
Define a function to fetch data using axios. This function can be reused for multiple endpoints.
export const useCustomFetch = (queryKey, url) => {
  return useQuery(queryKey, () => fetchData(url), {
    onError: (error) => {
      // Handle error here.
      console.error('Error fetching data:', error);
    }
  });
};
Create a custom hook that encapsulates the useQuery logic, making it reusable across components. This hook takes a queryKey and a URL, fetches the data, and handles errors.