AGENT SKILL

react-query-cache-utilities

Use TanStack React Query with auto-generated hooks from @repo/api-client (preferred) or a centralized QueryKeys enum and cache utility for manual setup

License 许可
Apache-2.0
最近更新
2026-11-04
Stars
★ 41
Forks
0

01 前言 Front Matter

name
react-query-cache-utilities
description
Use TanStack React Query with auto-generated hooks from @repo/api-client (preferred) or a centralized QueryKeys enum and cache utility for manual setup

03 SKILL.md 正文

React Query Cache Utilities

This skill covers @tanstack/react-query.

This project uses React Query (@tanstack/react-query) for server state caching. There are two patterns:

  1. Auto-generated hooks from @repo/api-client — preferred for covered domains
  2. Manual setup — for domains not covered by @repo/api-client

Pattern A: Auto-generated Hooks from @repo/api-client (Preferred)

For domains covered by @repo/api-client, all React Query hooks are auto-generated by Orval:

// Extension app — in a component
import { useGetAllGuides, useCreateGuide, useDeleteGuide } from "@repo/api-client";

function GuideList() {
  // Query hook with auto-generated query keys, caching, and refetching
  const { data, isLoading, error } = useGetAllGuides();

  // Mutation hook with auto-generated invalidate logic
  const deleteMutation = useDeleteGuide({
    mutation: {
      onSuccess: () => {
        showToastSuccess("Guide deleted");
      },
      onError: (error) => {
        showToastError("Error", error.message);
      },
    },
  });

  // ...
}

✅ DO — Use auto-generated hooks as the primary pattern

✅ DO — Use standard TanStack Query patterns (loading, error, success callbacks)

❌ DON'T — Write manual query hooks for domains covered by @repo/api-client


Pattern B: Manual Setup (Non-api-client Domains)

For domains not covered by @repo/api-client, use manual React Query setup:

  • useQuery / useMutation — for component-level data fetching
  • fetchCachedDataOrFetchNewQuery — for app boot hydration into Zustand stores
  • QueryKeys — centralized enum for all cache keys

Folder Structure

constants/
├── query-keys.ts        ← QueryKeys enum ONLY
├── query-client.ts      ← QueryClient instance + cache utility
└── env.ts

QueryClient Setup (constants/query-client.ts)

import { QueryClient } from "@tanstack/react-query";

export const queryClient = new QueryClient();

QueryKeys Enum (constants/query-keys.ts)

All cache keys are centralized in a single enum:

// constants/query-keys.ts
export enum QueryKeys {
  GET_USER_ME = "get_user_me",
  INVENTORY = "inventory",
  PRODUCT = "product",
  PRODUCTS = "products",
  // ...
}

✅ DO — All query keys in the enum, no inline string literals

❌ DON'T — Use string literals as query keys

// ❌ DON'T
useQuery(["get_user_me"], getUserMe);

// ✅ DO
useQuery([QueryKeys.GET_USER_ME], getUserMe);

Cache Utility (constants/query-client.ts)

This utility is used specifically for app boot hydration — loading cached or fresh data into Zustand stores before the first render:

// constants/query-client.ts
export const fetchCachedDataOrFetchNewQuery = async <T>(
  queryKey: QueryKey,
  queryFn: () => Promise<unknown>
): Promise<T | null> => {
  const cachedData: any | undefined = queryClient.getQueryData(queryKey);

  if (cachedData) {
    return cachedData as T;
  }

  const fetchedQueryData: any = await queryClient.fetchQuery({
    queryKey,
    queryFn: async () => {
      try {
        return await queryFn();
      } catch (error: any) {
        console.error(error);
        return null;
      }
    },
    staleTime: 60 * 1000
  });

  return fetchedQueryData;
};

Usage: Boot Hydration into Zustand Stores

async function bootstrapApp() {
  const userData = await fetchCachedDataOrFetchNewQuery(
    [QueryKeys.GET_USER_ME],
    getCurrentUser
  );

  if (userData) {
    useSessionStore.getState().setUser(userData);
  } else {
    useSessionStore.getState().setUser(null);
  }
}

When to Use What

Scenario Pattern Tool
Extension app, api-client covers the domain Auto-generated hooks useGetAllGuides, useCreateGuide, etc.
Web app, client-side caching needed Standard React Query useQuery / useMutation
App boot, hydrate store (non-api-client) Manual cache utility fetchCachedDataOrFetchNewQuery
Invalidating cache (non-api-client) Manual queryClient.invalidateQueries()

Rules

✅ DO

  • Use auto-generated hooks from @repo/api-client for covered domains
  • Put QueryKeys enum in constants/query-keys.ts (non-api-client domains)
  • Put QueryClient + fetchCachedDataOrFetchNewQuery in constants/query-client.ts (non-api-client domains)
  • Use fetchCachedDataOrFetchNewQuery only for app boot / context provider hydration
  • Cache-first: always check cache before network

❌ DON'T

  • Don't write manual query hooks for domains covered by @repo/api-client
  • Don't use fetchCachedDataOrFetchNewQuery in components — it's for boot hydration only
  • Don't inline query key strings — always use QueryKeys
  • Don't forget staleTime when using fetchCachedDataOrFetchNewQuery

04 同仓库更多 Skills

CliqRelay
CliqRelay/cliqrelay

typst

Typst document creation and package development. Use when: (1) Working with .typ files, (2) User mentions typst, typst.toml, or typst-cli, (3) Creating or using Typst packages, (4) Developing document templates, (5) Converting Markdown/LaTeX to Typst

★ 41
CliqRelay
CliqRelay/cliqrelay

shadcn

Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".

★ 41
CliqRelay
CliqRelay/cliqrelay

handoff

Compact the current conversation into a handoff document for another agent to pick up.

★ 41
CliqRelay
CliqRelay/cliqrelay

grilling

Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.

★ 41
CliqRelay
CliqRelay/cliqrelay

grill-me

A relentless interview to sharpen a plan or design.

★ 41
CliqRelay
CliqRelay/cliqrelay

dont-waffle

Use this skill when answering questions, explaining concepts, writing technical responses, reviewing code, or helping with development tasks. Communicate in clear, simple, standard English. Keep answers concise and focused, remove unnecessary filler and repetition, explain technical ideas in plain language, and structure information so it is easy to read and understand. When showing code, present it clearly with enough context for the developer to understand what it does and where it belongs.

★ 41