Blog>
Snippets

Configuring focusManager to Optimize Query Refetching

Demonstrate configuring focusManager in React Query to control query refetching on window focus events, minimizing unnecessary network requests.
import { focusManager } from 'react-query';

// Initializing focus management in your application
focusManager.setEventListener(handleFocus => {
  if (typeof window !== 'undefined' && window.addEventListener) {
    // Listen for window focus events
    window.addEventListener('focus', handleFocus(true), false);
    window.addEventListener('blur', handleFocus(false), false);

    // Cleanup listeners
    return () => {
      window.removeEventListener('focus', handleFocus(true), false);
      window.removeEventListener('blur', handleFocus(false), false);
    };
  }
});
This code sets up an event listener with React Query's focusManager, which will now listen to window focus and blur events to respectively signal that queries should refetch (on focus) or not (on blur). This optimizes network requests by refetching data only when the app or page is in focus.
import { useQuery } from 'react-query';

// Usage within a React component
const fetchData = async () => {
  // your data fetching logic here
};

const useCustomQuery = () => {
  return useQuery('dataKey', fetchData, {
    refetchOnWindowFocus: true,  // Ensure queries refetch on window focus by default
    staleTime: 5000, // Customize the stale time
  });
};
This piece of code demonstrates the use of a custom hook that utilizes React Query's useQuery to fetch data. The `refetchOnWindowFocus: true` option is set, so the query will automatically refetch data when the window regains focus, but only if the data is stale (controlled by the `staleTime` option).