secondsky/claude-skills / plugins/zustand-state-management/skills/zustand-state-management
zustand-state-management
VerifiedZustand state management for React with TypeScript. Use for global state, Redux/Context API migration, localStorage persistence, slices pattern, devtools, Next.js SSR, or encountering hydration errors, TypeScript inference issues, persist middleware problems, infinite render loops.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 9.7 KB |
| assets/example-template.txt | markdown | 416 B |
| references/advanced-topics.md | markdown | 7.9 KB |
| references/common-patterns.md | markdown | 6.4 KB |
| references/example-reference.md | markdown | 760 B |
| references/known-issues.md | markdown | 5.4 KB |
| references/middleware-guide.md | markdown | 5.2 KB |
| references/migration-guide.md | markdown | 6.2 KB |
| references/nextjs-hydration.md | markdown | 5.0 KB |
| references/typescript-patterns.md | markdown | 4.9 KB |
| scripts/check-versions.shexecutable | script | 3.6 KB |
| scripts/example-script.shexecutable | script | 302 B |
| templates/async-actions-store.ts | script | 7.6 KB |
| templates/basic-store.ts | script | 908 B |
| templates/computed-store.ts | script | 5.6 KB |
| templates/devtools-store.ts | script | 3.4 KB |
| templates/nextjs-store.ts | script | 2.6 KB |
| templates/persist-store.ts | script | 2.8 KB |
| templates/slices-pattern.ts | script | 5.0 KB |
| templates/typescript-store.ts | script | 1.8 KB |
templates/async-actions-store.ts
View on GitHub/**
* Zustand Store with Async Actions
*
* Use when:
* - Fetching data from APIs
* - Need loading/error states
* - Handling async operations
*
* Pattern: Actions can be async, just call set() when done
*
* Features:
* - Loading states
* - Error handling
* - Optimistic updates
* - Request cancellation
*
* NOTE: For server state (data fetching), consider TanStack Query instead!
* Zustand is better for client state. But this pattern works for simple cases.
*
* Learn more: See SKILL.md Common Patterns section
*/
import { create } from 'zustand'
interface User {
id: string
name: string
email: string
}
interface Post {
id: string
title: string
body: string
userId: string
}
interface AsyncStore {
// Data state
user: User | null
posts: Post[]
// Loading states
isLoadingUser: boolean
isLoadingPosts: boolean
isSavingPost: boolean
// Error states
userError: string | null
postsError: string | null
saveError: string | null
// Actions
fetchUser: (userId: string) => Promise<void>
fetchPosts: (userId: string) => Promise<void>
createPost: (post: Omit<Post, 'id'>) => Promise<void>
deletePost: (postId: string) => Promise<void>
reset: () => void
}
export const useAsyncStore = create<AsyncStore>()((set, get) => ({
// Initial state
user: null,
posts: [],
isLoadingUser: false,
isLoadingPosts: false,
isSavingPost: false,
userError: null,
postsError: null,
saveError: null,
// Fetch user
fetchUser: async (userId) => {
set({ isLoadingUser: true, userError: null })
try {
const response = await fetch(`https://api.example.com/users/${userId}`)
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.statusText}`)
}
const user = await response.json()
set({ user, isLoadingUser: false })
} catch (error) {
set({
userError: (error as Error).message,
isLoadingUser: false,
user: null,
})
}
},
// Fetch posts
fetchPosts: async (userId) => {
set({ isLoadingPosts: true, postsError: null })
try {
const response = await fetch(`https://api.example.com/users/${userId}/posts`)
if (!response.ok) {
throw new Error(`Failed to fetch posts: ${response.statusText}`)
}
const posts = await response.json()
set({ posts, isLoadingPosts: false })
} catch (error) {
set({
postsError: (error as Error).message,
isLoadingPosts: false,
})
}
},
// Create post with optimistic update
createPost: async (post) => {
const tempId = `temp-${Date.now()}`
const optimisticPost = { ...post, id: tempId }
// Optimistic update
set((state) => ({
posts: [...state.posts, optimisticPost],
isSavingPost: true,
saveError: null,
}))
try {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post),
})
if (!response.ok) {
throw new Error(`Failed to create post: ${response.statusText}`)
}
const savedPost = await response.json()
// Replace optimistic post with real one
set((state) => ({
posts: state.posts.map((p) =>
p.id === tempId ? savedPost : p
),
isSavingPost: false,
}))
} catch (error) {
// Rollback optimistic update
set((state) => ({
posts: state.posts.filter((p) => p.id !== tempId),
saveError: (error as Error).message,
isSavingPost: false,
}))
}
},
// Delete post
deletePost: async (postId) => {
// Store original posts for rollback
const originalPosts = get().posts
// Optimistic update
set((state) => ({
posts: state.posts.filter((p) => p.id !== postId),
}))
try {
const response = await fetch(`https://api.example.com/posts/${postId}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error(`Failed to delete post: ${response.statusText}`)
}
} catch (error) {
// Rollback on error
set({
posts: originalPosts,
saveError: (error as Error).message,
})
}
},
// Reset
reset: () =>
set({
user: null,
posts: [],
isLoadingUser: false,
isLoadingPosts: false,
isSavingPost: false,
userError: null,
postsError: null,
saveError: null,
}),
}))
/**
* Usage in components:
*
* function UserProfile({ userId }: { userId: string }) {
* const user = useAsyncStore((state) => state.user)
* const isLoading = useAsyncStore((state) => state.isLoadingUser)
* const error = useAsyncStore((state) => state.userError)
* const fetchUser = useAsyncStore((state) => state.fetchUser)
*
* useEffect(() => {
* fetchUser(userId)
* }, [userId, fetchUser])
*
* if (isLoading) return <div>Loading...</div>
* if (error) return <div>Error: {error}</div>
* if (!user) return <div>No user found</div>
*
* return (
* <div>
* <h1>{user.name}</h1>
* <p>{user.email}</p>
* </div>
* )
* }
*
* function PostsList({ userId }: { userId: string }) {
* const posts = useAsyncStore((state) => state.posts)
* const isLoading = useAsyncStore((state) => state.isLoadingPosts)
* const error = useAsyncStore((state) => state.postsError)
* const fetchPosts = useAsyncStore((state) => state.fetchPosts)
* const deletePost = useAsyncStore((state) => state.deletePost)
*
* useEffect(() => {
* fetchPosts(userId)
* }, [userId, fetchPosts])
*
* if (isLoading) return <div>Loading posts...</div>
* if (error) return <div>Error: {error}</div>
*
* return (
* <ul>
* {posts.map((post) => (
* <li key={post.id}>
* <h3>{post.title}</h3>
* <p>{post.body}</p>
* <button onClick={() => deletePost(post.id)}>Delete</button>
* </li>
* ))}
* </ul>
* )
* }
*
* function CreatePostForm({ userId }: { userId: string }) {
* const [title, setTitle] = useState('')
* const [body, setBody] = useState('')
* const createPost = useAsyncStore((state) => state.createPost)
* const isSaving = useAsyncStore((state) => state.isSavingPost)
* const error = useAsyncStore((state) => state.saveError)
*
* const handleSubmit = async (e: FormEvent) => {
* e.preventDefault()
* await createPost({ title, body, userId })
* setTitle('')
* setBody('')
* }
*
* return (
* <form onSubmit={handleSubmit}>
* <input
* value={title}
* onChange={(e) => setTitle(e.target.value)}
* placeholder="Title"
* />
* <textarea
* value={body}
* onChange={(e) => setBody(e.target.value)}
* placeholder="Body"
* />
* <button type="submit" disabled={isSaving}>
* {isSaving ? 'Creating...' : 'Create Post'}
* </button>
* {error && <div>Error: {error}</div>}
* </form>
* )
* }
*
* ADVANCED: Request Cancellation with AbortController
*
* let abortController: AbortController | null = null
*
* fetchUserWithCancellation: async (userId) => {
* // Cancel previous request
* abortController?.abort()
* abortController = new AbortController()
*
* set({ isLoadingUser: true, userError: null })
*
* try {
* const response = await fetch(
* `https://api.example.com/users/${userId}`,
* { signal: abortController.signal }
* )
* // ... rest of fetch logic
* } catch (error) {
* if (error.name === 'AbortError') {
* // Request was cancelled
* return
* }
* // ... handle other errors
* }
* }
*/
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |