No slash command · from react-plugin
Decision tree for React SPA state management: useState/useReducer, Context API, Zustand, Jotai, Redux Toolkit, TanStack Query, SWR. Detects installed libraries and applies matching patterns for local, shared UI, server, and form state.
Ships in react-plugin. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
There is no one-size-fits-all state tool. This skill covers the most common choices and when each fits.
| Data | Tool |
|---|---|
| Local component state (count, isOpen, hover) | useState, useReducer |
| Shared between siblings / parent-child | Lift to common parent + props |
| App-wide UI state (theme, locale, sidebar open) | Context, Zustand, Jotai |
| Complex domain state with many actions | Redux Toolkit (or Zustand for simpler cases) |
| Server data with caching, pagination, refetch | TanStack Query, SWR |
| Form state | react-hook-form (see react-forms skill) |
| URL-synced state | URL params via useSearchParams |
Detect what the project uses and follow its pattern. Don't introduce a new state lib without BA approval.
useState and useReducerconst [count, setCount] = useState(0);
// Function form for updates depending on previous state
setCount((c) => c + 1);
// Reducer for complex state with discriminated actions
const [state, dispatch] = useReducer(reducer, initialState);
When state has more than ~3 fields and updates are coordinated, prefer useReducer:
type State = { items: Item[]; loading: boolean; error: string | null };
type Action =
| { type: 'fetch_start' }
| { type: 'fetch_success'; items: Item[] }
| { type: 'fetch_error'; error: string };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'fetch_start': return { ...state, loading: true, error: null };
case 'fetch_success': return { ...state, loading: false, items: action.items };
case 'fetch_error': return { ...state, loading: false, error: action.error };
}
}
For values shared across many components without prop drilling. Best for relatively static or rarely-changing data (theme, locale, current user).
import { createContext, useContext, useState } from 'react';
type Theme = 'light' | 'dark';
const ThemeContext = createContext<{ theme: Theme; setTheme: (t: Theme) => void } | null>(null);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<Theme>('light');
return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
return ctx;
}
Every consumer of a Context re-renders when the Context value changes. For frequently-updating state, this is expensive. Solutions:
const value = useMemo(() => ({ theme, setTheme }), [theme]).For app-wide state that updates frequently, prefer Zustand/Jotai over Context.
Lightweight (pnpm add zustand). Simple API, no Provider needed.
// stores/userStore.ts
import { create } from 'zustand';
type User = { id: string; name: string };
type UserStore = {
user: User | null;
setUser: (user: User | null) => void;
logout: () => void;
};
export const useUserStore = create<UserStore>((set) => ({
user: null,
setUser: (user) => set({ user }),
logout: () => set({ user: null }),
}));
Usage:
const user = useUserStore((s) => s.user);
const setUser = useUserStore((s) => s.setUser);
Selectors ((s) => s.user) prevent unrelated re-renders. Without a selector, the component re-renders on every store change.
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
export const useUserStore = create(
persist(
(set) => ({ user: null, setUser: (user) => set({ user }) }),
{ name: 'user-storage', storage: createJSONStorage(() => sessionStorage) }
)
);
NEVER persist auth tokens to localStorage / sessionStorage — XSS risk.
Atomic state — each piece is an atom. Best for fine-grained state where many components subscribe to small slices.
import { atom, useAtom } from 'jotai';
export const userAtom = atom<User | null>(null);
export const themeAtom = atom<'light' | 'dark'>('light');
// Derived atom
export const isAuthenticatedAtom = atom((get) => get(userAtom) !== null);
Usage:
const [user, setUser] = useAtom(userAtom);
const isAuth = useAtomValue(isAuthenticatedAtom);
Jotai is great for forms with many independent fields, atomic updates, or React Suspense integration. Less idiomatic for big domain stores.
For complex domain state with many actions, time-travel debugging, or large team conventions.
// features/users/usersSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
export const fetchUsers = createAsyncThunk('users/fetch', async () => {
const res = await fetch('/api/users');
return res.json() as Promise<User[]>;
});
const slice = createSlice({
name: 'users',
initialState: { items: [] as User[], loading: false, error: null as string | null },
reducers: {
add: (state, action: PayloadAction<User>) => {
state.items.push(action.payload);
},
},
extraReducers: (builder) => {
builder
.addCase(fetchUsers.pending, (state) => { state.loading = true; })
.addCase(fetchUsers.fulfilled, (state, action) => { state.loading = false; state.items = action.payload; })
.addCase(fetchUsers.rejected, (state, action) => { state.loading = false; state.error = action.error.message ?? 'failed'; });
},
});
export const { add } = slice.actions;
export default slice.reducer;
// store.ts
import { configureStore } from '@reduxjs/toolkit';
import users from './features/users/usersSlice';
export const store = configureStore({ reducer: { users } });
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
// hooks.ts
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();
For most apps in 2024+, RTK is overkill — Zustand or Jotai is lighter. Pick RTK when:
For data that lives on the server. Handles caching, deduplication, refetching, pagination, mutation-then-invalidation.
// features/users/api.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
export function useUsers() {
return useQuery({
queryKey: ['users'],
queryFn: async () => {
const res = await fetch('/api/users');
if (!res.ok) throw new Error('Failed to fetch');
return res.json() as Promise<User[]>;
},
});
}
export function useUser(id: string) {
return useQuery({
queryKey: ['users', id],
queryFn: () => fetch(`/api/users/${id}`).then((r) => r.json() as Promise<User>),
enabled: !!id,
});
}
export function useCreateUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: (input: CreateUserInput) =>
fetch('/api/users', { method: 'POST', body: JSON.stringify(input) }).then((r) => r.json()),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['users'] });
},
});
}
Usage:
function UsersList() {
const { data, isLoading, error } = useUsers();
if (isLoading) return <Spinner />;
if (error) return <Error error={error} />;
return <ul>{data?.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}
Use array keys with hierarchical structure:
['users'] // list
['users', id] // single
['users', { filter: 'active' }] // filtered list
['users', id, 'orders'] // sub-resource
invalidateQueries({ queryKey: ['users'] }) invalidates ALL keys starting with ['users'] — handy for "users changed somewhere, refresh everything."
const { mutate, isPending } = useCreateUser();
mutate({ email: '[email protected]', name: 'Alice' }, {
onSuccess: (user) => router.push(`/users/${user.id}`),
onError: (err) => toast.error(err.message),
});
Always invalidate or update queries after mutation success. Otherwise UI shows stale data.
useMutation({
mutationFn: deleteUser,
onMutate: async (id) => {
await qc.cancelQueries({ queryKey: ['users'] });
const previous = qc.getQueryData<User[]>(['users']);
qc.setQueryData<User[]>(['users'], (old) => old?.filter((u) => u.id !== id) ?? []);
return { previous };
},
onError: (_err, _id, context) => {
qc.setQueryData(['users'], context?.previous);
},
onSettled: () => qc.invalidateQueries({ queryKey: ['users'] }),
});
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then((r) => r.json());
function Users() {
const { data, error, isLoading } = useSWR<User[]>('/api/users', fetcher);
if (isLoading) return <Spinner />;
if (error) return <Error />;
return <ul>{data?.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}
Simpler API than TanStack Query, slightly less feature-rich. Match the project.
useSearchParams)For state that should be shareable / bookmarkable / browser-back-compatible:
import { useSearchParams } from 'react-router-dom';
function FilteredList() {
const [params, setParams] = useSearchParams();
const filter = params.get('filter') ?? 'all';
return (
<>
<select value={filter} onChange={(e) => setParams({ filter: e.target.value })}>
<option value="all">All</option>
<option value="active">Active</option>
</select>
</>
);
}
Use for filters, pagination, sort order, search queries — anything users want to return to.
useState + a Context would do.invalidateQueries after mutations — stale UI.useState and manually refetching — that's what TanStack Query/SWR are for.useState calls for clearly-coordinated state — use useReducer.state.items.push(x) followed by setState(state)) — React shallow-compares; same reference = no re-render.dispatch(action()) outside a Redux Toolkit slice — actions ARE creators in RTK, just call dispatch(slice.actions.add(payload)).What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
state-management, react-state, zustand, jotai, redux-toolkit, tanstack-query
npx claudepluginhub aratkruglik/claude-sdlc --plugin react-plugin5 skills in this plugin
/react-conventionsReact component structure, hooks rules, file naming, project layout, composition patterns, performance idioms, and effects discipline. Apply when implementing or modifying React SPA code.
Use this skill to:
- Structure a new component or feature folder.
- Apply hooks correctly (rules, naming, dependency arrays).
- Compose components via children, render props, or compound patterns.
- Write effects only when needed (and avoid common misuses).
- Pick performance escape hatches (memo, useMemo, useCallback) when justified.
Do NOT use this skill for:
- State management lib choice (see react-state-management).
- Routing primitives (see react-routing).
- Form patterns (see react-forms).
- Testing (see react-testing).
/react-formsForm patterns for React: react-hook-form (most common), Formik (legacy/stable), TanStack Form (newer). Validation via zod / yup / valibot. Controlled vs uncontrolled inputs, field arrays, multi-step wizards.
Use this skill to:
- Wire react-hook-form with a validation schema.
- Pick between controlled and uncontrolled patterns.
- Build multi-step forms with state preservation.
- Handle async validation (e.g., username availability).
- Integrate forms with TanStack Query mutations.
Do NOT use this skill for:
- General state management (see react-state-management).
- Routing (see react-routing).
- Component conventions (see react-conventions).
- Testing forms (see react-testing).
/react-routingRouting libraries for React SPAs: React Router v6/v7 (most common), TanStack Router (typed, modern), wouter (minimal). Detect what's installed and apply matching patterns. Lazy loading, navigation guards, typed params.
Use this skill to:
- Configure routes (declarative or file-based).
- Use navigation hooks (useNavigate, useParams, useSearchParams).
- Lazy-load routes for code splitting.
- Implement protected routes / auth guards.
- Type-safe params via Zod or framework's built-ins.
Do NOT use this skill for:
- General React conventions (see react-conventions).
- State management (see react-state-management).
- Form handling (see react-forms).
- Next.js routing (different model — see nextjs-plugin).
/react-testingTesting React SPAs: React Testing Library + Vitest/Jest for components and hooks, msw for network mocks, Playwright/Cypress for e2e. Query priority, user events, async assertions, mocking patterns.
Use this skill to:
- Pick the right runner (Vitest vs Jest) and setup.
- Write component tests with RTL using accessible queries.
- Test custom hooks via renderHook.
- Mock network with msw at the boundary.
- Set up Playwright or Cypress for end-to-end coverage.
Do NOT use this skill for:
- General React conventions (see react-conventions).
- State management testing patterns specific to a store lib (see react-state-management).
- Form-specific testing (apply react-forms patterns inside test).
Other plugins' skills for the same job