---
name: state-management
description: 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.
metadata:
tags: state-management, React, Redux, Context, Zustand, Recoil, global-state
platforms: Claude, ChatGPT, Gemini
---
# 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**:
```tsx
// ✅ Local state (single component)
function SearchBox() {
const [query, setQuery] = useState('');
const [isOpen, setIsOpen] = useState(false);
return (
);
}
```
### Step 5: Server State Management (React Query / TanStack Query)
Specialized for API data fetching and caching.
```tsx
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) => {
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
Loading...
;
if (error) return
Error: {error.message}
;
return (
{user.name}
{user.email}
);
}
```
## 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 + Zod
```
## Constraints
### Required Rules (MUST)
1. **State Immutability**: Never mutate state directly
```tsx
// ❌ Bad example
state.items.push(newItem);
// ✅ Good example
setState({ items: [...state.items, newItem] });
```
2. **Minimal State Principle**: Do not store derivable values in state
```tsx
// ❌ 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
```
3. **Single Source of Truth**: Do not duplicate the same data in multiple places
### Prohibited Rules (MUST NOT)
1. **Excessive Props Drilling**: Prohibited when passing props through 5+ levels
- Use Context or a state management library
2. **Avoid Making Everything Global State**: Prefer local state when sufficient
## Best practices
1. **Selective Subscription**: Subscribe only to the state you need
```tsx
// ✅ Good: only what you need
const items = useCartStore(state => state.items);
// ❌ Bad: subscribing to everything
const { items, addItem, removeItem, updateQuantity, clearCart } = useCartStore();
```
2. **Clear Action Names**: `update` → `updateUserProfile`
3. **Use TypeScript**: Ensure type safety
## References
- [Zustand](https://zustand-demo.pmnd.rs/)
- [Redux Toolkit](https://redux-toolkit.js.org/)
- [React Query](https://tanstack.com/query/latest)
- [Jotai](https://jotai.org/)
- [Recoil](https://recoiljs.org/)
## Metadata
### Version
- **Current Version**: 1.0.0
- **Last Updated**: 2025-01-01
- **Compatible Platforms**: Claude, ChatGPT, Gemini
### Related Skills
- [ui-component-patterns](../ui-component-patterns/SKILL.md): Component and state integration
- [backend-testing](../../backend/backend-testing/SKILL.md): Testing state logic
### Tags
`#state-management` `#React` `#Redux` `#Zustand` `#Context` `#global-state` `#frontend`
## Examples
### Example 1: Basic usage
### Example 2: Advanced usage