state-management
Skill110 starsChanged 9 months agoApache-2.0View on GitHub
Frontend state management patterns for React apps. Use when implementing Redux Toolkit, Zustand, Jotai, React Query, or any global state management solution.
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 2 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
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
- 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
- Piyush8296/claude-workspace★ 2same 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 repository75 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- algorithmic-artSkill
- api-designSkill
- apple-notesSkill
- apple-remindersSkill
- article-writingSkill
- async-pythonSkill
- brand-guidelinesSkill
- camsnapSkill
- canvas-designSkill
- celery-tasksSkill
- claude-apiSkill
- coding-agentSkill
- content-engineSkill
- diffsSkill
- doc-coauthoringSkill
- docker-deploymentSkill
- docxSkill
- e2e-testingSkill
- email-serviceSkill
- fastapi-backendSkill
- frontend-designSkill
- frontend-slidesSkill
- gh-issuesSkill
- githubSkill
- git-workflowSkill
- graphql-apiSkill
- healthcheckSkill
- internal-commsSkill
- investor-materialsSkill
- jwt-authenticationSkill
- market-researchSkill
- mcp-builderSkill
- mermaid-diagramsSkill
- microservicesSkill
- mobile-react-nativeSkill
- model-usageSkill
- nextjs-fullstackSkill
- nodejs-expressSkill
- obsidianSkill
- openai-whisperSkill
- oracleSkill
- pdfSkill
- peekabooSkill
- planning-with-filesSkill
- postgres-databaseSkill
- pptxSkill
- prisma-ormSkill
- proseSkill
- pytest-patternsSkill
- react-typescriptSkill
- redis-cachingSkill
- s3-file-storageSkill
- security-reviewSkill
- session-logsSkill
- skill-creatorSkill
- slack-gif-creatorSkill
- sqlalchemy-ormSkill
- strategic-compactSkill
- stripe-paymentsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 15 edited versions we read keep these.
2
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
- could be automatic: a setting could enforce it
- Distinctive: line 261
Never store server data in Redux/Zustand — that's React Query's job
- Distinctive: line 264
Always invalidate queries after mutations — never manually merge response into cache
“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 Patterns
Zustand (Recommended — simple & powerful)
// store/useAuthStore.ts
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface User {
id: string
email: string
name: string
}
interface AuthStore {
user: User | null
token: string | null
isLoading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => void
setUser: (user: User) => void
}
export const useAuthStore = create<AuthStore>()(
persist(
(set) => ({
user: null,
token: null,
isLoading: false,
login: async (email, password) => {
set({ isLoading: true })
try {
const { user, token } = await api.login(email, password)
set({ user, token, isLoading: false })
} catch (error) {
set({ isLoading: false })
throw error
}
},
logout: () => set({ user: null, token: null }),
setUser: (user) => set({ user }),
}),
{
name: 'auth-storage',
partialize: (state) => ({ token: state.token }), // Only persist token
}
)
)
// Usage
const { user, login, logout } = useAuthStore()
const isLoggedIn = useAuthStore((state) => state.user !== null)React Query / TanStack Query (Server state)
// lib/queryClient.ts
import { QueryClient } from '@tanstack/react-query'
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 min
retry: 1,
},
},
})
// hooks/useUsers.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
export function useUsers(filters?: UserFilters) {
return useQuery({
queryKey: ['users', filters],
queryFn: () => api.getUsers(filters),
staleTime: 30_000,
})
}
export function useUser(id: string) {
return useQuery({
queryKey: ['users', id],
queryFn: () => api.getUser(id),
enabled: !!id, // Don't run if no ID
})
}
export function useUpdateUser() {
const qc = useQueryClient()
return useMutation({
mutationFn: (data: UpdateUserInput) => api.updateUser(data),
onSuccess: (updatedUser) => {
// Optimistic update
qc.setQueryData(['users', updatedUser.id], updatedUser)
// Invalidate list
qc.invalidateQueries({ queryKey: ['users'] })
},
})
}
// Infinite scroll
export function useInfiniteUsers() {
return useInfiniteQuery({
queryKey: ['users', 'infinite'],
queryFn: ({ pageParam = 1 }) => api.getUsers({ page: pageParam }),
getNextPageParam: (lastPage) => lastPage.nextPage ?? undefined,
initialPageParam: 1,
})
}
// Component usage
function UserList() {
const { data, isLoading, error } = useUsers()
const { mutate: updateUser, isPending } = useUpdateUser()
if (isLoading) return <Skeleton />
if (error) return <ErrorMessage error={error} />
return data?.map(user => (
<UserCard
key={user.id}
user={user}
onUpdate={(data) => updateUser({ id: user.id, ...data })}
/>
))
}Redux Toolkit (Complex state)
// store/postsSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
interface Post { id: string; title: string; body: string }
interface PostsState {
items: Post[]
status: 'idle' | 'loading' | 'succeeded' | 'failed'
error: string | null
}
// Async thunk
export const fetchPosts = createAsyncThunk('posts/fetchAll', async () => {
return await api.getPosts()
})
export const postsSlice = createSlice({
name: 'posts',
initialState: { items: [], status: 'idle', error: null } as PostsState,
reducers: {
addPost: (state, action: PayloadAction<Post>) => {
state.items.push(action.payload)
},
removePost: (state, action: PayloadAction<string>) => {
state.items = state.items.filter(p => p.id !== action.payload)
},
},
extraReducers: (builder) => {
builder
.addCase(fetchPosts.pending, (state) => { state.status = 'loading' })
.addCase(fetchPosts.fulfilled, (state, action) => {
state.status = 'succeeded'
state.items = action.payload
})
.addCase(fetchPosts.rejected, (state, action) => {
state.status = 'failed'
state.error = action.error.message ?? null
})
},
})
// store/index.ts
import { configureStore } from '@reduxjs/toolkit'
import { useSelector, useDispatch } from 'react-redux'
export const store = configureStore({
reducer: { posts: postsSlice.reducer },
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
// Typed hooks
export const useAppSelector = useSelector.withTypes<RootState>()
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()Jotai (Atomic state)
// atoms/userAtom.ts
import { atom, useAtom, useAtomValue } from 'jotai'
import { atomWithStorage } from 'jotai/utils'
export const userAtom = atomWithStorage<User | null>('user', null)
export const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light')
// Derived atom
export const isAdminAtom = atom((get) => get(userAtom)?.role === 'ADMIN')
// Write-only atom (action)
export const logoutAtom = atom(null, (get, set) => {
set(userAtom, null)
set(themeAtom, 'light')
})
// Component
function Header() {
const user = useAtomValue(userAtom)
const isAdmin = useAtomValue(isAdminAtom)
const [, logout] = useAtom(logoutAtom)
return <nav>{user ? <button onClick={logout}>Logout</button> : null}</nav>
}Context + useReducer (Built-in, no deps)
// context/CartContext.tsx
type CartAction =
| { type: 'ADD_ITEM'; item: CartItem }
| { type: 'REMOVE_ITEM'; id: string }
| { type: 'CLEAR_CART' }
function cartReducer(state: CartItem[], action: CartAction): CartItem[] {
switch (action.type) {
case 'ADD_ITEM':
const existing = state.find(i => i.id === action.item.id)
if (existing) return state.map(i => i.id === action.item.id
? { ...i, quantity: i.quantity + 1 } : i)
return [...state, { ...action.item, quantity: 1 }]
case 'REMOVE_ITEM': return state.filter(i => i.id !== action.id)
case 'CLEAR_CART': return []
default: return state
}
}
const CartContext = createContext<{ cart: CartItem[]; dispatch: Dispatch<CartAction> } | null>(null)
export function CartProvider({ children }: { children: ReactNode }) {
const [cart, dispatch] = useReducer(cartReducer, [])
return <CartContext value={{ cart, dispatch }}>{children}</CartContext>
}
export const useCart = () => {
const ctx = use(CartContext)
if (!ctx) throw new Error('useCart must be used within CartProvider')
return ctx
}Rules
- Server state (API data): React Query / TanStack Query
- Global client state (auth, settings): Zustand or Jotai
- Complex local state (shopping cart, multi-step form): useReducer + Context
- Redux only for very large apps with complex cross-slice interactions
- Never store server data in Redux/Zustand — that's React Query's job
- Zustand: use selectors (
useStore(state => state.user)) not full store (prevents re-renders) - React Query: set
staleTimeappropriately — default is 0 (always refetch on mount) - Always invalidate queries after mutations — never manually merge response into cache
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.

