Blog>
Snippets

Customizing focusManager Settings

Provide an example on customizing focusManager settings, such as setting a delay for refetching queries after regaining focus to improve user experience and reduce server load.
import { focusManager } from 'react-query';

// Custom focus listener
function customFocusListener() {
  let isFocused = false;
  let timer = null;

  return (handleFocus) => {
    if (typeof window !== 'undefined' && window.addEventListener) {
      window.addEventListener('focus', () => {
        // Set isFocused to true when window gains focus
        isFocused = true;
        // Clear any existing timers
        clearTimeout(timer);
        // Set a delay before refetching queries
        timer = setTimeout(() => {
          // Only call the focus handler if still focused after the delay
          if (isFocused) {
            handleFocus();
          }
        }, 1000); // 1 second delay
      });

      window.addEventListener('blur', () => {
        // Set isFocused to false when window loses focus
        isFocused = false;
        // Clear the timer when window loses focus
        clearTimeout(timer);
      });
    }
  };
}

// Setting custom focus listener
focusManager.setEventListener(customFocusListener());
This code snippet demonstrates how to customize the focusManager's settings in React Query to add a delay before refetching queries upon regaining focus. A custom focus listener is created that works with a timer. When the window gains focus, it sets a flag to true and starts a timer. If the window remains focused after a 1-second delay, the focus handler is called, indicating it's an appropriate time to refetch queries. This can improve user experience and reduce unnecessary server load by avoiding immediate refetching when the focus rapidly changes.