| name | state-management |
| description | State management patterns. Local state, global state, server state. Zustand, Redux, Jotai, TanStack Query, React Context. |
State Management
Use the right tool for the right type of state.
1. State Classification
| Type | Description | Tool |
|---|
| Local UI | Component-only (open/closed, hover) | useState |
| Shared UI | Cross-component, no server | Zustand / Jotai / Context |
| Server/Async | Data from API, loading/error states | TanStack Query / SWR |
| URL | Navigation state, shareable | URLSearchParams / router |
| Form | Input values, validation | React Hook Form |
| Persistent | Survives page reload | localStorage + store |
2. Decision Tree
Is it server data?
└─ YES → TanStack Query / SWR
Is it only used in one component?
└─ YES → useState / useReducer
Is it form data?
└─ YES → React Hook Form
Is it global app state (auth, theme, cart)?
└─ YES → Zustand / Jotai
Does it need time-travel / devtools?
└─ YES → Redux Toolkit
Is it just prop drilling 2-3 levels?
└─ Use props, not context
3. TanStack Query (Server State)
const { data, isLoading, error } = useQuery({
queryKey: [, filters],
: (filters),
: * * ,
});
mutation = ({
: createUser,
: {
queryClient.({ : [] });
},
});
mutation = ({
: updateTodo,
: (newTodo) => {
queryClient.({ : [] });
prev = queryClient.([]);
queryClient.([],
old.( t. === newTodo. ? newTodo : t)
);
{ prev };
},
: {
queryClient.([], context.);
},
});