Skip to main content

Function: useTabLeader()

useTabLeader<TMessage>(key, options?): UseTabLeaderReturn<TMessage>

Defined in: use-tab-leader.ts:360

Elects one tab as the leader among all tabs of the same origin that use the same key, so work that should run only once (polling, a websocket, a sync) runs in a single tab. When the leader closes or crashes, another tab is elected automatically.

isLeader updates reactively, and onElected and onDemoted fire on the transitions. Different keys elect their leaders independently. Leadership is released when the component unmounts, key changes or enabled becomes false, and onDemoted is called if the instance was the leader.

The election uses the Web Locks API, so a leader that crashes or is frozen is replaced reliably. Without it, tabs fall back to a BroadcastChannel heartbeat: the oldest tab leads, and a tab that stops pinging for a few seconds is dropped. That fallback is best effort, since browsers may slow the timers of hidden tabs. If neither API exists (server rendering, an old browser, an insecure context), there is nothing to compete with, so the hook treats the page as a single tab and makes it the leader once the effect has run. During server rendering, isLeader is false.

broadcast and onMessage give the leader a way to share what it fetched with the other tabs over the same channel.

Type Parameters​

TMessage​

TMessage = unknown

The type of the messages passed to broadcast.

Parameters​

key​

string

Names the election. Tabs with the same key compete, tabs with different keys don't.

options?​

UseTabLeaderOptions<TMessage>

Optional settings and callbacks.

Returns​

UseTabLeaderReturn<TMessage>

The isLeader, leaderId and id state and the broadcast function.

Examples​

// Only the leader tab polls
const { isLeader } = useTabLeader("notifications");

useInterval(poll, isLeader ? 5000 : null);
// The leader fetches, every tab shows the result
const [data, setData] = useState<Data>();
const { broadcast } = useTabLeader<Data>("prices", {
onElected: () => startPolling(),
onDemoted: () => stopPolling(),
onMessage: setData,
});

const onPoll = (next: Data) => {
setData(next);
broadcast(next);
};

For a live, editable example, see the useTabLeader docs page.