state-management
Skill2 starsChanged 7 months agoMITView on GitHub
State management strategies for React — local state, server state, global state, URL state. Use when deciding state architecture, implementing data fetching, or managing complex state.
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 testing and api-design.
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.
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 · 0
None found.
Edited · 0
None found.
Wrote their own version · 18
- 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
- PMDevSolutions/Aurelius★ 8same name
- YepAPI/skills★ 8same name
8 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 repository18 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- accessibilitySkill
- api-layerSkill
- auth-patternsSkill
- core-web-vitalsSkill
- css-architectureSkill
- design-intelligenceSkill
- error-handlingSkill
- frontend-designSkill
- i18nSkill
- monorepo-patternsSkill
- performance-optimizationSkill
- react-patternsSkill
- security-auditSkill
- seo-fundamentalsSkill
- structured-dataSkill
- systematic-debuggingSkill
- testing-strategySkill
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 1 is distinctive, and 1 is very specific to this project.
0
Common
Most of the 15 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 10
Before choosing a tool, classify the state:
- Very specific: line 21
Golden rule: Use the simplest tool that fits.
“Common” is measured: kept by at least 6 in 10 of the 15 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
The State Classification Framework
Before choosing a tool, classify the state:
| Type | Scope | Tool | Example |
| UI State | Single component | useState | Modal open, input value |
| Shared UI State | Few components | Lift state + props / Context | Active tab, sidebar collapsed |
| Server State | Cached remote data | TanStack Query / SWR | User list, profile data |
| Global App State | Entire app | Zustand / Jotai | Auth, theme, feature flags |
| URL State | Navigation | useSearchParams / router | Filters, pagination, sort |
| Form State | Form lifecycle | React Hook Form / Formik | Input values, validation |
Golden rule: Use the simplest tool that fits. useState > Context > Zustand > Redux.
Server State (TanStack Query)
This is the most common state type in frontend apps. Most "global state" is actually server state.
Query Pattern
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
// Query keys as const for type safety
export 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,
};
// Query hook
export function useUsers(filters: UserFilters) {
return useQuery({
queryKey: userKeys.list(filters),
queryFn: () => api.users.list(filters),
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
// Mutation hook with cache invalidation
export function useCreateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: api.users.create,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
toast.success('User created');
},
onError: (error) => {
console.error('createUser failed:', error);
toast.error('Failed to create user');
},
});
}Optimistic Updates
export function useToggleFavorite() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: api.favorites.toggle,
onMutate: async (itemId) => {
// Cancel outgoing queries
await queryClient.cancelQueries({ queryKey: ['items', itemId] });
// Snapshot previous value
const previous = queryClient.getQueryData(['items', itemId]);
// Optimistically update
queryClient.setQueryData(['items', itemId], (old: Item) => ({
...old,
isFavorite: !old.isFavorite,
}));
return { previous };
},
onError: (_err, itemId, context) => {
// Rollback on error
queryClient.setQueryData(['items', itemId], context?.previous);
toast.error('Failed to update');
},
onSettled: (_data, _err, itemId) => {
// Refetch to ensure consistency
queryClient.invalidateQueries({ queryKey: ['items', itemId] });
},
});
}Global App State (Zustand)
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
interface AuthStore {
user: User | null;
token: string | null;
login: (credentials: Credentials) => Promise<void>;
logout: () => void;
isAuthenticated: () => boolean;
}
export const useAuthStore = create<AuthStore>()(
devtools(
persist(
(set, get) => ({
user: null,
token: null,
login: async (credentials) => {
const { user, token } = await api.auth.login(credentials);
set({ user, token }, false, 'auth/login');
},
logout: () => {
set({ user: null, token: null }, false, 'auth/logout');
},
isAuthenticated: () => get().token !== null,
}),
{ name: 'auth-storage' }
),
{ name: 'AuthStore' }
)
);Zustand best practices:
- One store per domain (auth, theme, layout) — not one mega-store
- Selectors to prevent unnecessary re-renders:
useAuthStore((s) => s.user) - Actions inside the store, not in components
devtoolsmiddleware in development for debugging
URL State
import { useSearchParams } from 'react-router-dom'; // or next/navigation
function useFilters() {
const [searchParams, setSearchParams] = useSearchParams();
const filters = {
query: searchParams.get('q') ?? '',
page: Number(searchParams.get('page') ?? '1'),
sort: (searchParams.get('sort') ?? 'newest') as SortOption,
};
const setFilter = (key: string, value: string) => {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
if (value) {
next.set(key, value);
} else {
next.delete(key);
}
// Reset page when filters change
if (key !== 'page') next.set('page', '1');
return next;
});
};
return { filters, setFilter };
}When to use URL state: Filters, pagination, sort order, selected tabs, modal open state — anything the user might want to share via link or use browser back/forward.
Decision Framework
Is it from an API?
→ Yes: TanStack Query (server state)
→ No: Continue
Should it survive page refresh?
→ Yes, in URL: useSearchParams (URL state)
→ Yes, persisted: Zustand with persist (global state)
→ No: Continue
Used by many unrelated components?
→ Yes: Zustand store (global state)
→ No: Continue
Used by parent + 1-2 children?
→ Yes: Lift state to parent (local/shared state)
→ No: useState in the component (local state)Anti-Patterns
| Bad | Good | Why |
useEffect to sync state | Derive from source | Extra render cycle, bug-prone |
| Global store for form values | React Hook Form / local state | Forms are local by nature |
| Context for frequently updating values | Zustand with selectors | Context re-renders all consumers |
Fetching in useEffect | TanStack Query | No caching, no loading/error states, race conditions |
| Prop drilling 4+ levels | Zustand or Context | Maintenance burden |
Integration with Other Skills
- react-patterns: Component state handling order
- testing-strategy: Mocking stores and query clients in tests
- performance-optimization: Selector optimization, re-render prevention
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.

