coming from useEffect fetching, is one query key per screen too coarse Hooks
Two months into my first React job. The codebase I inherited fetches in useEffect everywhere and I am moving it to TanStack Query one screen at a time.
My instinct was to give each screen one key - ['ordersScreen'], ['customerScreen', id] - because then invalidation is easy and I always know what to invalidate. A senior on another team looked at it and said "that is not what keys are for" and then went to a meeting.
So: what is the actual convention, and why is screen-shaped wrong?
@mulch_marta · 3w ago · 3 replies
Key by the resource and its parameters, not by the place it is displayed.
['orders', { status, page }]and['customer', id].The reason is that screens are not unique owners of data. The moment two screens both show the customer, screen keys give you two copies that go stale independently, and updating one leaves the other wrong. Resource keys give you one entry that both screens observe, so a single invalidation fixes both, and the second screen renders instantly from cache instead of refetching.
Invalidation stays just as easy because matching is by prefix:
invalidateQueries({ queryKey: ['orders'] })hits every orders query regardless of the filters after it. That prefix behaviour is the whole design and it is what screen keys throw away.Reply
Report
@mulch_marta · 4w ago
Exactly that, and it is why the resource goes first in the key and the specifics after. Once you internalise "keys are paths, invalidation matches prefixes", most of the design questions answer themselves.
Reply
Report
@sam_the_temp · 3w ago
So
invalidateQueries({ queryKey: ['orders'] })after a mutation hits both the list and the detail without me listing them? That is the bit I did not realise I was giving up.Reply
Report