Blog>
Snippets

Implementing Real-time Tab Synchronization

Show how to synchronize data in real-time across multiple browser tabs using React Query's Broadcast Query Client, focusing on shared state management.
import { BroadcastChannel } from 'broadcast-channel';
import { QueryClient } from 'react-query';

// Create a new broadcast channel
cost myChannel = new BroadcastChannel('my_channel');

// Override queryClient's default queryCache and mutationCache
const queryClient = new QueryClient({
  queryCache: {
    onMutation: async ({ mutation }) => {
      // Whenever a mutation happens, publish it to the channel
      myChannel.postMessage(mutation);
    },
    // Subscribe to the channel for receiving messages
    subscribe: (callback) => myChannel.onmessage = callback
  }
});
This code snippet demonstrates how to create a broadcast channel using the 'broadcast-channel' package and integrates it with React Query's QueryClient for real-time tab synchronization. It overrides the default 'queryCache' to publish mutations to a channel and subscribes to the channel to receive updates.
myChannel.onmessage = (message) => {
  // Invalidate queries to refetch data and update UI across tabs
  queryClient.invalidateQueries();
};
This part sets up an event listener on the broadcast channel. When a message (indicating a mutation) is received, it invalidates queries using the 'queryClient'. This triggers a refetch of data, ensuring that all tabs are synchronized and display the latest state.