I found "don't fetch on load or mount" especially common for queries associated with pop-ups or dialogs. A common scenario is when you don't want to fetch data on component mount or initial load, but rather when a specific UI element (like a dialog) is opened.
The solution that worked for me is to bind a variable to the dialog state and use it to control when the query is enabled. This means:
- It fetches data only when the dialog or popup is opened.
- It continues to refetch when query keys change or data becomes invalid, but only while the dialog remains open.
- It prevents unnecessary API calls when the dialog is closed.
Implementation
import { useState } from 'react';
import { useQuery } from 'react-query';
function YourComponent() {
const [isOpen, setIsOpen] = useState(false);
const { data, isPending, isError, error, refetch } = useQuery({
queryKey: [promptId, inputValue],
queryFn: async () => {
const data = await // Your API call here
return data;
},
// Note that we pass isOpen to enabled instead of `true` or `false`
enabled: isOpen,
});
// Rest of your component logic
}
A breakdown of what it means when enabled option in the useQuery hook is set to isOpen:
- The query will only run when
isOpen is true (i.e., when the dialog is opened).
- If the dialog is closed (
isOpen is false), the query won't run, saving unnecessary API calls.
- When the dialog is open, the query will behave normally, refetching when query keys change or data becomes invalid.
forceFetchOnMountproperty in the previous version, but it's replaced byrefetchOnMountin version 3.