@ranimontagna/agent-toolkit 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +68 -14
  2. package/package.json +1 -1
  3. package/skills/backend/go/golang-patterns/LICENSE +21 -0
  4. package/skills/backend/go/golang-patterns/NOTICE.md +10 -0
  5. package/skills/backend/go/golang-patterns/SKILL.md +674 -0
  6. package/skills/backend/go/golang-testing/LICENSE +21 -0
  7. package/skills/backend/go/golang-testing/NOTICE.md +10 -0
  8. package/skills/backend/go/golang-testing/SKILL.md +329 -0
  9. package/skills/backend/java/java-coding-standards/LICENSE +21 -0
  10. package/skills/backend/java/java-coding-standards/NOTICE.md +10 -0
  11. package/skills/backend/java/java-coding-standards/SKILL.md +383 -0
  12. package/skills/backend/java/java-junit/LICENSE +21 -0
  13. package/skills/backend/java/java-junit/NOTICE.md +10 -0
  14. package/skills/backend/java/java-junit/SKILL.md +64 -0
  15. package/skills/frontend/react/react-patterns/LICENSE +21 -0
  16. package/skills/frontend/react/react-patterns/NOTICE.md +11 -0
  17. package/skills/frontend/react/react-patterns/SKILL.md +341 -0
  18. package/skills/frontend/react/react-patterns/rules/react/LICENSE +21 -0
  19. package/skills/frontend/react/react-patterns/rules/react/NOTICE.md +11 -0
  20. package/skills/frontend/react/react-patterns/rules/react/coding-style.md +109 -0
  21. package/skills/frontend/react/react-patterns/rules/react/hooks.md +187 -0
  22. package/skills/frontend/react/react-patterns/rules/react/patterns.md +194 -0
  23. package/skills/frontend/react/react-patterns/rules/react/security.md +180 -0
  24. package/skills/frontend/react/react-patterns/rules/react/testing.md +208 -0
  25. package/skills/frontend/react/react-performance/LICENSE +21 -0
  26. package/skills/frontend/react/react-performance/NOTICE.md +11 -0
  27. package/skills/frontend/react/react-performance/SKILL.md +574 -0
  28. package/skills/frontend/react/react-performance/rules/react/LICENSE +21 -0
  29. package/skills/frontend/react/react-performance/rules/react/NOTICE.md +11 -0
  30. package/skills/frontend/react/react-performance/rules/react/coding-style.md +109 -0
  31. package/skills/frontend/react/react-performance/rules/react/hooks.md +187 -0
  32. package/skills/frontend/react/react-performance/rules/react/patterns.md +194 -0
  33. package/skills/frontend/react/react-performance/rules/react/security.md +180 -0
  34. package/skills/frontend/react/react-performance/rules/react/testing.md +208 -0
  35. package/skills/frontend/react/react-testing/LICENSE +21 -0
  36. package/skills/frontend/react/react-testing/NOTICE.md +11 -0
  37. package/skills/frontend/react/react-testing/SKILL.md +423 -0
  38. package/skills/frontend/react/react-testing/rules/react/LICENSE +21 -0
  39. package/skills/frontend/react/react-testing/rules/react/NOTICE.md +11 -0
  40. package/skills/frontend/react/react-testing/rules/react/coding-style.md +109 -0
  41. package/skills/frontend/react/react-testing/rules/react/hooks.md +187 -0
  42. package/skills/frontend/react/react-testing/rules/react/patterns.md +194 -0
  43. package/skills/frontend/react/react-testing/rules/react/security.md +180 -0
  44. package/skills/frontend/react/react-testing/rules/react/testing.md +208 -0
  45. package/skills/frontend/react-native/react-native-expert/LICENSE +21 -0
  46. package/skills/frontend/react-native/react-native-expert/NOTICE.md +11 -0
  47. package/skills/frontend/react-native/react-native-expert/SKILL.md +187 -0
  48. package/skills/frontend/react-native/react-native-expert/references/expo-router.md +187 -0
  49. package/skills/frontend/react-native/react-native-expert/references/list-optimization.md +204 -0
  50. package/skills/frontend/react-native/react-native-expert/references/platform-handling.md +188 -0
  51. package/skills/frontend/react-native/react-native-expert/references/project-structure.md +171 -0
  52. package/skills/frontend/react-native/react-native-expert/references/storage-hooks.md +173 -0
  53. package/skills/frontend/react-native/react-native-unistyles-v3/LICENSE +21 -0
  54. package/skills/frontend/react-native/react-native-unistyles-v3/NOTICE.md +11 -0
  55. package/skills/frontend/react-native/react-native-unistyles-v3/SKILL.md +159 -0
  56. package/skills/frontend/react-native/react-native-unistyles-v3/references/api-reference.md +495 -0
  57. package/skills/frontend/react-native/react-native-unistyles-v3/references/common-issues.md +389 -0
  58. package/skills/frontend/react-native/react-native-unistyles-v3/references/setup-guide.md +217 -0
  59. package/skills/frontend/react-native/react-native-unistyles-v3/references/styling-patterns.md +705 -0
  60. package/skills/frontend/react-native/react-native-unistyles-v3/references/third-party-integration.md +318 -0
