state-management
Skill14 starsChanged 9 months agoApache-2.0View on GitHub
Implement state management patterns for frontend applications. Use when managing global state, handling complex data flows, or coordinating state across components. Handles React Context, Redux, Zustand, Recoil, and state management best practices.
- Installs packages
- Sends data out
32 other projects use a version of this.
Adopted by
Most recently taken up by
- AtulPurohit/Antigravity-Awesome-Skillstheir own version, first seen Nov 29, 2026
- compozy/compozytheir own version, first seen Nov 28, 2026
- TheBeardedBearSAS/claude-crafttheir own version, first seen Nov 22, 2026
- novatic-cu/nova-skills-coretheir own version, first seen Nov 22, 2026
- PMDevSolutions/Aureliustheir own version, first seen Nov 16, 2026
- PMDevSolutions/Claudiustheir own version, first seen Nov 16, 2026
Used with
Projects with it also use css-architecture, accessibility-a11y and 9 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.
jayavibhavnkSkillcss-architecture
Design scalable CSS architecture - naming conventions, component styles, and organization.
Also in 4 projects that use this
JasonPaffSkillaccessibility-a11y
Implement web accessibility (a11y) best practices following WCAG guidelines to create inclusive, accessible user interfaces.
Also in 3 projects that use this
MicrosoftSkillerror-handling
统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。
Also in 6 projects that use this
lbednerSkilli18n
Use when a code or template change introduces a new translation message key, in either the framework CLI (aegis/i18n/locales/) or a generated project's CLI (the app/i18n/locales/ template tree). Covers adding the real English string, stubbing the same key into every other locale for parity, and the separate translation PR that later replaces placeholders with reviewed native text.
Also in 4 projects that use this
mijunriSkilldatabase
数据库脚本与操作规范。脚本放在 db_scripts 目录,遵循查询优化、事务、安全等实践。
Also in 3 projects that use this
nahisahoSkillsystem-architect
Copilot agent that assists with architecture design, C4 model diagrams, ADR creation, and tradeoff analysis
Also in 3 projects that use this
Other versions32 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 32
- compozy/compozy★ 2.9ksame name
- github/replica★ 400same name
- conorluddy/xclaude-plugin★ 186same name
- TheBeardedBearSAS/claude-craft★ 109same name
- cohen-liel/hivemind★ 108same name
- EmeaAppGbb/spec2cloud★ 103same name
- statelyai/skills★ 56same name
- komluk/scaffolding★ 16same name
- darknecrocities/SkillBuilder★ 13same name
- PMDevSolutions/Aurelius★ 9same name
22 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 repository1,129 other files it gives its agents.
- userinterface-wiki/AGENTS.mdAGENTS.md
- aaronontheweb-dotnet-skillsSkill
- ab-test-setupSkill
- acquiring-disk-image-with-dd-and-dcflddSkill
- Agent BrowserSkill
- agent-browserSkill
- agent-browserSkill
- agent-configurationSkill
- agent-email-cliSkill
- agent-evaluationSkill
- agentic-development-principlesSkill
- agentic-workflowSkill
- agent-toolsSkill
- ai-image-generationSkill
- ai-video-generationSkill
- algorithmic-artSkill
- analytics-trackingSkill
- analyzing-active-directory-acl-abuseSkill
- analyzing-android-malware-with-apktoolSkill
- analyzing-api-gateway-access-logsSkill
- analyzing-apt-group-with-mitre-navigatorSkill
- analyzing-azure-activity-logs-for-threatsSkill
- analyzing-bootkit-and-rootkit-samplesSkill
- analyzing-browser-forensics-with-hindsightSkill
- analyzing-campaign-attribution-evidenceSkill
- analyzing-certificate-transparency-for-phishingSkill
- analyzing-cloud-storage-access-patternsSkill
- analyzing-cobalt-strike-beacon-configurationSkill
- analyzing-cobaltstrike-malleable-c2-profilesSkill
- analyzing-cobalt-strike-malleable-profilesSkill
- analyzing-command-and-control-communicationSkill
- analyzing-cyber-kill-chainSkill
- analyzing-disk-image-with-autopsySkill
- analyzing-dns-logs-for-exfiltrationSkill
- analyzing-docker-container-forensicsSkill
- analyzing-email-headers-for-phishing-investigationSkill
- analyzing-ethereum-smart-contract-vulnerabilitiesSkill
- analyzing-golang-malware-with-ghidraSkill
- analyzing-heap-spray-exploitationSkill
- analyzing-indicators-of-compromiseSkill
- analyzing-ios-app-security-with-objectionSkill
- analyzing-kubernetes-audit-logsSkill
- analyzing-linux-audit-logs-for-intrusionSkill
- analyzing-linux-elf-malwareSkill
- analyzing-linux-kernel-rootkitsSkill
- analyzing-linux-system-artifactsSkill
- analyzing-lnk-file-and-jump-list-artifactsSkill
- analyzing-macro-malware-in-office-documentsSkill
- analyzing-malicious-pdf-with-peepdfSkill
- analyzing-malicious-url-with-urlscanSkill
- analyzing-malware-behavior-with-cuckoo-sandboxSkill
- analyzing-malware-family-relationships-with-malpediaSkill
- analyzing-malware-persistence-with-autorunsSkill
- analyzing-malware-sandbox-evasion-techniquesSkill
- analyzing-memory-dumps-with-volatilitySkill
- analyzing-memory-forensics-with-lime-and-volatilitySkill
- analyzing-mft-for-deleted-file-recoverySkill
- analyzing-network-covert-channels-in-malwareSkill
- analyzing-network-flow-data-with-netflowSkill
- analyzing-network-packets-with-scapySkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
8 rules. 0 are common, 8 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 24 edited versions we read keep these.
8
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 33
Use Context API, Redux, Zustand
- Distinctive: line 273
Use when complex state logic and middleware are required.
- Distinctive: line 480
State Immutability: Never mutate state directly
- Distinctive: line 489
Minimal State Principle: Do not store derivable values in state
- Distinctive: line 500
Single Source of Truth: Do not duplicate the same data in multiple places
- Distinctive: line 505
Use Context or a state management library
- Distinctive: line 507
Avoid Making Everything Global State: Prefer local state when sufficient
- Distinctive: line 522
Use TypeScript: Ensure type safety
“Common” is measured: kept by at least 6 in 10 of the 24 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
When to use this skill
- Global State Required: Multiple components share the same data
- Props Drilling Problem: Passing props through 5+ levels
- Complex State Logic: Authentication, shopping cart, themes, etc.
- State Synchronization: Sync server data with client state
Instructions
Step 1: Determine State Scope
Distinguish between local and global state.
Decision Criteria:
- Local State: Used only within a single component
- Form input values, toggle states, dropdown open/close
- Use
useState,useReducer
- Global State: Shared across multiple components
- User authentication, shopping cart, theme, language settings
- Use Context API, Redux, Zustand
Example:
// ✅ Local state (single component)
function SearchBox() {
const [query, setQuery] = useState('');
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => setIsOpen(true)}
/>
{isOpen && <SearchResults query={query} />}
</div>
);
}
// ✅ Global state (multiple components)
// User authentication info is used in Header, Profile, Settings, etc.
const { user, logout } = useAuth(); // Context or ZustandStep 2: React Context API (Simple Global State)
Suitable for lightweight global state management.
Example (Authentication Context):
// contexts/AuthContext.tsx
import { createContext, useContext, useState, ReactNode } from 'react';
interface User {
id: string;
email: string;
name: string;
}
interface AuthContextType {
user: User | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const login = async (email: string, password: string) => {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await response.json();
setUser(data.user);
localStorage.setItem('token', data.token);
};
const logout = () => {
setUser(null);
localStorage.removeItem('token');
};
return (
<AuthContext.Provider value={{
user,
login,
logout,
isAuthenticated: !!user
}}>
{children}
</AuthContext.Provider>
);
}
// Custom hook
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within AuthProvider');
}
return context;
}Usage:
// App.tsx
function App() {
return (
<AuthProvider>
<Router>
<Header />
<Routes />
</Router>
</AuthProvider>
);
}
// Header.tsx
function Header() {
const { user, logout, isAuthenticated } = useAuth();
return (
<header>
{isAuthenticated ? (
<>
<span>Welcome, {user!.name}</span>
<button onClick={logout}>Logout</button>
</>
) : (
<Link to="/login">Login</Link>
)}
</header>
);
}Step 3: Zustand (Modern and Concise State Management)
Simpler than Redux with less boilerplate.
Installation:
npm install zustandExample (Shopping Cart):
// stores/cartStore.ts
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartStore {
items: CartItem[];
addItem: (item: Omit<CartItem, 'quantity'>) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clearCart: () => void;
total: () => number;
}
export const useCartStore = create<CartStore>()(
devtools(
persist(
(set, get) => ({
items: [],
addItem: (item) => set((state) => {
const existing = state.items.find(i => i.id === item.id);
if (existing) {
return {
items: state.items.map(i =>
i.id === item.id
? { ...i, quantity: i.quantity + 1 }
: i
)
};
}
return { items: [...state.items, { ...item, quantity: 1 }] };
}),
removeItem: (id) => set((state) => ({
items: state.items.filter(item => item.id !== id)
})),
updateQuantity: (id, quantity) => set((state) => ({
items: state.items.map(item =>
item.id === id ? { ...item, quantity } : item
)
})),
clearCart: () => set({ items: [] }),
total: () => {
const { items } = get();
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
}),
{ name: 'cart-storage' } // localStorage key
)
)
);Usage:
// components/ProductCard.tsx
function ProductCard({ product }) {
const addItem = useCartStore(state => state.addItem);
return (
<div>
<h3>{product.name}</h3>
<p>${product.price}</p>
<button onClick={() => addItem(product)}>
Add to Cart
</button>
</div>
);
}
// components/Cart.tsx
function Cart() {
const items = useCartStore(state => state.items);
const total = useCartStore(state => state.total());
const removeItem = useCartStore(state => state.removeItem);
return (
<div>
<h2>Cart</h2>
{items.map(item => (
<div key={item.id}>
<span>{item.name} x {item.quantity}</span>
<span>${item.price * item.quantity}</span>
<button onClick={() => removeItem(item.id)}>Remove</button>
</div>
))}
<p>Total: ${total.toFixed(2)}</p>
</div>
);
}Step 4: Redux Toolkit (Large-Scale Apps)
Use when complex state logic and middleware are required.
Installation:
npm install @reduxjs/toolkit react-reduxExample (Todo):
// store/todosSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
interface Todo {
id: string;
text: string;
completed: boolean;
}
interface TodosState {
items: Todo[];
status: 'idle' | 'loading' | 'failed';
}
const initialState: TodosState = {
items: [],
status: 'idle'
};
// Async action
export const fetchTodos = createAsyncThunk('todos/fetch', async () => {
const response = await fetch('/api/todos');
return response.json();
});
const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
addTodo: (state, action: PayloadAction<string>) => {
state.items.push({
id: Date.now().toString(),
text: action.payload,
completed: false
});
},
toggleTodo: (state, action: PayloadAction<string>) => {
const todo = state.items.find(t => t.id === action.payload);
if (todo) {
todo.completed = !todo.completed;
}
},
removeTodo: (state, action: PayloadAction<string>) => {
state.items = state.items.filter(t => t.id !== action.payload);
}
},
extraReducers: (builder) => {
builder
.addCase(fetchTodos.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchTodos.fulfilled, (state, action) => {
state.status = 'idle';
state.items = action.payload;
})
.addCase(fetchTodos.rejected, (state) => {
state.status = 'failed';
});
}
});
export const { addTodo, toggleTodo, removeTodo } = todosSlice.actions;
export default todosSlice.reducer;
// store/index.ts
import { configureStore } from '@reduxjs/toolkit';
import todosReducer from './todosSlice';
export const store = configureStore({
reducer: {
todos: todosReducer
}
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;Usage:
// App.tsx
import { Provider } from 'react-redux';
import { store } from './store';
function App() {
return (
<Provider store={store}>
<TodoApp />
</Provider>
);
}
// components/TodoList.tsx
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '../store';
import { toggleTodo, removeTodo } from '../store/todosSlice';
function TodoList() {
const todos = useSelector((state: RootState) => state.todos.items);
const dispatch = useDispatch();
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => dispatch(toggleTodo(todo.id))}
/>
<span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
</span>
<button onClick={() => dispatch(removeTodo(todo.id))}>Delete</button>
</li>
))}
</ul>
);
}Step 5: Server State Management (React Query / TanStack Query)
Specialized for API data fetching and caching.
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function UserProfile({ userId }: { userId: string }) {
const queryClient = useQueryClient();
// GET: Fetch user info
const { data: user, isLoading, error } = useQuery({
queryKey: ['user', userId],
queryFn: async () => {
const res = await fetch(`/api/users/${userId}`);
return res.json();
},
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
});
// POST: Update user info
const mutation = useMutation({
mutationFn: async (updatedUser: Partial<User>) => {
const res = await fetch(`/api/users/${userId}`, {
method: 'PATCH',
body: JSON.stringify(updatedUser)
});
return res.json();
},
onSuccess: () => {
// Invalidate cache and refetch
queryClient.invalidateQueries({ queryKey: ['user', userId] });
}
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
<button onClick={() => mutation.mutate({ name: 'New Name' })}>
Update Name
</button>
</div>
);
}Output format
State Management Tool Selection Guide
Recommended tools by scenario:
1. Simple global state (theme, language)
→ React Context API
2. Medium complexity (shopping cart, user settings)
→ Zustand
3. Large-scale apps, complex logic, middleware required
→ Redux Toolkit
4. Server data fetching/caching
→ React Query (TanStack Query)
5. Form state
→ React Hook Form + ZodConstraints
Required Rules (MUST)
- State Immutability: Never mutate state directly
// ❌ Bad example state.items.push(newItem); // ✅ Good example setState({ items: [...state.items, newItem] }); - Minimal State Principle: Do not store derivable values in state
// ❌ Bad example const [items, setItems] = useState([]); const [count, setCount] = useState(0); // Can be calculated as items.length // ✅ Good example const [items, setItems] = useState([]); const count = items.length; // Derived value - Single Source of Truth: Do not duplicate the same data in multiple places
Prohibited Rules (MUST NOT)
- Excessive Props Drilling: Prohibited when passing props through 5+ levels
- Use Context or a state management library
- Avoid Making Everything Global State: Prefer local state when sufficient
Best practices
- Selective Subscription: Subscribe only to the state you need
// ✅ Good: only what you need const items = useCartStore(state => state.items); // ❌ Bad: subscribing to everything const { items, addItem, removeItem, updateQuantity, clearCart } = useCartStore(); - Clear Action Names:
update→updateUserProfile - Use TypeScript: Ensure type safety
References
Metadata
Version
- Current Version: 1.0.0
- Last Updated: 2025-01-01
- Compatible Platforms: Claude, ChatGPT, Gemini
Related Skills
- ui-component-patterns: Component and state integration
- backend-testing: Testing state logic
Tags
#state-management #React #Redux #Zustand #Context #global-state #frontend
Examples
Example 1: Basic usage
<!-- Add example content here -->Example 2: Advanced usage
<!-- Add advanced example content here -->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.

