Combining useIsFetching and Custom Hooks
Show how to combine the useIsFetching hook with a custom hook to manage and display a loading state based on multiple concurrent data fetching operations.
import { useIsFetching } from '@tanstack/react-query';
export const useGlobalFetchingIndicator = () => {
const isFetching = useIsFetching();
return { isFetchingGlobal: isFetching };
};
This custom hook, useGlobalFetchingIndicator, utilizes the useIsFetching hook from React Query to provide a global fetching state indicator. It returns an object containing a boolean indicating if any queries are currently fetching data.
import React from 'react';
import { useGlobalFetchingIndicator } from './useGlobalFetchingIndicator';
export const GlobalLoader = () => {
const { isFetchingGlobal } = useGlobalFetchingIndicator();
if (!isFetchingGlobal) return null;
return (
<div>Loading...</div>
);
};
This component, GlobalLoader, uses the custom hook useGlobalFetchingIndicator to determine if any data fetching is currently happening globally. If isFetchingGlobal is true, it renders a loading indicator, otherwise, it returns null, showing nothing.