@@ -0,0 +1,341 @@
1
+ ---
2
+ name: react-patterns
3
+ description: React 18/19 patterns including hooks discipline, server/client component boundaries, Suspense + error boundaries, form actions, data fetching, state management decision trees, and accessibility-first composition. Use when writing or reviewing React components.
4
+ origin: ECC
5
+ ---
6
+
7
+ # React Patterns
8
+
9
+ Idiomatic React 18/19 patterns for building robust, accessible, performant component trees.
10
+
11
+ ## When to Activate
12
+
13
+ - Writing or modifying React function components, custom hooks, or component trees
14
+ - Reviewing JSX/TSX files
15
+ - Designing state shape or component composition
16
+ - Migrating class components or older `forwardRef`/`useEffect`-heavy code
17
+ - Choosing between local state, lifted state, context, and external stores
18
+ - Working with Server Components / Client Components (Next.js App Router, RSC)
19
+ - Implementing forms with React 19 actions or controlled inputs
20
+ - Wiring data fetching with TanStack Query / SWR / RSC
21
+
22
+ ## Core Principles
23
+
24
+ ### 1. Render is a Pure Function of Props and State
25
+
26
+ ```tsx
27
+ // Good: derive during render
28
+ function Cart({ items }: { items: CartItem[] }) {
29
+ const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
30
+ return <span>{formatMoney(total)}</span>;
31
+ }
32
+
33
+ // Bad: derived state stored separately
34
+ function Cart({ items }: { items: CartItem[] }) {
35
+ const [total, setTotal] = useState(0);
36
+ useEffect(() => {
37
+ setTotal(items.reduce((sum, i) => sum + i.price * i.qty, 0));
38
+ }, [items]);
39
+ return <span>{formatMoney(total)}</span>;
40
+ }
41
+ ```
42
+
43
+ Derived state in `useEffect` adds a render cycle, can desync, and obscures the data flow.
44
+
45
+ ### 2. Side Effects Outside Render
46
+
47
+ Effects, mutations, network calls, and subscriptions live in event handlers or `useEffect` — never in the render body.
48
+
49
+ ### 3. Composition Over Inheritance
50
+
51
+ React has no inheritance model for components. Compose with `children`, render props, or component props.
52
+
53
+ ## Hooks Discipline
54
+
55
+ See [rules/react/hooks.md](rules/react/hooks.md) for the full ruleset. Highlights:
56
+
57
+ - Top-level only, never conditional
58
+ - Cleanup every subscription, interval, listener
59
+ - Functional updater (`setX(prev => prev + 1)`) when new state depends on old
60
+ - Default position: do not memoize — add `useMemo`/`useCallback` only when a profiler or a dependency chain proves it matters
61
+ - Extract a custom hook only when the same hook sequence appears in 2+ components
62
+
63
+ ## State Location Decision Tree
64
+
65
+ ```
66
+ Used by one component?
67
+ -> useState inside it
68
+
69
+ Used by parent + a few descendants?
70
+ -> lift to nearest common ancestor
71
+
72
+ Used across distant branches AND low-frequency reads (theme, auth, locale)?
73
+ -> React Context
74
+
75
+ High-frequency updates shared across the tree?
76
+ -> external store (Zustand, Jotai, Redux Toolkit)
77
+
78
+ Derived from a server?
79
+ -> server-state library (TanStack Query, SWR, RSC fetch)
80
+ ```
81
+
82
+ Most pages do not need context or a global store. Resist abstraction until duplicated lifting becomes painful.
83
+
84
+ ## Server / Client Components (RSC)
85
+
86
+ ```tsx
87
+ // Server Component - default, async, never ships JS for itself
88
+ export default async function ProductPage({ params }: { params: { id: string } }) {
89
+ const product = await db.product.findUnique({ where: { id: params.id } });
90
+ if (!product) notFound();
91
+ return <ProductView product={product} />;
92
+ }
93
+
94
+ // Client Component - opt in with "use client"
95
+ "use client";
96
+ export function AddToCartButton({ productId }: { productId: string }) {
97
+ const [pending, startTransition] = useTransition();
98
+ return (
99
+ <button
100
+ disabled={pending}
101
+ onClick={() => startTransition(() => addToCart(productId))}
102
+ >
103
+ {pending ? "Adding..." : "Add to cart"}
104
+ </button>
105
+ );
106
+ }
107
+ ```
108
+
109
+ Boundaries:
110
+
111
+ - Server -> Client: pass serializable props or `children`
112
+ - Client -> Server: invoke Server Actions via `<form action={...}>` or imperatively from event handlers
113
+ - Never `import` a Server Component from a Client Component file — compose them via `children` instead
114
+
115
+ ## Suspense + Error Boundaries
116
+
117
+ ```tsx
118
+ <ErrorBoundary fallback={<ErrorView />}>
119
+ <Suspense fallback={<UserSkeleton />}>
120
+ <UserDetail id={id} />
121
+ </Suspense>
122
+ </ErrorBoundary>
123
+ ```
124
+
125
+ - Place Suspense boundaries close to the data, not at the route root — progressively reveal content
126
+ - Error Boundary remains a class API; use `react-error-boundary` for a hook-friendly wrapper
127
+ - A boundary catches errors thrown during render, lifecycle, and constructors of its children — NOT in event handlers or async code
128
+
129
+ ## Forms
130
+
131
+ ### React 19 form actions (preferred for new code)
132
+
133
+ ```tsx
134
+ "use client";
135
+ import { useActionState } from "react";
136
+
137
+ const initial = { error: null as string | null };
138
+
139
+ async function updateUserAction(_prev: typeof initial, formData: FormData) {
140
+ "use server";
141
+ const parsed = UserSchema.safeParse(Object.fromEntries(formData));
142
+ if (!parsed.success) return { error: "Invalid input" };
143
+ await db.user.update({ where: { id: parsed.data.id }, data: parsed.data });
144
+ return { error: null };
145
+ }
146
+
147
+ export function UserForm() {
148
+ const [state, formAction, pending] = useActionState(updateUserAction, initial);
149
+ return (
150
+ <form action={formAction}>
151
+ <input name="name" required />
152
+ <button type="submit" disabled={pending}>Save</button>
153
+ {state.error && <p role="alert">{state.error}</p>}
154
+ </form>
155
+ );
156
+ }
157
+ ```
158
+
159
+ ### Controlled inputs
160
+
161
+ Use controlled when the value drives other UI, formats on every keystroke, or implements real-time validation.
162
+
163
+ ### Complex forms
164
+
165
+ For multi-step forms, dynamic field arrays, or cross-field validation: use a library (React Hook Form, TanStack Form). Roll-your-own state management for forms past trivial complexity is a maintenance trap.
166
+
167
+ ## Data Fetching Decision Matrix
168
+
169
+ | Need | Tool |
170
+ |---|---|
171
+ | Per-request data in Next.js App Router | RSC `await fetch()` |
172
+ | Client-side cache + mutations + invalidation | TanStack Query |
173
+ | Lightweight client cache + revalidation | SWR |
174
+ | Real-time subscriptions | Server-Sent Events, WebSockets, or the lib's subscription API |
175
+ | One-off fire-and-forget | `fetch()` in an event handler |
176
+
177
+ Avoid `useEffect` + `fetch` for application data — race conditions, no cache, no retry, no Suspense integration.
178
+
179
+ ## Composition Recipes
180
+
181
+ ### Slot via `children`
182
+
183
+ ```tsx
184
+ <Layout>
185
+ <Header />
186
+ <Main>{content}</Main>
187
+ </Layout>
188
+ ```
189
+
190
+ ### Named slots
191
+
192
+ ```tsx
193
+ <Page header={<Nav />} sidebar={<Filters />}>
194
+ <Results />
195
+ </Page>
196
+ ```
197
+
198
+ ### Compound components (shared state via Context)
199
+
200
+ ```tsx
201
+ <Tabs defaultValue="profile">
202
+ <Tabs.List>
203
+ <Tabs.Trigger value="profile">Profile</Tabs.Trigger>
204
+ <Tabs.Trigger value="settings">Settings</Tabs.Trigger>
205
+ </Tabs.List>
206
+ <Tabs.Panel value="profile"><Profile /></Tabs.Panel>
207
+ <Tabs.Panel value="settings"><Settings /></Tabs.Panel>
208
+ </Tabs>
209
+ ```
210
+
211
+ ### Render prop / function-as-child
212
+
213
+ Useful when the parent needs to pass parameters to the rendered output:
214
+
215
+ ```tsx
216
+ <DataLoader id={id}>
217
+ {({ data, isLoading }) => isLoading ? <Spinner /> : <UserCard user={data} />}
218
+ </DataLoader>
219
+ ```
220
+
221
+ Modern alternative: a hook (`useData(id)`) returning the same shape — usually cleaner.
222
+
223
+ ## Performance
224
+
225
+ ### When `React.memo` Actually Helps
226
+
227
+ Wrap a component in `React.memo` only when:
228
+
229
+ 1. It re-renders frequently
230
+ 2. Its props are usually the same between renders
231
+ 3. Its render is measurably expensive
232
+
233
+ `React.memo` adds an equality check on every render. If props differ on most renders, the check is pure overhead.
234
+
235
+ ### Avoiding Render Cascades
236
+
237
+ - Lift state down rather than up where possible
238
+ - Split context: one context per concern, so a change to `themeContext` does not re-render auth consumers
239
+ - Use `useSyncExternalStore` for external state libraries — required for safe concurrent rendering
240
+
241
+ ### Lists
242
+
243
+ - Provide stable `key` props (database id, not array index)
244
+ - Virtualize long lists with `@tanstack/react-virtual` or `react-window` once visible item count exceeds ~50 with non-trivial rows
245
+
246
+ ## Accessibility-First Composition
247
+
248
+ - Always render semantic HTML (`<button>`, `<a>`, `<nav>`, `<main>`) before reaching for `role` attributes
249
+ - Every interactive element must be reachable by keyboard
250
+ - Form inputs need labels — `<label htmlFor>` or `aria-label` if visually labeled by an icon
251
+ - Manage focus on route changes and modal open/close
252
+ - Run `axe` in component tests (see [skills/react-testing](../react-testing/SKILL.md))
253
+ - Cross-link: skills/accessibility covers WCAG criteria and pattern libraries when that optional skill is installed
254
+
255
+ ## Routing
256
+
257
+ This skill is router-agnostic. The patterns above work with React Router, TanStack Router, Next.js App Router, Remix Router. Router-specific patterns (loaders, actions, nested layouts) follow the router's documentation — those are framework concerns layered on top of React core.
258
+
259
+ ## Out of Scope (Pointer Sections)
260
+
261
+ - **Next.js specifics**: App Router data loading, Route Handlers, Middleware, Parallel Routes — separate concern, use Next.js docs
262
+ - **React Native**: Platform-specific patterns differ enough to warrant a separate `react-native-patterns` skill (not present yet)
263
+ - **Remix**: Loader/action conventions overlap with RSC but follow Remix docs
264
+
265
+ ## Related
266
+
267
+ - Rules: [rules/react/](rules/react/) — coding-style, hooks, patterns, security, testing
268
+ - Skills: [react-performance](../react-performance/SKILL.md) for the Vercel-derived performance ruleset; frontend-patterns for cross-framework UI concerns; accessibility; angular-developer for framework comparison
269
+ - Agents: `react-reviewer` for code review, `react-build-resolver` for build/bundler errors
270
+ - Commands: `/react-review`, `/react-build`, `/react-test`
271
+
272
+ ## Examples
273
+
274
+ ### Custom hook for debounced search
275
+
276
+ ```tsx
277
+ function useDebounce<T>(value: T, delay = 300): T {
278
+ const [debounced, setDebounced] = useState(value);
279
+ useEffect(() => {
280
+ const id = setTimeout(() => setDebounced(value), delay);
281
+ return () => clearTimeout(id);
282
+ }, [value, delay]);
283
+ return debounced;
284
+ }
285
+
286
+ function SearchBox() {
287
+ const [query, setQuery] = useState("");
288
+ const debounced = useDebounce(query, 300);
289
+ const { data } = useQuery({
290
+ queryKey: ["search", debounced],
291
+ queryFn: () => searchApi(debounced),
292
+ enabled: debounced.length > 0,
293
+ });
294
+ return (
295
+ <>
296
+ <input value={query} onChange={(e) => setQuery(e.target.value)} />
297
+ <Results items={data ?? []} />
298
+ </>
299
+ );
300
+ }
301
+ ```
302
+
303
+ ### Optimistic UI with React 19 `useOptimistic`
304
+
305
+ ```tsx
306
+ "use client";
307
+ import { useOptimistic } from "react";
308
+
309
+ export function MessageList({ messages }: { messages: Message[] }) {
310
+ const [optimistic, addOptimistic] = useOptimistic(
311
+ messages,
312
+ (state, newMessage: Message) => [...state, newMessage],
313
+ );
314
+
315
+ async function send(formData: FormData) {
316
+ const text = String(formData.get("text"));
317
+ addOptimistic({ id: "pending", text, sender: "me" });
318
+ await saveMessage(text);
319
+ }
320
+
321
+ return (
322
+ <>
323
+ <ul>{optimistic.map((m) => <li key={m.id}>{m.text}</li>)}</ul>
324
+ <form action={send}>
325
+ <input name="text" />
326
+ <button type="submit">Send</button>
327
+ </form>
328
+ </>
329
+ );
330
+ }
331
+ ```
332
+
333
+ ### Splitting context to avoid render cascades
334
+
335
+ ```tsx
336
+ // Two contexts: one rarely changes, one frequently
337
+ const ThemeContext = createContext<Theme>("light");
338
+ const NotificationsContext = createContext<Notification[]>([]);
339
+
340
+ // A component that only consumes ThemeContext does NOT re-render when notifications change
341
+ ```
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Affaan Mustafa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ # Third-party notice
2
+
3
+ This directory contains React rule references copied from Affaan Mustafa's ECC
4
+ repository.
5
+
6
+ - Source: https://github.com/affaan-m/ECC/tree/main/rules/react
7
+ - Source commit: 0f84c0e2796703fbda87d577b2636351418c7442
8
+ - License: MIT
9
+ - Copyright: Copyright (c) 2026 Affaan Mustafa
10
+
11
+ The upstream MIT license is included in `LICENSE`.
@@ -0,0 +1,109 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/components/**/*.ts"
6
+ - "**/components/**/*.js"
7
+ - "**/hooks/**/*.ts"
8
+ - "**/hooks/**/*.js"
9
+ ---
10
+ # React Coding Style
11
+
12
+ > This file extends the upstream `typescript/coding-style.md` and `common/coding-style.md` rules with React specific content.
13
+
14
+ ## File Extensions
15
+
16
+ - `.tsx` for any file containing JSX, even one-liner snippets
17
+ - `.ts` for pure logic, custom hooks without JSX, type definitions, utilities
18
+ - `.test.tsx` / `.test.ts` mirroring the source file
19
+ - Use `.jsx` only when the project intentionally avoids TypeScript — flag every new untyped React file in review
20
+
21
+ ## Naming
22
+
23
+ - Components: `PascalCase` for both the symbol and the file (`UserCard.tsx`, default export `UserCard`)
24
+ - Custom hooks: `useCamelCase` for the symbol, kebab-case for the file when the project convention is kebab-case (`use-debounce.ts` exports `useDebounce`)
25
+ - Context: `<Domain>Context` symbol, `<Domain>Provider` provider component, `use<Domain>` consumer hook
26
+ - Event handlers: `handleClick`, `handleSubmit` inside the component; the prop that receives it is `onClick`, `onSubmit`
27
+ - Boolean props: `isLoading`, `hasError`, `canSubmit` — never `loading` or `error` alone for booleans
28
+
29
+ ## Component Shape
30
+
31
+ ```tsx
32
+ type Props = {
33
+ user: User;
34
+ onSelect: (id: string) => void;
35
+ };
36
+
37
+ export function UserCard({ user, onSelect }: Props) {
38
+ return (
39
+ <button type="button" onClick={() => onSelect(user.id)}>
40
+ {user.name}
41
+ </button>
42
+ );
43
+ }
44
+ ```
45
+
46
+ - Prefer `type Props = {}` for closed component prop shapes
47
+ - Use `interface` only when the prop type is extended via declaration merging or exported as a public API extension point
48
+ - Always destructure props in the parameter list — no `props.user` access inside the body
49
+ - Type the return implicitly through JSX (`function Foo(): JSX.Element` only when the function returns conditionally and the union confuses inference)
50
+
51
+ ## JSX
52
+
53
+ - Self-close tags with no children: `<img />`, `<UserCard user={u} />`
54
+ - Use fragments `<>...</>` over wrapper `<div>` when no DOM element is needed
55
+ - Conditional rendering: `{condition && <Foo />}` for booleans, ternary for either/or, early return for guard clauses
56
+ - Never put logic inline in JSX when it reads as multi-line — extract to a const above the return or a function
57
+
58
+ ```tsx
59
+ // Prefer
60
+ const greeting = user.isAdmin ? "Welcome, admin" : `Hello ${user.name}`;
61
+ return <h1>{greeting}</h1>;
62
+
63
+ // Over
64
+ return <h1>{user.isAdmin ? "Welcome, admin" : `Hello ${user.name}`}</h1>;
65
+ ```
66
+
67
+ ## Server / Client Boundary (Next.js App Router, RSC)
68
+
69
+ - Default a new file to Server Component — only add `"use client"` when the file uses state, effects, refs, browser APIs, or event handlers
70
+ - Place the `"use client"` directive on line 1, before any imports
71
+ - Never import a Client Component file from inside a `"use server"` action file
72
+ - Never re-export server-only code through a client module — the bundler will silently include it
73
+
74
+ ## Imports
75
+
76
+ - React imports first: `import { useState } from "react"`
77
+ - Then third-party libs, then absolute project imports, then relative
78
+ - Type-only imports: `import type { ReactNode } from "react"` — never mix runtime and type imports in one statement when ESLint's `consistent-type-imports` is configured
79
+
80
+ ## Hooks Discipline
81
+
82
+ See [hooks.md](./hooks.md) for the full ruleset. Style highlights:
83
+
84
+ - Custom hooks must start with `use` — enforced by `eslint-plugin-react-hooks`
85
+ - Group all hook calls at the top of the component, before any conditional logic
86
+ - Avoid creating ad-hoc hooks for one-line wrappers — inline the call instead
87
+
88
+ ## State
89
+
90
+ - Local first (`useState`), lift only when shared
91
+ - Context for cross-cutting state read by many components (theme, auth, i18n) — not for high-frequency updates
92
+ - External store (Zustand, Jotai, Redux Toolkit) when state must persist across route changes, sync across tabs, or be debugged via devtools
93
+ - Never duplicate state that can be derived — compute during render
94
+
95
+ ## Class Components
96
+
97
+ Forbidden in new code. Convert legacy class components to function components when touching them for non-trivial changes.
98
+
99
+ ## File Layout per Component
100
+
101
+ ```
102
+ components/UserCard/
103
+ UserCard.tsx
104
+ UserCard.module.css # or styled-components, or Tailwind classes inline
105
+ UserCard.test.tsx
106
+ index.ts # re-export only
107
+ ```
108
+
109
+ Inline single-file components are fine for trivial presentational pieces.
@@ -0,0 +1,187 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/hooks/**/*.ts"
6
+ - "**/hooks/**/*.js"
7
+ - "**/use-*.ts"
8
+ - "**/use-*.tsx"
9
+ ---
10
+ # React Hooks
11
+
12
+ > This file covers **React hooks** (`useState`, `useEffect`, `useMemo`, `useCallback`, custom hooks) — NOT the Claude Code `hooks/` runtime system. Naming matches the per-language convention `rules/<lang>/hooks.md` used across this repo.
13
+ >
14
+ > Extends the upstream `typescript/patterns.md` and `common/patterns.md` rules.
15
+
16
+ ## Rules of Hooks
17
+
18
+ Enforce `eslint-plugin-react-hooks` with `react-hooks/rules-of-hooks` set to error.
19
+
20
+ 1. Hooks only at the top level of a function component or another hook
21
+ 2. Never in loops, conditionals, nested functions, or after early returns
22
+ 3. Always called in the same order on every render
23
+ 4. Only inside React function components or custom hooks (functions starting with `use`)
24
+
25
+ ```tsx
26
+ // WRONG: conditional hook
27
+ function Foo({ enabled }: { enabled: boolean }) {
28
+ if (enabled) {
29
+ const [x, setX] = useState(0); // rule violation
30
+ }
31
+ }
32
+
33
+ // CORRECT: hook unconditional, condition inside
34
+ function Foo({ enabled }: { enabled: boolean }) {
35
+ const [x, setX] = useState(0);
36
+ if (!enabled) return null;
37
+ return <span>{x}</span>;
38
+ }
39
+ ```
40
+
41
+ ## `useEffect` — When NOT to Use
42
+
43
+ `useEffect` is for synchronizing with external systems (subscriptions, browser APIs, third-party libraries). It is **not** the right tool for:
44
+
45
+ - Derived state — compute it during render
46
+ - Transforming data for rendering — compute it during render
47
+ - Resetting state when a prop changes — use a `key` on the parent or derive from props
48
+ - Notifying parents of state changes — call the callback in the event handler
49
+ - Initializing app-level singletons — call the function module-side or in `main.tsx`
50
+
51
+ ```tsx
52
+ // WRONG: effect for derived state
53
+ const [fullName, setFullName] = useState("");
54
+ useEffect(() => {
55
+ setFullName(`${first} ${last}`);
56
+ }, [first, last]);
57
+
58
+ // CORRECT: derive during render
59
+ const fullName = `${first} ${last}`;
60
+ ```
61
+
62
+ ## Dependency Arrays
63
+
64
+ - Always include every reactive value referenced inside the effect/callback
65
+ - Enable `react-hooks/exhaustive-deps` lint rule — never silence it without a comment explaining why
66
+ - If the dep array grows unwieldy, the effect is doing too much — split it
67
+ - Stable identity for functions passed in deps: wrap in `useCallback` only when the function is itself a dependency of another hook or passed to a memoized child
68
+
69
+ ## Cleanup
70
+
71
+ Every subscription, interval, listener, or in-flight request must clean up.
72
+
73
+ ```tsx
74
+ useEffect(() => {
75
+ const controller = new AbortController();
76
+ fetch(url, { signal: controller.signal }).then(handleResponse);
77
+ return () => controller.abort();
78
+ }, [url]);
79
+ ```
80
+
81
+ ```tsx
82
+ useEffect(() => {
83
+ const id = setInterval(tick, 1000);
84
+ return () => clearInterval(id);
85
+ }, []);
86
+ ```
87
+
88
+ Missing cleanup = race conditions when deps change, memory leaks on unmount.
89
+
90
+ ## `useMemo` and `useCallback` — When Worth It
91
+
92
+ Default position: **do not memoize**. Add `useMemo` / `useCallback` only when:
93
+
94
+ 1. The value is passed to a `React.memo`-wrapped child as a prop, and identity matters
95
+ 2. The value is a dependency of another `useEffect` / `useMemo` / `useCallback`
96
+ 3. The computation is measurably expensive (profile before assuming)
97
+
98
+ Premature memoization adds noise, hides bugs, and can be slower than the recompute it replaces.
99
+
100
+ ## Custom Hooks
101
+
102
+ Extract a custom hook when:
103
+
104
+ - The same hook sequence (state + effect + computed) appears in 2+ components
105
+ - The logic has a clear, nameable purpose (`useDebounce`, `useOnClickOutside`, `useLocalStorage`)
106
+ - You want to test the logic independently of any component
107
+
108
+ Do NOT extract when:
109
+
110
+ - It would have a single caller — inline it
111
+ - The "hook" is just `useState` with a different name — adds indirection, no value
112
+
113
+ ```tsx
114
+ export function useDebounce<T>(value: T, delay: number): T {
115
+ const [debounced, setDebounced] = useState(value);
116
+ useEffect(() => {
117
+ const id = setTimeout(() => setDebounced(value), delay);
118
+ return () => clearTimeout(id);
119
+ }, [value, delay]);
120
+ return debounced;
121
+ }
122
+ ```
123
+
124
+ ## `useState` Patterns
125
+
126
+ - Initial state from prop only at mount: pass a function `useState(() => computeInitial(prop))` when computation is expensive
127
+ - Functional updater when the new state depends on the old: `setCount(c => c + 1)` — never `setCount(count + 1)` inside async or batched contexts
128
+ - Group related state into one object only when they always change together; otherwise split into multiple `useState` calls
129
+ - Use `useReducer` once state transitions are conditional on the previous state or there are 3+ related values
130
+
131
+ ## `useRef` Patterns
132
+
133
+ - DOM refs for imperative APIs (focus, scroll, third-party libs)
134
+ - Mutable container that does not trigger re-render (timer ids, previous values, "is mounted" flags)
135
+ - Never read or write `ref.current` during render — only inside effects or event handlers
136
+ - `useImperativeHandle` only when exposing a child API to a parent ref — last-resort escape hatch
137
+
138
+ ## `useSyncExternalStore`
139
+
140
+ Use this hook to subscribe to any external store (browser API, third-party state lib, custom event emitter). It is the supported way to make external state safe with concurrent rendering.
141
+
142
+ ```tsx
143
+ const isOnline = useSyncExternalStore(
144
+ (cb) => {
145
+ window.addEventListener("online", cb);
146
+ window.addEventListener("offline", cb);
147
+ return () => {
148
+ window.removeEventListener("online", cb);
149
+ window.removeEventListener("offline", cb);
150
+ };
151
+ },
152
+ () => navigator.onLine,
153
+ () => true,
154
+ );
155
+ ```
156
+
157
+ ## React 19 Additions
158
+
159
+ - `use()` — unwrap promises and contexts inline; usable conditionally (only hook with that property)
160
+ - `useFormStatus()` / `useFormState()` (or `useActionState`) — form submission state without prop drilling
161
+ - `useOptimistic()` — optimistic UI updates while a server action is pending
162
+ - `useTransition()` — mark non-urgent state updates so urgent ones stay responsive
163
+
164
+ When the project targets React 19+, prefer these over hand-rolled equivalents.
165
+
166
+ ## Stale Closure Trap
167
+
168
+ Async handlers and intervals capture the values from the render where they were created. Fix by:
169
+
170
+ 1. Using the functional updater form of `setState`
171
+ 2. Putting the changing value in the dep array of `useEffect` and rebuilding the handler
172
+ 3. Reading from a ref that is kept in sync
173
+
174
+ ## Lint Configuration
175
+
176
+ Required rules:
177
+
178
+ ```json
179
+ {
180
+ "rules": {
181
+ "react-hooks/rules-of-hooks": "error",
182
+ "react-hooks/exhaustive-deps": "warn"
183
+ }
184
+ }
185
+ ```
186
+
187
+ Treat `exhaustive-deps` warnings as errors in CI for new code.