To ensure that the API is called only once with React Query, use the useQuery hook with appropriate configuration to fetch data. React Query automatically deduplicates multiple requests for the same query key into a single request. Here's how to achieve this:
javascriptimport { useQuery } from 'react-query'; // Define your API fetch function const fetchMyApi = async () => { // replace with your actual API call const response = await fetch('https://my-api/service'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; function MyComponent() { // Use the useQuery hook to fetch data const { data, error, isLoading, isFetching } = useQuery( 'myUniqueQueryKey', // This key is used internally by React Query to manage the queries fetchMyApi, // Your fetch function { // Optional configurations // To cache data and prevent refetching, set `staleTime` to `Infinity` staleTime: Infinity, // To prevent refetching when the window regains focus, set `refetchOnWindowFocus` to `false` refetchOnWindowFocus: false, // To disable automatic retries on failure, set `retry` to `false` retry: false, // To specify that the query should not refetch on mount if data is already cached, set `refetchOnMount` to `false` refetchOnMount: false, } ); if (isLoading) { return <span>Loading...</span>; } if (error) { return <span>An error occurred: {error.message}</span>; } // Render your component with the fetched data return ( <div> {/* Render your API data here */} <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }
In this example, the useQuery hook is used with a unique query key ('myUniqueQueryKey') and a fetch function (fetchMyApi). The configuration options are set to prevent the API call from being made again under certain circumstances, such as cached data (staleTime: Infinity), window refocus (refetchOnWindowFocus: false), component remount (refetchOnMount: false), and failure retries (retry: false).
The query runs once, and the result is cached. Any other component using the same query key will use the cached data instead of making a new API call, provided the cached data is not invalidated or considered stale based on your configuration.
Note that React Query's defaults assume your data may change and should be periodically updated, which is why the defaults are relatively aggressive about refetching. Adjusting these options allows you to control the behavior to match your specific requirements.