Files
skills/public/frontend-react-state-management.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

806 lines
34 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>frontend-react-state-management</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/frontend-react-state-management.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/frontend-react-state-management">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/frontend-react-state-management.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>frontend-react-state-management</h1><p class="lede">Choosing state management solution</p><h1>React State Management</h1>
<p><strong>Scope</strong>: Context, Zustand, Jotai, Redux Toolkit, when to use each, state patterns <strong>Lines</strong>: ~300 <strong>Last Updated</strong>: 2025-10-18</p>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Choosing state management solution</li><li>Managing global application state</li><li>Sharing state across components</li><li>Optimizing state updates and re-renders</li><li>Migrating between state libraries</li><li>Debugging state management issues</li></ul>
<h2>Core Concepts</h2>
<h3>State Types</h3>
<p><strong>Local State</strong> - Component-specific</p>
<pre><code class="lang-tsx">const [count, setCount] = useState(0);</code></pre>
<p><strong>Shared State</strong> - Multiple components</p>
<pre><code class="lang-tsx">const theme = useContext(ThemeContext);</code></pre>
<p><strong>Global State</strong> - Application-wide</p>
<pre><code class="lang-tsx">const user = useStore(state =&gt; state.user);</code></pre>
<p><strong>Server State</strong> - Data from API</p>
<pre><code class="lang-tsx">const { data: posts } = useSWR(&#x27;/api/posts&#x27;);</code></pre>
<hr>
<h2>When to Use Each Solution</h2>
<h3>Decision Tree</h3>
<pre><code>State needed by single component? → useState
↓
State needed by 2-3 nearby components? → Lift state up or useContext
↓
State needed across app (5+ components)? → Zustand or Jotai
↓
Complex state logic (reducers, middleware)? → Redux Toolkit
↓
Server data (API, caching, revalidation)? → SWR or React Query</code></pre>
<h3>Comparison Matrix</h3>
<p>| Library | Complexity | Bundle Size | DevTools | Best For | |---------|-----------|-------------|----------|----------| | <strong>Context</strong> | Low | 0kb (built-in) | No | Small apps, theming | | <strong>Zustand</strong> | Low | 1.2kb | Yes | Most apps, simple global state | | <strong>Jotai</strong> | Medium | 3kb | Yes | Atomic state, derived values | | <strong>Redux Toolkit</strong> | High | 8kb | Excellent | Large apps, complex logic |</p>
<hr>
<h2>React Context</h2>
<h3>Basic Context Pattern</h3>
<pre><code class="lang-tsx">// contexts/ThemeContext.tsx
import { createContext, useContext, useState } from &#x27;react&#x27;;
type Theme = &#x27;light&#x27; | &#x27;dark&#x27;;
const ThemeContext = createContext&lt;{
theme: Theme;
setTheme: (theme: Theme) =&gt; void;
} | null&gt;(null);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState&lt;Theme&gt;(&#x27;light&#x27;);
return (
&lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;
{children}
&lt;/ThemeContext.Provider&gt;
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) throw new Error(&#x27;useTheme must be used within ThemeProvider&#x27;);
return context;
}
// Usage
function App() {
return (
&lt;ThemeProvider&gt;
&lt;Header /&gt;
&lt;Main /&gt;
&lt;/ThemeProvider&gt;
);
}
function Header() {
const { theme, setTheme } = useTheme();
return (
&lt;button onClick={() =&gt; setTheme(theme === &#x27;light&#x27; ? &#x27;dark&#x27; : &#x27;light&#x27;)}&gt;
Toggle: {theme}
&lt;/button&gt;
);
}</code></pre>
<h3>Context Performance Optimization</h3>
<pre><code class="lang-tsx">// Split context to prevent unnecessary re-renders
const UserContext = createContext&lt;User | null&gt;(null);
const UserActionsContext = createContext&lt;{
login: (email: string, password: string) =&gt; void;
logout: () =&gt; void;
} | null&gt;(null);
function UserProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState&lt;User | null&gt;(null);
// Memoize actions to prevent re-renders
const actions = useMemo(() =&gt; ({
login: async (email: string, password: string) =&gt; {
const user = await loginAPI(email, password);
setUser(user);
},
logout: () =&gt; setUser(null),
}), []);
return (
&lt;UserContext.Provider value={user}&gt;
&lt;UserActionsContext.Provider value={actions}&gt;
{children}
&lt;/UserActionsContext.Provider&gt;
&lt;/UserContext.Provider&gt;
);
}
// Components only re-render when user changes (not actions)
function UserProfile() {
const user = useContext(UserContext);
return &lt;div&gt;{user?.name}&lt;/div&gt;;
}
// Components using actions don&#x27;t re-render when user changes
function LogoutButton() {
const { logout } = useContext(UserActionsContext)!;
return &lt;button onClick={logout}&gt;Logout&lt;/button&gt;;
}</code></pre>
<p><strong>When to use Context</strong>:</p>
<ul><li>Simple state (theme, locale, auth user)</li><li>2-5 consumers</li><li>Infrequent updates</li><li>Small apps</li></ul>
<p><strong>When NOT to use Context</strong>:</p>
<ul><li>Frequent updates (causes re-renders)</li><li>Many consumers (performance issues)</li><li>Complex state logic</li></ul>
<hr>
<h2>Zustand</h2>
<h3>Basic Store</h3>
<pre><code class="lang-tsx">// stores/useStore.ts
import { create } from &#x27;zustand&#x27;;
interface Todo {
id: string;
title: string;
completed: boolean;
}
interface TodoStore {
todos: Todo[];
addTodo: (title: string) =&gt; void;
toggleTodo: (id: string) =&gt; void;
deleteTodo: (id: string) =&gt; void;
}
export const useTodoStore = create&lt;TodoStore&gt;((set) =&gt; ({
todos: [],
addTodo: (title) =&gt;
set((state) =&gt; ({
todos: [...state.todos, { id: crypto.randomUUID(), title, completed: false }],
})),
toggleTodo: (id) =&gt;
set((state) =&gt; ({
todos: state.todos.map((todo) =&gt;
todo.id === id ? { ...todo, completed: !todo.completed } : todo
),
})),
deleteTodo: (id) =&gt;
set((state) =&gt; ({
todos: state.todos.filter((todo) =&gt; todo.id !== id),
})),
}));
// Usage
function TodoList() {
const todos = useTodoStore((state) =&gt; state.todos);
const toggleTodo = useTodoStore((state) =&gt; state.toggleTodo);
return (
&lt;div&gt;
{todos.map((todo) =&gt; (
&lt;div key={todo.id} onClick={() =&gt; toggleTodo(todo.id)}&gt;
{todo.title} - {todo.completed ? &#x27;✓&#x27; : &#x27;○&#x27;}
&lt;/div&gt;
))}
&lt;/div&gt;
);
}
function AddTodo() {
const addTodo = useTodoStore((state) =&gt; state.addTodo);
return (
&lt;button onClick={() =&gt; addTodo(&#x27;New Todo&#x27;)}&gt;
Add Todo
&lt;/button&gt;
);
}</code></pre>
<p><strong>Selector optimization</strong> - Component only re-renders when selected value changes:</p>
<pre><code class="lang-tsx">// ❌ Re-renders on any store change
const store = useTodoStore();
// ✅ Only re-renders when todos change
const todos = useTodoStore((state) =&gt; state.todos);</code></pre>
<h3>Zustand with Immer (Immutability)</h3>
<pre><code class="lang-tsx">import { create } from &#x27;zustand&#x27;;
import { immer } from &#x27;zustand/middleware/immer&#x27;;
interface Store {
nested: {
deeply: {
value: number;
};
};
increment: () =&gt; void;
}
const useStore = create&lt;Store&gt;()(
immer((set) =&gt; ({
nested: { deeply: { value: 0 } },
// Immer allows &quot;mutation&quot; syntax
increment: () =&gt;
set((state) =&gt; {
state.nested.deeply.value += 1;
}),
}))
);</code></pre>
<h3>Zustand with Persistence</h3>
<pre><code class="lang-tsx">import { create } from &#x27;zustand&#x27;;
import { persist } from &#x27;zustand/middleware&#x27;;
interface AuthStore {
user: User | null;
login: (user: User) =&gt; void;
logout: () =&gt; void;
}
export const useAuthStore = create&lt;AuthStore&gt;()(
persist(
(set) =&gt; ({
user: null,
login: (user) =&gt; set({ user }),
logout: () =&gt; set({ user: null }),
}),
{
name: &#x27;auth-storage&#x27;, // localStorage key
}
)
);</code></pre>
<p><strong>When to use Zustand</strong>:</p>
<ul><li>Most applications</li><li>Simple global state</li><li>Good performance (fine-grained subscriptions)</li><li>Minimal boilerplate</li></ul>
<hr>
<h2>Jotai</h2>
<h3>Atoms (Atomic State)</h3>
<pre><code class="lang-tsx">// stores/atoms.ts
import { atom } from &#x27;jotai&#x27;;
// Primitive atoms
export const countAtom = atom(0);
export const userAtom = atom&lt;User | null&gt;(null);
// Derived atoms (computed)
export const doubleCountAtom = atom((get) =&gt; get(countAtom) * 2);
// Writable derived atoms
export const incrementCountAtom = atom(
(get) =&gt; get(countAtom),
(get, set) =&gt; set(countAtom, get(countAtom) + 1)
);
// Async atoms
export const postsAtom = atom(async () =&gt; {
const res = await fetch(&#x27;/api/posts&#x27;);
return res.json();
});
// Usage
function Counter() {
const [count, setCount] = useAtom(countAtom);
const doubleCount = useAtomValue(doubleCountAtom);
return (
&lt;div&gt;
&lt;p&gt;Count: {count}&lt;/p&gt;
&lt;p&gt;Double: {doubleCount}&lt;/p&gt;
&lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;
&lt;/div&gt;
);
}</code></pre>
<h3>Atom Families (Dynamic Atoms)</h3>
<pre><code class="lang-tsx">import { atomFamily } from &#x27;jotai/utils&#x27;;
// Create atoms dynamically by ID
const todoAtomFamily = atomFamily((id: string) =&gt;
atom&lt;Todo&gt;({ id, title: &#x27;&#x27;, completed: false })
);
function TodoItem({ id }: { id: string }) {
const [todo, setTodo] = useAtom(todoAtomFamily(id));
return (
&lt;div&gt;
&lt;input
value={todo.title}
onChange={(e) =&gt; setTodo({ ...todo, title: e.target.value })}
/&gt;
&lt;/div&gt;
);
}</code></pre>
<h3>Jotai with Storage</h3>
<pre><code class="lang-tsx">import { atomWithStorage } from &#x27;jotai/utils&#x27;;
export const themeAtom = atomWithStorage&lt;&#x27;light&#x27; | &#x27;dark&#x27;&gt;(&#x27;theme&#x27;, &#x27;light&#x27;);</code></pre>
<p><strong>When to use Jotai</strong>:</p>
<ul><li>Bottom-up state (compose small pieces)</li><li>Derived/computed state</li><li>Atomic updates (fine-grained reactivity)</li><li>TypeScript-first</li></ul>
<hr>
<h2>Redux Toolkit</h2>
<h3>Store Setup</h3>
<pre><code class="lang-tsx">// store/store.ts
import { configureStore } from &#x27;@reduxjs/toolkit&#x27;;
import todosReducer from &#x27;./todosSlice&#x27;;
import userReducer from &#x27;./userSlice&#x27;;
export const store = configureStore({
reducer: {
todos: todosReducer,
user: userReducer,
},
});
export type RootState = ReturnType&lt;typeof store.getState&gt;;
export type AppDispatch = typeof store.dispatch;</code></pre>
<h3>Slice Definition</h3>
<pre><code class="lang-tsx">// store/todosSlice.ts
import { createSlice, PayloadAction } from &#x27;@reduxjs/toolkit&#x27;;
interface Todo {
id: string;
title: string;
completed: boolean;
}
interface TodosState {
items: Todo[];
loading: boolean;
}
const initialState: TodosState = {
items: [],
loading: false,
};
const todosSlice = createSlice({
name: &#x27;todos&#x27;,
initialState,
reducers: {
addTodo: (state, action: PayloadAction&lt;string&gt;) =&gt; {
state.items.push({
id: crypto.randomUUID(),
title: action.payload,
completed: false,
});
},
toggleTodo: (state, action: PayloadAction&lt;string&gt;) =&gt; {
const todo = state.items.find((t) =&gt; t.id === action.payload);
if (todo) todo.completed = !todo.completed;
},
deleteTodo: (state, action: PayloadAction&lt;string&gt;) =&gt; {
state.items = state.items.filter((t) =&gt; t.id !== action.payload);
},
},
});
export const { addTodo, toggleTodo, deleteTodo } = todosSlice.actions;
export default todosSlice.reducer;</code></pre>
<h3>Async Thunks</h3>
<pre><code class="lang-tsx">// store/userSlice.ts
import { createSlice, createAsyncThunk } from &#x27;@reduxjs/toolkit&#x27;;
export const fetchUser = createAsyncThunk(&#x27;user/fetch&#x27;, async (userId: string) =&gt; {
const res = await fetch(`/api/users/${userId}`);
return res.json();
});
interface UserState {
user: User | null;
loading: boolean;
error: string | null;
}
const userSlice = createSlice({
name: &#x27;user&#x27;,
initialState: { user: null, loading: false, error: null } as UserState,
reducers: {},
extraReducers: (builder) =&gt; {
builder
.addCase(fetchUser.pending, (state) =&gt; {
state.loading = true;
state.error = null;
})
.addCase(fetchUser.fulfilled, (state, action) =&gt; {
state.loading = false;
state.user = action.payload;
})
.addCase(fetchUser.rejected, (state, action) =&gt; {
state.loading = false;
state.error = action.error.message || &#x27;Failed to fetch user&#x27;;
});
},
});
export default userSlice.reducer;</code></pre>
<h3>Hooks</h3>
<pre><code class="lang-tsx">// hooks/redux.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from &#x27;react-redux&#x27;;
import type { RootState, AppDispatch } from &#x27;../store/store&#x27;;
export const useAppDispatch = () =&gt; useDispatch&lt;AppDispatch&gt;();
export const useAppSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector;
// Usage
function TodoList() {
const todos = useAppSelector((state) =&gt; state.todos.items);
const dispatch = useAppDispatch();
return (
&lt;div&gt;
{todos.map((todo) =&gt; (
&lt;div key={todo.id} onClick={() =&gt; dispatch(toggleTodo(todo.id))}&gt;
{todo.title}
&lt;/div&gt;
))}
&lt;button onClick={() =&gt; dispatch(addTodo(&#x27;New Todo&#x27;))}&gt;Add&lt;/button&gt;
&lt;/div&gt;
);
}</code></pre>
<p><strong>When to use Redux Toolkit</strong>:</p>
<ul><li>Large, complex applications</li><li>Time-travel debugging needed</li><li>Team familiar with Redux</li><li>Extensive middleware needed</li><li>Strict state management patterns</li></ul>
<hr>
<h2>State Patterns</h2>
<h3>Optimistic Updates</h3>
<pre><code class="lang-tsx">// Zustand
const useStore = create&lt;Store&gt;((set) =&gt; ({
todos: [],
toggleTodo: async (id: string) =&gt; {
// Optimistic update
set((state) =&gt; ({
todos: state.todos.map((todo) =&gt;
todo.id === id ? { ...todo, completed: !todo.completed } : todo
),
}));
try {
await fetch(`/api/todos/${id}/toggle`, { method: &#x27;POST&#x27; });
} catch (error) {
// Revert on error
set((state) =&gt; ({
todos: state.todos.map((todo) =&gt;
todo.id === id ? { ...todo, completed: !todo.completed } : todo
),
}));
}
},
}));</code></pre>
<h3>Loading States</h3>
<pre><code class="lang-tsx">interface Store {
data: Data[];
loading: boolean;
error: string | null;
fetch: () =&gt; Promise&lt;void&gt;;
}
const useStore = create&lt;Store&gt;((set) =&gt; ({
data: [],
loading: false,
error: null,
fetch: async () =&gt; {
set({ loading: true, error: null });
try {
const res = await fetch(&#x27;/api/data&#x27;);
const data = await res.json();
set({ data, loading: false });
} catch (error) {
set({ error: error.message, loading: false });
}
},
}));</code></pre>
<h3>Derived State</h3>
<pre><code class="lang-tsx">// Jotai - automatic memoization
const todosAtom = atom&lt;Todo[]&gt;([]);
const completedTodosAtom = atom((get) =&gt;
get(todosAtom).filter((todo) =&gt; todo.completed)
);
const activeTodosAtom = atom((get) =&gt;
get(todosAtom).filter((todo) =&gt; !todo.completed)
);
const statsAtom = atom((get) =&gt; {
const todos = get(todosAtom);
return {
total: todos.length,
completed: get(completedTodosAtom).length,
active: get(activeTodosAtom).length,
};
});
// Zustand - manual memoization
const useStore = create&lt;Store&gt;((set) =&gt; ({
todos: [],
get completedTodos() {
return this.todos.filter((todo) =&gt; todo.completed);
},
}));</code></pre>
<hr>
<h2>Migration Patterns</h2>
<h3>Context → Zustand</h3>
<pre><code class="lang-tsx">// Before (Context)
const TodoContext = createContext&lt;{
todos: Todo[];
addTodo: (title: string) =&gt; void;
} | null&gt;(null);
function TodoProvider({ children }) {
const [todos, setTodos] = useState&lt;Todo[]&gt;([]);
const addTodo = (title: string) =&gt; setTodos([...todos, { title }]);
return &lt;TodoContext.Provider value={{ todos, addTodo }}&gt;{children}&lt;/TodoContext.Provider&gt;;
}
// After (Zustand)
const useTodoStore = create&lt;Store&gt;((set) =&gt; ({
todos: [],
addTodo: (title) =&gt; set((state) =&gt; ({ todos: [...state.todos, { title }] })),
}));
// Replace useContext with store hook
const todos = useTodoStore((state) =&gt; state.todos);
const addTodo = useTodoStore((state) =&gt; state.addTodo);</code></pre>
<hr>
<h2>Quick Reference</h2>
<h3>Choosing State Management</h3>
<pre><code>Local component state → useState
2-3 components nearby → Lift state or Context
App-wide, simple → Zustand
Atomic, derived state → Jotai
Complex, large app → Redux Toolkit
Server data → SWR/React Query</code></pre>
<h3>Performance Tips</h3>
<pre><code class="lang-tsx">// ❌ Bad: Entire store subscription
const store = useStore();
// ✅ Good: Selective subscription
const todos = useStore((state) =&gt; state.todos);
// ✅ Good: Multiple selectors
const addTodo = useStore((state) =&gt; state.addTodo);
const deleteTodo = useStore((state) =&gt; state.deleteTodo);
// ✅ Good: Memoized selector
const completedCount = useStore(
(state) =&gt; state.todos.filter((t) =&gt; t.completed).length
);</code></pre>
<hr>
<h2>Common Anti-Patterns</h2>
<p>❌ <strong>Storing server state in global store</strong>: Use SWR/React Query instead ✅ Keep server state separate from client state</p>
<p>❌ <strong>Too much global state</strong>: Most state should be local ✅ Only globalize what needs to be shared</p>
<p>❌ <strong>Not splitting context</strong>: One context causes all consumers to re-render ✅ Split into multiple contexts (data + actions)</p>
<p>❌ <strong>Derived state not memoized</strong>: Recalculates on every render ✅ Use useMemo, Jotai derived atoms, or Zustand getters</p>
<hr>
<h2>Level 3: Resources</h2>
<h3>Comprehensive Reference</h3>
<ul><li><strong>REFERENCE.md</strong>: Complete React state management guide (900+ lines)</li><li>All state categories (local, shared, server, URL, form)</li><li>React built-in hooks (useState, useReducer, useContext)</li><li>External libraries (Zustand, Jotai, Redux Toolkit, MobX, Recoil)</li><li>Server state (TanStack Query, SWR)</li><li>URL state management</li><li>Form state (React Hook Form, Formik)</li><li>Decision trees and comparison matrices</li><li>Performance optimization patterns</li><li>State colocation strategies</li><li>Immutability patterns</li><li>Common patterns and anti-patterns</li></ul>
<h3>Executable Scripts</h3>
<p>Located in <code>resources/scripts/</code>:</p>
<ol><li><strong>analyze_state.py</strong> - Analyze React component state patterns</li></ol>
<ul><li>Detects state management approaches (useState, useReducer, Context)</li><li>Identifies prop drilling issues</li><li>Finds stale closure risks</li><li>Detects unnecessary derived state</li><li>Suggests optimization opportunities</li><li>Reports state complexity metrics</li></ul>
<p> ``<code>bash ./analyze_state.py ./src ./analyze_state.py ./src --json </code>``</p>
<ol><li><strong>benchmark_renders.js</strong> - Benchmark render performance</li></ol>
<ul><li>Simulates component trees with different state patterns</li><li>Measures render count and timing</li><li>Compares useState, Context, Zustand, Jotai</li><li>Reports performance metrics</li></ul>
<p> ``<code>bash ./benchmark_renders.js ./benchmark_renders.js --depth 20 --updates 500 ./benchmark_renders.js --json </code>``</p>
<ol><li><strong>detect_unnecessary_renders.js</strong> - Detect unnecessary re-renders</li></ol>
<ul><li>Identifies components that should use React.memo</li><li>Finds props that change on every render (object/array literals)</li><li>Detects missing dependencies in useMemo/useCallback</li><li>Finds unstable callback props</li><li>Reports context overuse</li></ul>
<p> ``<code>bash ./detect_unnecessary_renders.js ./src ./detect_unnecessary_renders.js ./components --json </code>``</p>
<h3>TypeScript Examples</h3>
<p>Located in <code>resources/examples/typescript/</code>:</p>
<ol><li><strong>zustand-store.ts</strong> - Complete Zustand patterns</li></ol>
<ul><li>Basic store with actions</li><li>Async operations</li><li>Slices pattern for large stores</li><li>Middleware (persist, immer)</li><li>Selectors and performance</li></ul>
<ol><li><strong>tanstack-query-hooks.ts</strong> - TanStack Query (React Query) patterns</li></ol>
<ul><li>Basic queries and mutations</li><li>Optimistic updates</li><li>Pagination and infinite queries</li><li>Dependent and parallel queries</li><li>Query invalidation</li><li>Cache management</li></ul>
<ol><li><strong>context-provider.tsx</strong> - React Context patterns</li></ol>
<ul><li>Basic Context</li><li>Optimized Context (split state/dispatch)</li><li>Context with useReducer</li><li>Context composition</li><li>Selector pattern</li><li>Performance optimization</li></ul>
<ol><li><strong>react-hook-form-example.tsx</strong> - Form state management</li></ol>
<ul><li>Basic forms with Zod validation</li><li>Complex nested fields</li><li>Field arrays (dynamic forms)</li><li>Controlled components</li><li>Custom validation</li><li>Async validation</li></ul>
<ol><li><strong>immutable-updates.ts</strong> - Immutable state patterns</li></ol>
<ul><li>Array operations (add, remove, update, sort)</li><li>Object operations (shallow, nested)</li><li>Complex state operations</li><li>Using Immer for complex updates</li><li>Performance considerations</li><li>Common patterns</li></ul>
<hr>
<h2>Related Skills</h2>
<ul><li><code>react-component-patterns.md</code> - useState, useContext, custom hooks</li><li><code>react-data-fetching.md</code> - SWR, React Query for server state</li><li><code>nextjs-app-router.md</code> - Server Components (minimal client state)</li><li><code>frontend-performance.md</code> - Re-render optimization</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/frontend-react-state-management.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>