# typescript-react-nextjs-patterns

Adopt this skill: https://proskills.md/skills/other/leejpsd-typescript-react-nextjs-patterns

Page: https://proskills.md/skills/other/leejpsd-typescript-react-nextjs-patterns
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 8214
upstream: https://github.com/leejpsd/typescript-react-nextjs-patterns/blob/HEAD/SKILL.md

````text
---
name: typescript-react-nextjs-patterns
description: >
  Production-grade TypeScript reference for React & Next.js frontend development.
  Covers type narrowing, component Props, generic hooks, discriminated unions,
  as const, satisfies, Zod validation, TanStack Query, server/client boundaries,
  forms, state management, performance, accessibility, debugging, and code review.
  Use when the user works with TypeScript in React or Next.js: type errors,
  Props design, generics, API typing, SSR/CSR boundaries, hydration issues,
  form validation, state management, performance, or code review.
  Also use for "how should I type this?", "why does this type error happen?",
  or any architectural decision involving TypeScript in a frontend context.
---

# TypeScript for React & Next.js — Agent Skill

A structured reference for AI coding agents assisting frontend engineers with TypeScript, React, and Next.js in production environments.

---

## Agent Behavior Rules

### Before answering, always verify:

1. **Server or client?** Server Components, Server Actions, and Route Handlers have different type constraints than `"use client"` components.
2. **Runtime validation needed?** Static types do NOT validate API responses, URL params, form data, or localStorage. Data crossing a trust boundary requires Zod or equivalent.
3. **App Router or Pages Router?** Patterns differ significantly. If unclear, ask.
4. **TypeScript version?** `satisfies` needs 5.0+, `NoInfer` 5.4+, inferred type predicates 5.5+. TS 6.0 is the final JS-based compiler; TS 7 is the Go-native rewrite — ~10x faster, same language, but tooling that consumes the old compiler API may lag.
5. **Next.js version?** `params` is a `Promise` in 15+. Caching model changed in 16+ (`"use cache"`), and 16 renames `middleware.ts` → `proxy.ts` (Node runtime).
6. **React version?** 19 makes `ref` a regular prop (`forwardRef` deprecated), renders `<Context>` directly, and replaces `useFormState` with `useActionState`. `useEffectEvent` and `<Activity>` need 19.2+.

### Assumptions the agent must NOT make:

- That API responses match their TypeScript types at runtime
- That `searchParams` values are the expected type (they are always `string | string[] | undefined`)
- That `any` in existing code is intentional
- That a type assertion (`as`) is justified without checking context
- That server-only imports are safe in client components
- That `useEffect` dependencies in existing code are correct

### When uncertain:

- State tradeoffs explicitly rather than picking one approach silently
- Mark unstable or version-dependent patterns as such
- Distinguish: **[HARD RULE]** (violating causes bugs) / **[DEFAULT]** (override with reason) / **[SITUATIONAL]** (depends on context)

### After context compaction:

If this session was compacted and the rules content survives only as a summary:

1. Do NOT answer from the summary — it drops the reasoning, examples, and edge cases.
2. Re-read the relevant file from the Decision Guide below before continuing. One file read is enough; this hub is deliberately thin so recovery is cheap.
3. If mid-task and unsure which file applies, re-read `HARD-RULES.md` first — every non-negotiable rule in compressed form.

---

## Decision Guide

### Quick: What pattern should I use?

| Situation | Start here |
|-----------|-----------|
| Typing component Props, children, events, refs | → `react-typescript-patterns.md` |
| Narrowing unions, `unknown`, type guards, utility types | → `typescript-core.md` |
| Next.js params, searchParams, Server Actions, RSC boundary | → `nextjs-typescript.md` |
| Discriminated unions, conditional props, compound components | → `component-patterns.md` |
| API responses, fetch typing, TanStack Query, caching | → `data-fetching-and-api-types.md` |
| Form state, validation, controlled vs uncontrolled | → `forms-and-validation.md` |
| Local state vs context vs server state vs Zustand | → `state-management.md` |
| Re-renders, memoization, accessibility | → `performance-and-accessibility.md` |
| Type errors, hydration, stale state, effect bugs | → `debugging-checklists.md` (hub) + `playbooks/` |
| PR review, risk vs preference, architecture smells | → `code-review-rules.md` |
| Common mistakes, cargo-cult patterns | → `anti-patterns.md` |

