Blog>
Snippets

Setting Up React Query with Broadcast Query Client

Initialize React Query in a React application and configure the Broadcast Query Client to sync queries across browser tabs.
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
import { BroadcastChannel } from 'broadcast-channel';
Import necessary modules from React Query, including the DevTools for debugging, and the BroadcastChannel module to enable cross-tab communication.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // Configure retries, staleTime, etc.
    }
  }
});
Initialize the QueryClient with default options. It is customizable as per the application needs.
const channel = new BroadcastChannel('react-query');

queryClient.getQueryData = (queryKey) => {
  const data = queryClient.getDefaultedQueryData(queryKey);
  channel.postMessage(data);
  return data;
};

queryClient.setQueryData = (queryKey, updater) => {
  const result = queryClient.getDefaultedQueryData(queryKey, updater);
  channel.postMessage({ queryKey, result });
  return result;
};

channel.onmessage = (message) => {
  if (message.queryKey && message.result) {
    queryClient.invalidateQueries(message.queryKey);
  }
};
Configure the BroadcastChannel to sync the React Query state across browser tabs. Overrides the getQueryData and setQueryData methods of QueryClient to broadcast messages when a query's state changes. It listens for messages from other tabs to invalidate queries and refetch as necessary.
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your application components go here */}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}
The App component wraps the entire application with QueryClientProvider to provide React Query functionality throughout. Includes the ReactQueryDevtools for debugging.