@ranimontagna/agent-toolkit 0.1.6 → 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 (38) hide show
  1. package/README.md +28 -8
  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/SKILL.md +4 -4
  16. package/skills/frontend/react/react-patterns/rules/react/LICENSE +21 -0
  17. package/skills/frontend/react/react-patterns/rules/react/NOTICE.md +11 -0
  18. package/skills/frontend/react/react-patterns/rules/react/coding-style.md +109 -0
  19. package/skills/frontend/react/react-patterns/rules/react/hooks.md +187 -0
  20. package/skills/frontend/react/react-patterns/rules/react/patterns.md +194 -0
  21. package/skills/frontend/react/react-patterns/rules/react/security.md +180 -0
  22. package/skills/frontend/react/react-patterns/rules/react/testing.md +208 -0
  23. package/skills/frontend/react/react-performance/SKILL.md +2 -2
  24. package/skills/frontend/react/react-performance/rules/react/LICENSE +21 -0
  25. package/skills/frontend/react/react-performance/rules/react/NOTICE.md +11 -0
  26. package/skills/frontend/react/react-performance/rules/react/coding-style.md +109 -0
  27. package/skills/frontend/react/react-performance/rules/react/hooks.md +187 -0
  28. package/skills/frontend/react/react-performance/rules/react/patterns.md +194 -0
  29. package/skills/frontend/react/react-performance/rules/react/security.md +180 -0
  30. package/skills/frontend/react/react-performance/rules/react/testing.md +208 -0
  31. package/skills/frontend/react/react-testing/SKILL.md +4 -4
  32. package/skills/frontend/react/react-testing/rules/react/LICENSE +21 -0
  33. package/skills/frontend/react/react-testing/rules/react/NOTICE.md +11 -0
  34. package/skills/frontend/react/react-testing/rules/react/coding-style.md +109 -0
  35. package/skills/frontend/react/react-testing/rules/react/hooks.md +187 -0
  36. package/skills/frontend/react/react-testing/rules/react/patterns.md +194 -0
  37. package/skills/frontend/react/react-testing/rules/react/security.md +180 -0
  38. package/skills/frontend/react/react-testing/rules/react/testing.md +208 -0