### Flowchart: Is this data safe to use?

```
Data comes from...
├─ Inside the app (useState, useReducer, computed)
│  → Static typing is sufficient. No runtime validation needed.
│
├─ Outside the app (API, URL, FormData, localStorage, postMessage)
│  → [HARD RULE] Validate at runtime. Use Zod or equivalent.
│  │
│  ├─ API response    → schema.parse(await res.json())
│  ├─ URL params      → schema.parse(searchParams)
│  ├─ FormData        → schema.safeParse({ field: formData.get('field') })
│  ├─ localStorage    → schema.safeParse(JSON.parse(stored))
│  └─ postMessage     → schema.safeParse(event.data)
│
└─ Third-party library callback
   → Check library types. Add runtime guard if types seem wrong.
```

### Flowchart: Where should this state live?

```
Is this data from a server/API?
├─ Yes → TanStack Query (NOT useState). See data-fetching-and-api-types.md
│
└─ No → Is it shareable via URL? (filters, page, sort)
   ├─ Yes → searchParams or nuqs. See state-management.md
   │
   └─ No → How many components need it?
      ├─ 1 component → useState or useReducer
      ├─ 2-3 in same tree → Lift state up (props)
      └─ Many across trees → How often does it change?
         ├─ Rarely (theme, locale, auth) → Context
         └─ Often (cart, notifications) → Zustand with selectors
```

### Flowchart: Should I memoize this?

```
Is there a measured performance problem?
├─ No → Don't memoize. Stop here.
│
└─ Yes → Can you restructure instead?
   ├─ Yes → Move state down, extract components. See performance-and-accessibility.md
   │
   └─ No → What needs memoizing?
      ├─ Expensive computation → useMemo (verify it's truly expensive)
      ├─ Callback to memoized child → useCallback
      └─ Component in a long list → React.memo (verify props are stable)
```

### Quick: hard rule vs default vs situational

| Label | Meaning | Example |
|-------|---------|---------|
| **[HARD RULE]** | Violating causes bugs or security issues. No exceptions. | "Validate API responses at runtime" |
| **[DEFAULT]** | Recommended unless you have a documented reason to deviate. | "Use `interface` for Props" |
| **[SITUATIONAL]** | Depends on context. Both options are valid. Explain your choice. | "Polymorphic components — only for design-system foundations" |

When you deviate from a **[DEFAULT]**, write the reason where a later session will find it — a one-line comment at the deviation site or in the commit message — since compaction and new sessions won't remember it.

---

## Code Generation Checklist

Before generating TypeScript/React/Next.js code:

**Context**
- [ ] Confirmed: server or client code?
- [ ] Confirmed: App Router or Pages Router?
- [ ] Confirmed: TypeScript strict mode enabled?

**Type Safety**
- [ ] No `any` — use `unknown` with validation or proper types
- [ ] No `as` without documented justification
- [ ] External data (API, URL, form, storage) validated at runtime
- [ ] Props use `interface`, only truly optional fields have `?`

**React**
- [ ] `children` typed as `React.ReactNode`
- [ ] Event handler Props expose values, not event objects
- [ ] Effects have stable dependencies and cleanup functions
- [ ] `"use client"` only where needed, as deep as possible
- [ ] No server data duplicated into `useState`

**Next.js (15+)**
- [ ] `params` and `searchParams` awaited
- [ ] Server Actions validate FormData with Zod
- [ ] Sensitive code protected with `import 'server-only'`
- [ ] Cross-boundary Props are RSC-serializable (no plain callbacks or class instances; `Date`/`Map`/`Set`/`Promise` are fine)

