Managing query keys as inline arrays breaks down once a codebase grows beyond a handful of queries. The query key factory pattern — a single object per entity that owns every key shape — solves four common problems: typo bugs, missed invalidations, refactoring pain, and inconsistent naming conventions. Each factory exposes hierarchical keys (all, lists, list(filters), details, detail(id)) that compose from general to specific, enabling TanStack Query's partial matching to surgically invalidate only the relevant cached data after mutations. The pattern also unlocks TypeScript tuple typing for compile-time safety. A recommended folder structure separates queryKeys/, queries/, and mutations/ so components consume clean composables rather than raw useQuery calls. The pattern is overkill for small apps but pays off quickly once a codebase has many queries or multiple developers.
Table of contents
Why Query Keys Matter More Than You ThinkThe Naive Approach (and Where It Hurts)Query Key FactoriesHierarchical InvalidationA Convention That ScalesFilter Objects as Plain ObjectsTypeScript: A Bonus WinWhere I Keep These FilesA Working Example: A Real Mutation FlowWhen to Skip All ThisWrapping Up84.4K Impressions1 Comment