Blog>
Snippets

Creating a Custom Hook for Data Fetching with TanStack Config

Demonstrate how to create a custom React hook that utilizes TanStack Config for efficient data fetching and state management.
import { useQuery } from '@tanstack/react-query';
Import the useQuery hook from TanStack Query (formerly React Query) to enable data fetching and caching capabilities.
async function fetchData(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error('Network response was not ok.');
  return response.json();
}
Define an asynchronous fetchData function that fetches data from a given URL and returns the JSON response. This function throws an error if the response is not OK, ensuring error handling is accounted for.
function useCustomFetch(url) {
  return useQuery({
    queryKey: [url],
    queryFn: () => fetchData(url),
    staleTime: 5000, // Data will be considered fresh for 5 seconds.
    cacheTime: 10000, // Data will be cached for 10 seconds after unmounting.
    retry: 1, // Number of retry attempts on failure.
  });
}
Create a custom hook named useCustomFetch that utilizes the useQuery hook from TanStack Query. It takes a URL as an argument and returns the useQuery instance. This hook is configured to consider data fresh for 5 seconds and cache data for 10 seconds after unmounting. It retries once on failure.
export default useCustomFetch;
Export the custom hook useCustomFetch as the default export of this module, making it available for use in other parts of the application.