@@ -0,0 +1,208 @@
1
+ ---
2
+ paths:
3
+ - "**/*.test.tsx"
4
+ - "**/*.test.jsx"
5
+ - "**/*.spec.tsx"
6
+ - "**/*.spec.jsx"
7
+ - "**/__tests__/**/*.ts"
8
+ - "**/__tests__/**/*.tsx"
9
+ ---
10
+ # React Testing
11
+
12
+ > This file extends the upstream `typescript/testing.md` and `common/testing.md` rules with React specific content.
13
+
14
+ ## Library Choice
15
+
16
+ - **React Testing Library (RTL)** — the standard for component testing. Tests behavior through the rendered DOM.
17
+ - **Vitest** — preferred runner for new Vite-based projects. Faster than Jest, native ESM, same API.
18
+ - **Jest** — still the default for Next.js / CRA projects. RTL works identically.
19
+ - **Playwright Component Testing** — when component tests need a real browser engine (animation, layout, complex events)
20
+ - **Cypress Component Testing** — alternative real-browser component runner
21
+
22
+ Pick one component test runner per project — do not mix RTL + Playwright CT in the same repo.
23
+
24
+ ## Core Principle
25
+
26
+ Test what the user sees and does, not implementation details.
27
+
28
+ - Query by accessible role first, then label, then text — fall back to `data-testid` only when nothing else fits
29
+ - Never assert on internal state, props passed to children, or which hooks were called
30
+ - Refactor without breaking tests = the test was testing behavior; that is the goal
31
+
32
+ ## Query Priority
33
+
34
+ RTL exposes queries in three families. Use this priority order top-down:
35
+
36
+ 1. **Accessible to everyone**
37
+ - `getByRole(role, { name })` — primary choice
38
+ - `getByLabelText` — for form inputs
39
+ - `getByPlaceholderText` — when no label is available (and add a label)
40
+ - `getByText` — for non-interactive text
41
+ - `getByDisplayValue` — for form fields with a current value
42
+
43
+ 2. **Semantic queries**
44
+ - `getByAltText` — for images
45
+ - `getByTitle` — last resort, low accessibility value
46
+
47
+ 3. **Test IDs**
48
+ - `getByTestId("some-id")` — escape hatch only, when none of the above work
49
+
50
+ `getBy*` throws when no match. `queryBy*` returns null (use for asserting absence). `findBy*` returns a promise (use for async).
51
+
52
+ ## User Interaction
53
+
54
+ Prefer `userEvent` over `fireEvent`. `userEvent` simulates real browser sequences (focus, keydown, beforeinput, input, keyup) — `fireEvent` dispatches a single synthetic event.
55
+
56
+ ```tsx
57
+ import userEvent from "@testing-library/user-event";
58
+
59
+ test("submits the form", async () => {
60
+ const user = userEvent.setup();
61
+ render(<UserForm onSubmit={handleSubmit} />);
62
+
63
+ await user.type(screen.getByLabelText("Email"), "user@example.com");
64
+ await user.click(screen.getByRole("button", { name: /save/i }));
65
+
66
+ expect(handleSubmit).toHaveBeenCalledWith({ email: "user@example.com" });
67
+ });
68
+ ```
69
+
70
+ - Always `await` `userEvent` calls — they are async
71
+ - Call `userEvent.setup()` once at the top of each test, then reuse the returned `user`
72
+
73
+ ## Async Assertions
74
+
75
+ ```tsx
76
+ // WRONG: synchronous query for async-rendered content
77
+ expect(screen.getByText("Loaded")).toBeInTheDocument(); // throws — not in DOM yet
78
+
79
+ // CORRECT: findBy* (returns a promise, retries)
80
+ expect(await screen.findByText("Loaded")).toBeInTheDocument();
81
+
82
+ // CORRECT: waitFor for non-element assertions
83
+ await waitFor(() => expect(saveSpy).toHaveBeenCalled());
84
+ ```
85
+
86
+ - `findBy*` for async element appearance
87
+ - `waitFor` for async expectations on side effects or other matchers
88
+ - Never `setTimeout` + assertion — flaky
89
+
90
+ ## Network Mocking with MSW
91
+
92
+ Use Mock Service Worker for any test that hits a network boundary. MSW runs at the network layer, so the component, hooks, and fetch library all behave as in production.
93
+
94
+ ```tsx
95
+ // test setup
96
+ import { setupServer } from "msw/node";
97
+ import { http, HttpResponse } from "msw";
98
+
99
+ const server = setupServer(
100
+ http.get("/api/users/:id", ({ params }) =>
101
+ HttpResponse.json({ id: params.id, name: "Alice" }),
102
+ ),
103
+ );
104
+
105
+ beforeAll(() => server.listen());
106
+ afterEach(() => server.resetHandlers());
107
+ afterAll(() => server.close());
108
+ ```
109
+
110
+ Per-test override:
111
+
112
+ ```tsx
113
+ test("renders error on 500", async () => {
114
+ server.use(http.get("/api/users/:id", () => new HttpResponse(null, { status: 500 })));
115
+ render(<UserPage id="1" />);
116
+ expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
117
+ });
118
+ ```
119
+
120
+ ## Avoid Snapshot Tests for Components
121
+
122
+ Snapshots of rendered output are brittle, hard to review, and rubber-stamped by reviewers. Use them only for:
123
+
124
+ - Pure data serialization (e.g., a transformer that produces a stable string)
125
+ - Catching unintended regressions in non-visual output
126
+
127
+ For component visual regression, use Playwright / Cypress / Percy screenshots — actual visual diffs, not DOM diffs.
128
+
129
+ ## Test Setup Helpers
130
+
131
+ Wrap providers once:
132
+
133
+ ```tsx
134
+ function renderWithProviders(ui: React.ReactElement) {
135
+ return render(
136
+ <QueryClientProvider client={new QueryClient()}>
137
+ <ThemeProvider theme={lightTheme}>
138
+ <Router>{ui}</Router>
139
+ </ThemeProvider>
140
+ </QueryClientProvider>,
141
+ );
142
+ }
143
+ ```
144
+
145
+ Export from `test-utils.tsx` and use everywhere.
146
+
147
+ ## Custom Hook Testing
148
+
149
+ Use `renderHook` from RTL:
150
+
151
+ ```tsx
152
+ import { renderHook, act } from "@testing-library/react";
153
+
154
+ test("useCounter increments", () => {
155
+ const { result } = renderHook(() => useCounter());
156
+ act(() => result.current.increment());
157
+ expect(result.current.count).toBe(1);
158
+ });
159
+ ```
160
+
161
+ - Always wrap state-changing calls in `act`
162
+ - Always test through the public hook API, not internal implementation
163
+
164
+ ## Accessibility Assertions
165
+
166
+ ```tsx
167
+ import { axe } from "vitest-axe"; // or jest-axe
168
+
169
+ test("UserCard has no a11y violations", async () => {
170
+ const { container } = render(<UserCard user={mockUser} />);
171
+ expect(await axe(container)).toHaveNoViolations();
172
+ });
173
+ ```
174
+
175
+ Run axe assertions in component tests — catches missing labels, ARIA misuse, color contrast (limited).
176
+
177
+ ## When to Reach for Playwright / Cypress
178
+
179
+ Component test with RTL + JSDOM cannot:
180
+
181
+ - Test real layout (flexbox, grid, viewport-dependent rendering)
182
+ - Test scrolling, drag-and-drop, paste from clipboard
183
+ - Test browser-native animation, CSS transitions
184
+ - Test cross-frame interactions (iframes, popups)
185
+
186
+ For those, use Playwright Component Testing or end-to-end Playwright/Cypress runs. See the e2e-testing skill when it is installed.
187
+
188
+ ## Coverage Targets
189
+
190
+ | Layer | Target |
191
+ |---|---|
192
+ | Pure utility functions | ≥90% |
193
+ | Custom hooks | ≥85% |
194
+ | Components (presentational) | ≥80% — behavior, not lines |
195
+ | Container components | ≥70% — golden paths + error states |
196
+ | Pages (E2E covered separately) | Smoke test per route minimum |
197
+
198
+ ## Anti-Patterns
199
+
200
+ - Asserting on `container.querySelector` — bypasses accessibility queries
201
+ - Asserting on number of renders — implementation detail
202
+ - Mocking React hooks (`jest.mock("react", ...)`) — refactor the component instead
203
+ - Mocking child components by default — tests the integration, not the parent in isolation
204
+ - Manual `act()` warnings ignored — they indicate real bugs
205
+
206
+ ## Skill Reference
207
+
208
+ See `skills/react-testing/SKILL.md` for end-to-end test examples, MSW patterns, and accessibility test scaffolding.
@@ -562,8 +562,8 @@ When the project ships React Compiler, demote `rerender-*` manual memoization ru
562
562
 
563
563
  ## Related
564
564
 
565
- - Skills: [react-patterns](../react-patterns/SKILL.md), [react-testing](../react-testing/SKILL.md), [frontend-patterns](../frontend-patterns/SKILL.md), [accessibility](../accessibility/SKILL.md), [nextjs-turbopack](../nextjs-turbopack/SKILL.md)
566
- - Rules: [rules/react/](../../rules/react/)
565
+ - Skills: [react-patterns](../react-patterns/SKILL.md), [react-testing](../react-testing/SKILL.md), frontend-patterns, accessibility, nextjs-turbopack
566
+ - Rules: [rules/react/](rules/react/)
567
567
  - Agents: `react-reviewer` enforces these rules in code review; `react-build-resolver` handles related build failures
568
568
  - Commands: `/react-review`, `/react-build`, `/react-test`
569
569
 
@@ -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.