Menu

Keeping TanStack Query fresh across tabs
📰

Keeping TanStack Query fresh across tabs

DEV Community: react·Idan Shalem·19 days ago
#kQr9tL0d
#devtoreact#devto#dev#broadcast#querykey
Reading 0:00
15s threshold

You change a project name in one tab. You switch to another tab of the same app. The old name is still there.

TanStack Query keeps one cache per tab. A mutation in tab A updates tab A. Tab B has no idea until it refetches, and that can be a long time if the window is not refocused or the stale time is generous.

The fix is small: tell the other tabs that something changed, and let each of them refetch.

Send the fact, not the data

It is tempting to broadcast the new data and write it into every cache. I would not. Each tab already knows how to fetch the right data, with the right auth, the right filters and the right error handling. So send only "this query key is stale" and let each tab ask the server.

The sender does not receive its own message: the browser skips the BroadcastChannel object that sent it, and the hook also filters out messages from its own source.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.