**Accessibility**
- [ ] Form inputs have associated labels
- [ ] Error messages use `role="alert"`
- [ ] Interactive elements are keyboard-access
````

## File: README.md
upstream: https://github.com/leejpsd/typescript-react-nextjs-patterns/blob/HEAD/README.md

````text
# typescript-react-nextjs-patterns
![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)
![TypeScript](https://img.shields.io/badge/TypeScript-5.8+-3178C6?logo=typescript&logoColor=white)
![React](https://img.shields.io/badge/React-18+-61DAFB?logo=react&logoColor=black)
![Next.js](https://img.shields.io/badge/Next.js-15+-000?logo=next.js)

> Production-grade Agent Skill for TypeScript, React, and Next.js.

Korean README: [README.ko.md](README.ko.md)

A structured markdown reference built for AI coding agents working on real TypeScript frontends, with especially strong coverage of React patterns and Next.js App Router architecture.

**Not an npm package. Not a tutorial.** A field manual for AI agents helping frontend engineers.

## Before / After

### Without this skill

```
User: "Type this API call"
Agent: const user: User = await res.json()  // ❌ no runtime validation
```

### With this skill

```
User: "Type this API call"
Agent:
  const userSchema = z.object({ id: z.string(), name: z.string(), email: z.email() })
  type User = z.infer<typeof userSchema>
  const user = userSchema.parse(await res.json())  // ✅ runtime + type safety
```

### Without this skill

```
User: "Add loading state to this component"
Agent: const [isLoading, setIsLoading] = useState(false)
       const [error, setError] = useState(null)
       const [data, setData] = useState(null)  // ❌ boolean flags, nullable fields
```

### With this skill

```
User: "Add loading state to this component"
Agent: // Uses discriminated union — impossible states are unrepresentable
  type State<T> =
    | { status: 'idle' }
    | { status: 'loading' }
    | { status: 'success'; data: T }
    | { status: 'error'; error: Error }
```

## Install

```bash
# Global (all projects)
git clone https://github.com/leejpsd/typescript-react-nextjs-patterns.git ~/.claude/skills/typescript-react-nextjs-patterns

# Project-only
git clone https://github.com/leejpsd/typescript-react-nextjs-patterns.git .claude/skills/typescript-react-nextjs-patterns
```

Compatible with Claude Code, Cursor, Codex, Gemini CLI, and any agent reading `SKILL.md`.

## Structure

```
typescript-react-nextjs-patterns/
├── SKILL.md                                ← Hub: agent rules, decision guide, checklists
├── HARD-RULES.md                           ← Every [HARD RULE] on one page (compaction survival kit)
├── rules/                                  ← Pattern references (loaded on demand)
│   ├── typescript-core.md                     Narrowing, unions, generics, utility types, as const, satisfies
│   ├── react-typescript-patterns.md           Props, children, events, refs, hooks, context
│   ├── nextjs-typescript.md                   App Router, params, Server Actions, RSC, Cache Components, proxy.ts, useOptimistic
│   ├── component-patterns.md                  Discriminated Props, compound components, modal/dialog, polymorphic
│   ├── data-fetching-and-api-types.md         Fetch, Zod, TanStack Query, Result<T,E>, pagination, error handling
│   ├── forms-and-validation.md                Form state, Zod, react-hook-form, Server Actions, multi-step forms
│   ├── state-management.md                    Local vs context vs Zustand (+ middleware) vs TanStack Query vs URL
│   ├── performance-and-accessibility.md       Memoization, effects, semantic HTML, ARIA, focus management
│   ├── debugging-checklists.md                Quick diagnosis router, serialization, null access
│   ├── code-review-rules.md                   Risk vs preference, architecture smells, comment templates
│   └── anti-patterns.md                       13 common mistakes with root causes and fixes
├── playbooks/                              ← Step-by-step debugging guides
│   ├── type-error-debugging.md                Systematic type error resolution
│   ├── hydration-issues.md                    SSR/CSR mismatch diagnosis flowchart
│   └── effect-dependency-bugs.md              Loops, stale closures, useEffectEvent, StrictMode, cleanups
├── README.md
└── LICENSE
```

## Version Coverage

Last currency sweep: **July 2026**. The content documents:

| Area | Baseline |
|------|----------|
| React | **19.x-first** — ref as prop, `<Context>` provider syntax, `use()`; **19.2** `useEffectEvent` + `<Activity>`; React 18 variants kept and marked as legacy; React Compiler 1.0 awareness |
| Next.js | **15+** (async `params`, generated `PageProps<'/route'>` helpers) and **16** (Cache Components `'use cache'` / `cacheLife` / `updateTag`, `proxy.ts` on the Node runtime) |
| TypeScript | 5.5+ in examples (inferred type predicates, `NoInfer`, const type params); version notes through **6.0** and the Go-native **7.0** |
| Libraries | Zod 4 (`z.email()`, `z.flattenError()`), TanStack Query v5, Zustand v5, react-hook-form 7, nuqs v2 |

Version-dependent rules are labeled in place (e.g. `forwardRef` — React 18 codebases only; Edge-runtime middleware — Next.js ≤15).

## What Makes This Different

Most frontend skills stop at generic TypeScript tips. This one is intentionally stronger on React and Next.js, where coding agents most often make costly mistakes: props design, effects, state ownership, server/client boundaries, `searchParams`, Server Actions, hydration, serialization, and review-time architecture tradeoffs.

It is designed not just to suggest patterns, but to help an agent make safer decisions in production React and Next.js codebases.

| Feature | Typical skill | This skill |
|---------|-------------|-----------|
| React + Next.js depth | Limited or generic | Strong coverage of real React patterns and Next.js App Router constraints |
| Pattern guidance | ✅ | ✅ |
| Agent behavior rules | ❌ | ✅ What to check first, what NOT to assume |
| Decision guide | ❌ | ✅ Situation → recommended pattern → file |
| Debugging playbooks | ❌ | ✅ Type errors, hydration, effects, serialization |
| Code review heuristics | ❌ | ✅ Risk vs preference, comment templates |
| Rule classification | ❌ | ✅ [HARD RULE] / [DEFAULT] / [SITUATIONAL] |
| Generation + review checklists | ❌ | ✅ Separate checklists in SKILL.md |
| Compaction recovery | ❌ | ✅ HARD-RULES.md digest + re-read instructions |
| Version currency | Often frozen at React 18 | ✅ React 19.2 / Next.js 16 / Zod 4 / TS 7 baseline, legacy paths labeled |

## Surviving Context Compaction

Long agent sessions get compacted, and skill content loaded early is often
summarized away mid-task. Three layers deal with this:

1. **Disk is the source of truth.** Compaction unloads content; it never destroys
   it. `SKILL.md` is a thin router, so recovery costs one file read — and it
   explicitly instructs agents to re-read the relevant rules file after compaction
   instead of answering from the summary.
2. **`HARD-RULES.md` is the survival kit.** Every [HARD RULE] compressed to one
   page, with pointers back to the source files. Small enough to stay in context
   permanently.
3. **Optional: re-inject automatically.** Paste `HARD-RULES.md` into your
   project's `CLAUDE.md`, or add a Claude Code `SessionStart` hook so it comes
   back on its own whenever a session resumes from compaction. In
   `.claude/settings.json`:

```json
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          {
            "type": "command",
            "command": "cat .claude/skills/typescript-react-nextjs-patterns/HARD-RULES.md"
          }
        ]
      }
    ]
  }
}
```

`SessionStart` hook stdout is added to the agent's context, so the hard rules
re-enter the conversation the moment the summary replaces them.

## Each File Contains

Consistent structure across all modules:

- **Scope** + **Consult when** + **See also** (cross-references)
- **Key rules** labeled as [HARD RULE], [DEFAULT], or [SITUATIONAL]
- **When to use / When NOT to use**
- **Examples** from real frontend scenarios (forms, APIs, lists, modals)
- **Counterexamples** showing the wrong approach
- **Tradeoffs** — what you gain and what you lose
- 
````
