
Ia React Frontend
- 4 installs
- 28 repo stars
- Updated August 5, 2026
- iliaal/whetstone
Guides React architecture with TypeScript, hooks, state management, Next.js App Router, performance, and Vitest testing.
About
A skill covering React component TypeScript, an effects decision tree, state-management choices, React 19 APIs, and Next.js App Router patterns. A developer uses it when structuring React components, managing state, or reviewing React and Next.js code.
- Effects decision tree and state-management selection
- React 19 APIs, Next.js rendering/caching, and RTL testing
Ia React Frontend by the numbers
- 4 all-time installs (skills.sh)
- Ranked #1,814 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/iliaal/whetstone --skill ia-react-frontendAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 4 |
|---|---|
| repo stars | ★ 28 |
| Last updated | August 5, 2026 |
| Repository | iliaal/whetstone ↗ |
What it does
Guides React architecture with TypeScript, hooks, state management, Next.js App Router, performance, and Vitest testing.
Files
React Frontend
Verify before implementing: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs via Context7 (query-docs) before writing code. Training data may lag current releases.
Component TypeScript
- Extend native elements with
ComponentPropsWithoutRef<'button'>, add custom props via intersection - Use
React.ReactNodefor children,React.ReactElementfor single element, render prop(data: T) => ReactNode - Discriminated unions for variant props -- TypeScript narrows automatically in branches
- Generic components:
<T>withkeyof Tfor column keys,T extends { id: string }for constraints - Event types:
React.MouseEvent<HTMLButtonElement>,FormEvent<HTMLFormElement>,ChangeEvent<HTMLInputElement> as constfor custom hook tuple returnsuseRef<HTMLInputElement>(null)for DOM (use?.),useRef<number>(0)for mutable values- Explicit
useState<User | null>(null)for unions/null - useReducer actions as discriminated unions:
{ type: 'set'; payload: number } | { type: 'reset' } - useContext null guard: throw in custom
useX()hook if context is null
Effects Decision Tree
Effects are escape hatches -- most logic should NOT use effects.
| Need | Solution |
|---|---|
| Derived value from props/state | Calculate during render (useMemo if expensive) |
| Reset state on prop change | key prop on component |
| Respond to user event | Event handler |
| Notify parent of state change | Call onChange in event handler, or fully controlled component |
| Chain of state updates | Calculate all next state in one event handler |
| Sync with external system | Effect with cleanup |
Effect rules:
- Never suppress the linter -- fix the code instead
- Use updater functions (
setItems(prev => [...prev, item])) to remove state dependencies - Move objects/functions inside effects to stabilize dependencies
useEffectEventfor non-reactive values (e.g., theme in a connection effect)- Always return cleanup for subscriptions, connections, listeners
- Data fetching cancellation (pick by situation):
AbortControllerfor fetch;ignoreflag for non-cancellable promises; React Query handles both automatically
Concurrency & Race Classes
Frontend bugs that survive type-checking and unit tests usually land in one of five race classes. Hunt each one explicitly during review:
1. Lifecycle cleanup gaps -- in-production signal: "Can't perform state update on an unmounted component" warnings, slow-burn memory leaks under rapid navigation, duplicate event handlers firing. Root cause: useEffect registered a listener/timer/observer without returning cleanup (see Effect rules above for the rule). 2. Remount-timing mistakes -- async callbacks mutate DOM or state after swap / disconnect / route change. Classic cases: a fetch().then(setData) resolves after navigation to a different route; a requestAnimationFrame fires after the parent unmounts. See "Data fetching" in Effect rules above for the cancellation hierarchy. 3. Boolean-as-state for UI that isn't binary -- isLoading: boolean can't represent idle | loading | success | error | retry without creating inconsistent combinations (isLoading: true, error: Error is contradictory). Prefer an explicit state constant ('idle' | 'loading' | 'success' | 'error') with a transition function so invalid states are unreachable. 4. Stale promises and timers with no cancel path -- a promise chain or setTimeout holds a reference to setState after the component's moved on. Bind every async operation to a cancel mechanism per the cancellation hierarchy above, and verify the cleanup path is exercised by a test. 5. Per-element handlers where delegation would be safer -- attaching onClick to every row in a list creates N closures and N subscriptions; delegated listeners (single handler on the parent reading event.target.closest(...)) are safer under rapid re-renders, avoid stale-closure bugs, and scale to large lists. Use delegation when the list exceeds ~50 items or updates frequently.
These classes produce bugs that are intermittent, environment-dependent, and invisible to type-checking -- exactly the ones that reach production. Review for them deliberately, not just as "subscriptions need cleanup."
State Management
Local UI state → useState, useReducer
Shared client state → Zustand (simple) | Redux Toolkit (complex)
Atomic/granular → Jotai
Server/remote data → React Query (TanStack Query)
URL state → nuqs, router search params
Form state → React Hook FormKey patterns:
- Zustand:
create<State>()(devtools(persist((set) => ({...}))))-- use slices for scale, selective subscriptions to prevent re-renders - React Query: query keys factory (
['users', 'detail', id] as const),staleTime/gcTime, optimistic updates withonMutate/onErrorrollback - Separate client state (Zustand) from server state (React Query) -- never duplicate server data in client store
- Colocate state close to where it's used; don't over-globalize
Performance
Critical -- eliminate waterfalls:
Promise.all()for independent async operations- Move
awaitinto branches where actually needed - Suspense boundaries to stream slow content
Critical -- bundle size:
- Import directly from modules, avoid barrel files (
index.tsre-exports) next/dynamicorReact.lazy()for heavy components- Defer third-party scripts (analytics, logging) until after hydration
- Preload on hover/focus for perceived speed
content-visibility: auto+contain-intrinsic-sizeon long lists -- skips off-screen layout/paint
Re-render optimization:
- Derive state during render, not in effects
- Subscribe to derived booleans, not raw objects (
state.items.length > 0notstate.items) - Functional setState for stable callbacks:
setCount(c => c + 1) - Lazy state init:
useState(() => expensiveComputation()) useTransitionfor non-urgent updates (search filtering)useDeferredValuefor expensive derived UI- Don't subscribe to searchParams/state if only read in callbacks -- read on demand instead
- Use ternary (
condition ? <A /> : <B />), not&&for conditionals React.memoonly for expensive subtrees with stable props- Hoist static JSX outside components
React Compiler (React 19): auto-memoizes -- write idiomatic React, remove manual useMemo/useCallback/memo. Enable via framework config (Next.js: reactCompiler: true in next.config). Non-framework: install babel-plugin-react-compiler. Keep components pure.
React 19
- ref as prop --
forwardRefdeprecated. Acceptref?: React.Ref<HTMLElement>as regular prop - useActionState -- replaces
useFormState:const [state, formAction, isPending] = useActionState(action, initialState) - use() -- unwrap Promise or Context during render (not in callbacks/effects). Enables conditional context reads
- useOptimistic --
const [optimistic, addOptimistic] = useOptimistic(state, mergeFn)for instant UI feedback - useFormStatus --
const { pending } = useFormStatus()in child of<form action={...}> - Server Components -- default in App Router. Async, access DB/secrets directly. No hooks, no event handlers
- Server Actions --
'use server'directive. Validate inputs (Zod),revalidateTag/revalidatePathafter mutations. Server Actions are public endpoints -- always verify auth/authz inside each action, not just in middleware or layout guards - `<Activity mode='visible'|'hidden'>` -- preserves state/DOM for toggled components (experimental)
Next.js App Router
File conventions: page.tsx (route UI), layout.tsx (shared wrapper), template.tsx (re-mounted on navigation, unlike layout), loading.tsx (Suspense), error.tsx (error boundary), not-found.tsx (404), default.tsx (parallel route fallback), route.ts (API endpoint)
Rendering modes: Server Components (default) | Client ('use client') | Static (build) | Dynamic (request) | Streaming (progressive)
Decision: Server Component unless it needs hooks, event handlers, or browser APIs. Split: server parent + client child. Isolate interactive components as 'use client' leaf components -- keep server components static with no global state or event handlers.
Routing patterns:
- Route groups
(name)-- organize without affecting URL - Parallel routes
@slot-- independent loading states in same layout - Intercepting routes
(.)-- modal overlays with full-page fallback
Caching:
fetch(url, { cache: 'force-cache' })-- staticfetch(url, { next: { revalidate: 60 } })-- ISRfetch(url, { cache: 'no-store' })-- dynamic- Tag-based:
fetch(url, { next: { tags: ['products'] } })thenrevalidateTag('products')
Data fetching: Fetch in Server Components where data is used. Use Suspense boundaries for slow queries. React.cache() for per-request dedup. generateStaticParams for static generation. generateMetadata for dynamic SEO. Static metadata with title: { default: 'App', template: '%s | App' } for cascading page titles. after() for non-blocking side effects (logging, analytics) -- runs after response is sent. Hoist static I/O (fonts, config) to module level -- runs once, not per request.
Testing (Vitest + React Testing Library)
- Component tests: Vitest + RTL, co-located
*.test.tsx. Default for React components. - Hook tests:
renderHook+act, co-located*.test.ts - Unit tests: Vitest for pure functions, utilities, services
- E2E: Playwright for user flows and critical paths
- Query priority:
getByRole>getByLabelText>getByPlaceholderText>getByText>getByTestId - Mock API services and external providers; render child components real for integration confidence
- One behavior per test with AAA structure. Name:
should <behavior> when <condition> - Use
userEventoverfireEventfor realistic interactions findBy*for async elements,waitForafter state-triggering actionsvi.clearAllMocks()inbeforeEach. Recreate state per test.
General testing discipline (anti-patterns, rationalization resistance): see ia-writing-tests skill. See testing patterns and examples for component, hook, and mocking examples. See e2e testing for Playwright patterns.
Tailwind Integration
For Tailwind v4 configuration, utility patterns, dark mode, and component variants, see ia-tailwind-css skill.
Class sorting in JSX: when using clsx, cva, cn, tv, or tw utility functions, keep Tailwind classes in canonical order. Configure eslint-plugin-better-tailwindcss with useSortedClasses and functions: ["clsx", "cva", "cn", "tv", "tw"] to enforce this automatically across JSX attributes and helper calls.
Discipline
- Simplicity first -- every change as simple as possible, impact minimal code
- Only touch what's necessary -- avoid introducing unrelated changes
- No hacky workarounds -- if a fix feels wrong, step back and implement the clean solution
- Before adding a new abstraction, verify it appears in 3+ places
References
- testing.md -- Component, hook, and mocking test examples
- e2e-testing.md -- Playwright E2E patterns
Verify
- TypeScript compiles with zero errors
- No suppressed lint rules (
eslint-disable,@ts-ignore) in new code useEffectdependency arrays not manually overridden- No
forwardRefusage in React 19+ projects (userefprop directly)
E2E Testing with Playwright
When to read: when authoring Playwright end-to-end tests — directory layout, fixtures, page objects, network mocking, CI integration.
Directory Structure
e2e/
├── playwright.config.ts
├── fixtures/
│ ├── auth.fixture.ts
│ └── test-data.fixture.ts
├── pages/
│ ├── base.page.ts
│ └── <page-name>.page.ts
├── tests/
│ ├── auth/
│ │ └── login.spec.ts
│ └── smoke/
│ └── critical-paths.spec.ts
└── utils/
└── api-helpers.tsNaming: tests <feature>.spec.ts, page objects <page>.page.ts, fixtures <concern>.fixture.ts.
Configuration
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e/tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:5173',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },
dependencies: ['setup'],
},
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:5173',
reuseExistingServer: !process.env.CI,
},
});Page Object Model
Tests never use selectors directly -- page objects encapsulate all locators and actions.
// e2e/pages/base.page.ts
import { type Page, type Locator } from '@playwright/test';
export abstract class BasePage {
constructor(protected readonly page: Page) {}
abstract goto(): Promise<void>;
async waitForLoad() { await this.page.waitForLoadState('networkidle'); }
get toast(): Locator { return this.page.getByRole('alert'); }
}
// e2e/pages/users.page.ts
export class UsersPage extends BasePage {
readonly createButton: Locator;
readonly searchInput: Locator;
constructor(page: Page) {
super(page);
this.createButton = page.getByRole('button', { name: /create/i });
this.searchInput = page.getByRole('searchbox', { name: /search/i });
}
async goto() {
await this.page.goto('/users');
await this.waitForLoad();
}
async searchFor(query: string) {
await this.searchInput.fill(query);
await this.page.waitForResponse('**/api/users?*');
}
}Rules: locators as public readonly properties, actions as async methods with internal waits, no assertions in page objects, one PO per page.
Selector Priority
| Priority | Method | Use when |
|---|---|---|
| 1 | getByRole | Buttons, links, headings, inputs |
| 2 | getByLabel | Form inputs with labels |
| 3 | getByPlaceholder | Search inputs |
| 4 | getByText | Static text content |
| 5 | getByTestId | No accessible selector available |
Never use CSS selectors, XPath, or DOM structure selectors. When adding data-testid, use <action>-<entity>-<type> pattern: create-user-btn.
Wait Strategies
Never use waitForTimeout or setTimeout. Use explicit conditions:
await page.getByRole('heading', { name: 'Dashboard' }).waitFor();
await page.waitForURL('/dashboard');
await page.waitForResponse(
(r) => r.url().includes('/api/users') && r.status() === 200,
);
await page.getByTestId('spinner').waitFor({ state: 'hidden' });Auth State Reuse
Save auth state once, reuse across all tests:
// e2e/fixtures/auth.fixture.ts
import { test as setup } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('testuser@example.com');
await page.getByLabel('Password').fill('TestPassword123!');
await page.getByRole('button', { name: /sign in/i }).click();
await page.waitForURL('/dashboard');
await page.context().storageState({ path: 'e2e/.auth/user.json' });
});Tests receive auth state via storageState in config projects.
Test Data & Network
- Tests create own data via API helpers (faster than UI), clean up in
finallyblocks - Mock responses with
page.route('**/api/path', route => route.fulfill({ ... })) - Simulate errors with
route.abort('failed') - Wait for responses:
const resp = page.waitForResponse('**/api/users'); await click; await resp;
Flaky Test Fixes
| Cause | Fix |
|---|---|
| Hardcoded waits | Explicit wait conditions |
| Shared test data | Each test creates its own |
| Animations | animations: 'disabled' in config |
| Race conditions | Wait for API responses before assertions |
Quarantine workflow -- confirm flakiness before quarantining:
npx playwright test --repeat-each=10 path/to/test.spec.ts # Confirm flakiness
npx playwright test --retries=3 path/to/test.spec.ts # Check if retries helpMark confirmed flaky tests with an issue reference:
test.fixme(true, 'Flaky - Issue #123'); // Always skip
test.skip(!!process.env.CI, 'Flaky in CI only - Issue #123'); // Skip in CI onlynpx playwright test --headed --debug # Debug mode
npx playwright show-trace trace.zip # Trace viewer
npx playwright test --ui # Interactive UITesting React (Vitest + RTL)
When to read: when adding or fixing component tests with Vitest + React Testing Library — setup, queries, user-event, async assertions, mocking.
Setup
Vitest config: environment: 'jsdom', globals: true, setupFiles pointing to a file that imports @testing-library/jest-dom/vitest. Use @vitejs/plugin-react and mirror path aliases from tsconfig.json.
Component Test
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
vi.mock('@/api/client');
describe('UserForm', () => {
beforeEach(() => { vi.clearAllMocks(); });
it('should submit valid form data', async () => {
const onSubmit = vi.fn();
render(<UserForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText(/email/i), 'test@example.com');
await userEvent.click(screen.getByRole('button', { name: /submit/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({ email: 'test@example.com' }),
);
});
});
});Hook Test
import { renderHook, act } from '@testing-library/react';
it('should debounce value updates', () => {
vi.useFakeTimers();
const { result, rerender } = renderHook(
({ value }) => useDebounce(value, 300),
{ initialProps: { value: 'initial' } },
);
rerender({ value: 'updated' });
expect(result.current).toBe('initial');
act(() => { vi.advanceTimersByTime(300); });
expect(result.current).toBe('updated');
vi.useRealTimers();
});Mocking Patterns
// Service mock -- mock the module, not the transport layer
vi.mock('@/server-api/me/me.service', () => ({
MeService: { retrieveMe: vi.fn() },
}));
// QueryClient wrapper for components using TanStack Query
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
};
render(<Component />, { wrapper: createWrapper() });Test Classification
| Type | Tool | Target | File pattern |
|---|---|---|---|
| Unit | Vitest | Pure functions, utilities, services | Co-located *.test.ts |
| Component | Vitest + RTL | React components | Co-located *.test.tsx |
| Hook | Vitest + RTL | Custom hooks | Co-located *.test.ts |
| E2E | Playwright | User flows, critical paths | Separate e2e/ directory |
Running Tests
npx vitest # Watch mode
npx vitest run # Single run (CI)
npx vitest run src/features/ # Test specific directory
npx vitest --coverage # Coverage reportia-react-frontend Specification
Intent
ia-react-frontend is a language-class skill (stack-specific patterns and idioms). React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, or reviewing React code. For visual design and aesthetic direction, use frontend-design instead.
Scope
In scope:
- Behaviors described in
SKILL.mdand routed via the should_trigger phrasings indistillery/tests/fixtures/triggers/ia-react-frontend.jsonl. - Updates to runtime behavior, structure, trigger precision, references, and validation.
Out of scope:
- Acting as the runtime instructions themselves (those live in
SKILL.md). - Trigger phrasings already covered by adjacent
ia-*skills (validate-pluginflags >70% description overlap as DUPLICATE_TRIGGER). - <!-- to fill in: domain-specific exclusions when the skill drifts -->
Trigger Context
- Class:
language - Hook regex:
plugins/whetstone/hooks/skill-patterns.sh->SKILL_PATTERNS[ia-react-frontend] - Common requests (from fixture should_trigger):
- "create a React component with state management"
- "create a React hook for form validation"
- "fix the Next.js routing issue"
- Should not trigger for (from fixture should_not_trigger):
- "write a Laravel migration for the orders table"
- "optimize the database indexes"
- "write a bash script for deployment"
Source And Evidence Model
Authoritative sources:
SKILL.md-- runtime instructions and reference routing.references/*.md-- bundled supplementary content (2 file(s)).distillery/tests/fixtures/triggers/ia-react-frontend.jsonl-- positive and negative trigger phrasings under regression test.plugins/whetstone/hooks/skill-patterns.sh-- regex pattern that fires this skill.distillery/.eval-data/ia-react-frontend/-- harvested session examples (when present).
Data that must not be stored in this skill or its references:
- Secrets, credentials, tokens.
- Machine-specific filesystem paths (
/home/...,/Users/...,~/ai/...). The validator (MACHINE_PATH_LEAK) flags these as HIGH. - Private URLs, customer data, or unredacted personal information.
Coverage matrix
| Dimension | Status | Evidence |
|---|---|---|
| Trigger fixtures | complete | distillery/tests/fixtures/triggers/ia-react-frontend.jsonl (>=5 should_trigger, >=5 should_not_trigger) |
| Hook regex pattern | complete | plugins/whetstone/hooks/skill-patterns.sh (SKILL_PATTERNS[ia-react-frontend]) |
| Reference architecture | complete | 2 file(s) under references/ |
| Real-usage signal | <!-- populated by harvest-sessions when sessions exist --> | distillery/.eval-data/ia-react-frontend/ (created by harvest-sessions) |
Evaluation
Lightweight (run on every change):
python3 distillery/scripts/distiller.py validate-plugin --component ia-react-frontend
python3 distillery/scripts/distiller.py test-triggers --skill ia-react-frontendDeeper (when behavior risk warrants):
python3 distillery/scripts/distiller.py dspy-eval ia-react-frontend
python3 distillery/scripts/distiller.py diagnose-negatives ia-react-frontendAcceptance gates:
validate-plugin --component ia-react-frontendreturns 0 HIGH findings.test-triggers --skill ia-react-frontendreturns F1 = 1.0 with floors of 5 should_trigger and 5 should_not_trigger.- For dspy-eval, the composite score does not regress against the most recent saved baseline (see
distillery/.eval-data/ia-react-frontend/history.json).
Known Limitations
<!-- to fill in over time as drift surfaces. Default rule: any time diagnose-negatives surfaces a recurring failure pattern, document it here so future maintainers understand the trade-off the current implementation accepts. -->
Maintenance Notes
- Update
SKILL.mdwhen the runtime workflow, branch conditions, or output contract changes. - Update this
SPEC.mdwhen intent, scope, evidence model, evaluation gates, or maintenance expectations change. - Update the trigger fixture when adding new positive phrasings, removing stale ones, or expanding scope (the 5/5 floor is a hard validator gate).
- Update the hook regex in
skill-patterns.shwhenever fixture positives expose a missed phrasing; verify F1 = 1.0 witheval-triggersbefore committing. - Run the full release pipeline via
/release-- never bump versions or update CHANGELOG.md from a per-skill edit.