state-management
Skill1 starsChanged 9 months agoMITView on GitHub
State management patterns for React apps — Zustand, TanStack Query, Context, URL state. Guides architecture decisions for local, global, server, and URL state.
- Installs packages
18 other projects use a version of this.
Adopted by
Most recently taken up by
- brianshepardpss/analyzer-looptheir own version, first seen Oct 2, 2026
- compozy/compozytheir own version, first seen Oct 1, 2026
- komluk/scaffoldingtheir own version, first seen Sep 28, 2026
- alfredobs97/flutter_agentic_templatetheir own version, first seen Sep 24, 2026
- novatic-cu/nova-skillstheir own version, first seen Sep 20, 2026
- LeonxLJX/web-engineer-skillstheir own version, first seen Sep 3, 2026
Used with
Projects with it also use css-architecture, error-handling and 3 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
Piyush8296Skillcss-architecture
CSS architecture, Tailwind patterns, responsive design, design tokens, and styling best practices. Use when implementing designs, setting up styling infrastructure, or debugging layout issues.
Also in 3 projects that use this
MicrosoftSkillerror-handling
统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。
Also in 5 projects that use this
ffsshhttiikkSkilli18n
Internationalization and localization
Also in 4 projects that use this
NVIDIASkilltesting
Run Python and Rust tests for physicsnemo-curator using uv + pytest with coverage reporting via pytest-cov, and cargo-nextest for Rust tests. Includes benchmark workflows with pytest-benchmark and criterion.
Also in 4 projects that use this
MicrosoftSkillapi-design
Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.
Also in 3 projects that use this
Other versions18 projects use a version of this.
Word for word · 1
- PMDevSolutions/Aurelius★ 8100% same
Edited · 0
None found.
Wrote their own version · 17
- compozy/compozy★ 2.8ksame name
- conorluddy/xclaude-plugin★ 182same name
- Owl-Listener/ai-design-skills★ 178same name
- cohen-liel/hivemind★ 110same name
- TheBeardedBearSAS/claude-craft★ 106same name
- statelyai/skills★ 48same name
- komluk/scaffolding★ 15same name
- autohandai/community-skills★ 11same name
- YepAPI/skills★ 8same name
- Piyush8296/claude-workspace★ 2same name
7 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository9 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- animation-motionSkill
- auth-flowsSkill
- form-handlingSkill
- react-accessibilitySkill
- react-component-developmentSkill
- react-performance-optimizationSkill
- react-testing-workflowsSkill
- seo-metadataSkill
The file
We split this skill into the rules it gives an agent
11 rules. 0 are common, 6 are distinctive, and 5 are very specific to this project.
0
Common
Most of the 14 edited versions we read keep these.
6
Distinctive
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 74
Rule: If you have 3+ related useState calls that change together, switch to useReducer.
- Distinctive: line 127
Always use selectors for reads
- Very specific: line 128
Use persist middleware for state that survives refresh (theme, user preferences)
- Very specific: line 129
Use devtools middleware in development
- Distinctive: line 130
Keep actions in the store, not in components
- Distinctive: line 131
Never store server data in Zustand — use TanStack Query
- Distinctive: line 135
Use for: All data from APIs. Handles caching, refetching, loading states, error states, optimistic updates.
- Distinctive: line 225
NEVER store API data in useState or Zustand
- Distinctive: line 226
Every API call gets its own custom hook
- Very specific: line 228
Use enabled to conditionally fetch
- Very specific: line 229
Use staleTime (not refetchInterval) for most cases
“Common” is measured: kept by at least 6 in 10 of the 14 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
State Management Patterns
When to Use This Skill
Use when:
- Setting up state management for a new React app
- Deciding between state solutions
- Implementing data fetching/caching
- Debugging stale state or unnecessary re-renders
- Migrating from Redux or other state libraries
State Categories Decision Tree
What kind of state?
├── UI State (local) → useState / useReducer
│ └── Shared across 2-3 components → Lift state up
├── UI State (global) → Zustand
│ └── Theme, sidebar open, modals, toasts
├── Server State → TanStack Query
│ └── API data, caching, background refetching
├── URL State → useSearchParams / nuqs
│ └── Filters, pagination, sort, tab selection
└── Form State → React Hook Form + Zod
└── Inputs, validation, submission1. Local State — useState / useReducer
Use for: Component-scoped UI state that doesn't need sharing.
// Simple toggle
const [isOpen, setIsOpen] = useState(false);
// Complex state with multiple transitions — use useReducer
type Action =
| { type: 'FETCH_START' }
| { type: 'FETCH_SUCCESS'; data: Item[] }
| { type: 'FETCH_ERROR'; error: string };
interface State {
items: Item[];
loading: boolean;
error: string | null;
}
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'FETCH_START':
return { ...state, loading: true, error: null };
case 'FETCH_SUCCESS':
return { items: action.data, loading: false, error: null };
case 'FETCH_ERROR':
return { ...state, loading: false, error: action.error };
}
}Rule: If you have 3+ related useState calls that change together, switch to useReducer.
2. Global UI State — Zustand
Use for: State shared across many components (theme, auth status, notifications, layout).
Setup
pnpm add zustandStore Pattern
// src/stores/use-app-store.ts
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
interface AppState {
theme: 'light' | 'dark';
sidebarOpen: boolean;
setTheme: (theme: 'light' | 'dark') => void;
toggleSidebar: () => void;
}
export const useAppStore = create<AppState>()(
devtools(
persist(
(set) => ({
theme: 'light',
sidebarOpen: true,
setTheme: (theme) => set({ theme }),
toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
}),
{ name: 'app-store' }
)
)
);Usage — Select Only What You Need
// GOOD — component re-renders only when theme changes
const theme = useAppStore((s) => s.theme);
// BAD — re-renders on ANY store change
const { theme } = useAppStore();Zustand Rules
- One store per domain (app, auth, notifications) — not one mega store
- Always use selectors for reads
- Use
persistmiddleware for state that survives refresh (theme, user preferences) - Use
devtoolsmiddleware in development - Keep actions in the store, not in components
- Never store server data in Zustand — use TanStack Query
3. Server State — TanStack Query
Use for: All data from APIs. Handles caching, refetching, loading states, error states, optimistic updates.
Setup
pnpm add @tanstack/react-query @tanstack/react-query-devtoolsProvider Setup
// src/providers/query-provider.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
gcTime: 5 * 60 * 1000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
export function QueryProvider({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}Query Pattern — Custom Hooks
// src/hooks/use-users.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: string) => [...userKeys.details(), id] as const,
};
export function useUsers(filters: UserFilters) {
return useQuery({
queryKey: userKeys.list(filters),
queryFn: () => api.users.list(filters),
});
}
export function useUser(id: string) {
return useQuery({
queryKey: userKeys.detail(id),
queryFn: () => api.users.get(id),
enabled: !!id,
});
}
export function useUpdateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: UpdateUserInput) => api.users.update(data),
onMutate: async (newData) => {
await queryClient.cancelQueries({ queryKey: userKeys.detail(newData.id) });
const previous = queryClient.getQueryData(userKeys.detail(newData.id));
queryClient.setQueryData(userKeys.detail(newData.id), (old: User) => ({
...old,
...newData,
}));
return { previous };
},
onError: (_err, newData, context) => {
queryClient.setQueryData(userKeys.detail(newData.id), context?.previous);
},
onSettled: (_data, _err, variables) => {
queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) });
},
});
}TanStack Query Rules
- NEVER store API data in useState or Zustand
- Every API call gets its own custom hook
- Query keys are structured objects (not strings)
- Use
enabledto conditionally fetch - Use
staleTime(not refetchInterval) for most cases - Optimistic updates for mutations that need instant feedback
- Invalidate related queries after mutations
4. URL State — Search Params
Use for: Filters, pagination, sort order, active tabs — anything the user should be able to bookmark or share.
Next.js (App Router)
'use client';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
export function useUrlState<T extends string>(key: string, defaultValue: T) {
const searchParams = useSearchParams();
const router = useRouter();
const pathname = usePathname();
const value = (searchParams.get(key) as T) ?? defaultValue;
const setValue = (newValue: T) => {
const params = new URLSearchParams(searchParams.toString());
if (newValue === defaultValue) {
params.delete(key);
} else {
params.set(key, newValue);
}
router.replace(`${pathname}?${params.toString()}`);
};
return [value, setValue] as const;
}Vite (with nuqs)
pnpm add nuqsimport { useQueryState, parseAsInteger } from 'nuqs';
function ProductList() {
const [search, setSearch] = useQueryState('q', { defaultValue: '' });
const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1));
const [sort, setSort] = useQueryState('sort', { defaultValue: 'newest' });
}Anti-Patterns to Avoid
| Anti-Pattern | Instead |
| Storing API data in useState | Use TanStack Query |
| Prop drilling through 4+ levels | Zustand store or composition |
| Context for frequently changing values | Zustand (Context causes full tree re-render) |
| One giant Redux/Zustand store | Split by domain |
| useEffect to sync state | Derive it or use useMemo |
| Fetching in useEffect | TanStack Query |
| Manual loading/error states | TanStack Query gives these for free |
| Duplicating server state in client | Single source: TanStack Query cache |
Testing State
Zustand — test the store directly
import { useAppStore } from '@/stores/use-app-store';
beforeEach(() => {
useAppStore.setState({ theme: 'light', sidebarOpen: true });
});
test('toggleSidebar flips the value', () => {
useAppStore.getState().toggleSidebar();
expect(useAppStore.getState().sidebarOpen).toBe(false);
});TanStack Query — use wrapper
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook, waitFor } from '@testing-library/react';
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
test('useUsers returns user list', async () => {
const { result } = renderHook(() => useUsers({}), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data).toHaveLength(3);
});Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

