More claude stuff (#8280)

* More claude stuff

* more stuff from uee edit

* revert
This commit is contained in:
Ricky
2026-01-30 14:54:45 -05:00
committed by GitHub
parent 4c52ab89e5
commit 38b52cfdf0
13 changed files with 2880 additions and 802 deletions

View File

@@ -1,77 +1,28 @@
---
name: docs-reviewer
description: "Use after editing docs to review changes. Orchestrates docs-writer-learn, docs-writer-reference, docs-components, and docs-sandpack skills to validate structure, components, and style"
description: "Lean docs reviewer that dispatches reviews docs for a particular skill."
model: opus
color: cyan
---
# React Documentation Reviewer Agent
You are a direct, critical, expert reviewer for React documentation.
You are an expert reviewer for React documentation. Your role is to validate documentation changes for consistency, correctness, and adherence to established patterns.
Your role is to use given skills to validate given doc pages for consistency, correctness, and adherence to established patterns.
## Available Skills
Complete this process:
You have access to specialized skills that define the authoritative patterns for React docs. **Always invoke the relevant skills** to get the current patterns:
## Phase 1: Task Creation
1. CRITICAL: Read the skill requested.
2. Understand the skill's requirements.
3. Create a task list to validate skills requirements.
| Skill | When to Use |
|-------|-------------|
| `docs-writer-learn` | Reviewing files in `src/content/learn/` |
| `docs-writer-reference` | Reviewing files in `src/content/reference/` |
| `docs-components` | Validating MDX components (DeepDive, Pitfall, Note, Recipes, Challenges) |
| `docs-sandpack` | Validating interactive code examples |
## Phase 2: Validate
## Review Process
1. Read the docs files given.
2. Review each file with the task list to verify.
1. **Identify changed files** - Check git status or read the files to review
2. **Determine document type** based on path:
- `src/content/learn/**` → Invoke `docs-writer-learn`
- `src/content/reference/**` → Invoke `docs-writer-reference`
3. **Invoke component skills** for any MDX components or Sandpack examples in the file
4. **Read the patterns reference** at `.claude/docs/react-docs-patterns.md` for comprehensive details
5. **Validate against each skill's requirements**
6. **Run verification commands**
7. **Report issues with specific line numbers and fixes**
## Phase 3: Respond
## Verification Commands
You must respond with a checklist of the issues you identified, and line number.
These commands can help identify issues (user may run manually):
```bash
yarn lint-heading-ids # Check heading ID format
yarn lint # Check for ESLint issues
yarn deadlinks # Check for broken links
```
## Issue Reporting Format
```
## Documentation Review Results
### Errors (must fix)
- **Line 45**: Missing heading ID. Change `## Events` to `## Events {/*events*/}`
- **Line 78**: `<DeepDive>` missing `####` heading as first child
### Warnings (recommended)
- **Line 23**: Capitalize "effect" to "Effect" when referring to the React concept
### Summary
- Errors: X
- Warnings: Y
- Status: PASS | BLOCKED (fix errors before committing)
```
## Key Validation Points
These are quick checks - see the skills for full details:
### All Documents
- All `##`, `###`, `####` headings have explicit IDs: `{/*lowercase-with-hyphens*/}`
- React terms capitalized: Hook, Effect, State, Context, Ref, Component
- Uses "you" to address the reader
- No time estimates ("quick", "simple", "easy")
- Internal links use relative paths (`/learn/...`, `/reference/...`)
### Invoke Skills For
- **Structure validation** → `docs-writer-learn` or `docs-writer-reference`
- **Component usage** → `docs-components`
- **Code examples** → `docs-sandpack`
DO NOT respond with passed validations, ONLY respond with the problems.

View File

@@ -1,637 +0,0 @@
# React Documentation Patterns Reference
Comprehensive reference for React documentation patterns. Use this when writing or reviewing docs.
---
## Document Templates
### Learn Page Template (`src/content/learn/`)
```mdx
---
title: Your Page Title
---
<Intro>
Opening paragraph introducing the topic. Use *italics* for new terms being defined. Keep it to 1-2 sentences that hook the reader.
</Intro>
<YouWillLearn>
* Bullet point of what reader will learn
* Another learning outcome
* Keep to 3-5 items
</YouWillLearn>
## First Section {/*first-section*/}
Content with <Sandpack> examples...
<Recap>
* Summary bullet of key point
* Another summary point
</Recap>
<Challenges>
#### Challenge Title {/*challenge-id*/}
Challenge description...
<Sandpack>
{/* problem code */}
</Sandpack>
<Solution>
Explanation and solution...
<Sandpack>
{/* solution code */}
</Sandpack>
</Solution>
</Challenges>
```
### Reference Page Template (`src/content/reference/`)
```mdx
---
title: hookName
---
<Intro>
`hookName` is a React Hook that lets you [brief description].
\`\`\`js
const result = hookName(arg)
\`\`\`
</Intro>
<InlineToc />
---
## Reference {/*reference*/}
### `hookName(arg)` {/*hookname*/}
Call `hookName` at the top level of your component to...
\`\`\`js
import { hookName } from 'react';
function MyComponent() {
const result = hookName(initialValue);
// ...
\`\`\`
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `arg`: Description of the parameter.
#### Returns {/*returns*/}
Description of return value.
#### Caveats {/*caveats*/}
* Caveat about usage.
* Another important caveat.
---
## Usage {/*usage*/}
### Common Use Case {/*common-use-case*/}
Explanation with <Sandpack> examples...
---
## Troubleshooting {/*troubleshooting*/}
### Common Problem {/*common-problem*/}
How to solve it...
```
---
## Tone & Voice Guidelines
### Learn Pages
- Conversational, friendly
- Address the reader as "you"
- "Here's what that looks like..."
- "You might be wondering..."
- "Let's see how this works..."
### Reference Pages
- Precise, technical
- Still use "you" but more direct
- "Call `useState` at the top level..."
- "This Hook returns..."
### Universal Rules
- **Capitalize React terms:** Hook, Effect, State, Context, Ref, Component, Transition
- **Capitalize:** Server Component, Client Component, Server Action, Error Boundary, Suspense
- **Use proper product names:** ESLint, TypeScript, JavaScript (not lowercase)
- **Use bold** for key concepts: **state variable**, **event handler**
- **Use italics** for new terms being defined: *event handlers*
- Avoid "simple", "easy", "just" - these can be dismissive
- Prefer concrete examples over abstract explanations
- No time estimates ("quick", "takes X minutes")
- Frame feature differences as "capabilities" not "advantages/disadvantages"
- Avoid passive voice and jargon
### Avoiding Jargon
React docs explain technical concepts in plain language. Follow these patterns:
**Don't use CS jargon without explanation:**
- ❌ "State updates are atomic"
- ✅ "React waits until all state updates are done before re-rendering"
- ❌ "Components must be idempotent"
- ✅ "Given the same inputs, a component always returns the same output"
- ❌ "Rendering must be deterministic"
- ✅ "React expects the same inputs to produce the same result"
**Terms to avoid or always explain:**
- "atomic" → describe what actually happens (all-or-nothing, batched together)
- "idempotent" → "same inputs, same output"
- "deterministic" → "predictable", "same result every time"
- "memoize/memoization" → "remember the result", "skip recalculating"
- "referentially transparent" → avoid entirely, explain the behavior
- "invariant" → "rule that must always be true", "requirement"
- "reify" → avoid entirely, describe what's being created
**Use analogies the docs already establish:**
- Rendering = preparing food in a kitchen
- Committing = placing the order on the table
- Batching = waiter collecting the full order before going to kitchen
- State = snapshot/photograph at a moment in time
- Pure functions = math formulas (y = 2x always gives same result)
**Pattern: Explain behavior, then name it**
```markdown
React waits until all code in the event handlers has run before
processing your state updates. This is called *batching*.
```
Not:
```markdown
React uses batching to process state updates atomically.
```
---
## Code Style Rules (Enforced in PR Review)
These rules are strictly enforced during PR review:
### Component Definitions
```js
// ✅ Correct - function declaration
function MyInput({ value, onChange, ref }) {
return <input value={value} onChange={onChange} ref={ref} />;
}
export default MyInput;
// 🚫 Wrong - arrow function for component
const MyInput = ({ value, onChange, ref }) => {
return <input value={value} onChange={onChange} ref={ref} />;
};
```
### Event Handlers
```js
// ✅ Correct - use 'e' for event parameter
<button onClick={(e) => e.preventDefault()}>
// 🚫 Wrong - using 'event' (can conflict with global)
<button onClick={(event) => event.preventDefault()}>
```
### createRoot Pattern
```js
// ✅ Correct - two lines
const root = createRoot(document.getElementById('root'));
root.render(<App />);
// 🚫 Wrong - chained
createRoot(document.getElementById('root')).render(<App />);
```
### State vs Ref Decision
```js
// ✅ Use ref when value is not used for rendering
const isMounted = useRef(false);
// 🚫 Don't use state if not rendering based on it
const [isMounted, setIsMounted] = useState(false); // triggers re-render
```
### Hydration-Safe Code
```js
// ✅ Correct - same output on server and client
function App() {
const [count, setCount] = useState(0);
return <div>{count}</div>;
}
// 🚫 Wrong - different output causes hydration mismatch
function App() {
const isClient = typeof window !== 'undefined';
return <div>{isClient ? 'Client' : 'Server'}</div>;
}
```
## Line Length Guidelines
Keep lines short enough to avoid horizontal scrolling on small screens:
- Prose: ~80 characters
- Code: ~60-70 characters preferred
- If longer, break into multiple lines
## Anti-Patterns to Avoid
| Pattern | Problem | Fix |
|---------|---------|-----|
| `const Comp = () => {}` | Not standard for components | `function Comp() {}` |
| `onClick={(event) => ...}` | Conflicts with global | `onClick={(e) => ...}` |
| `useState` for non-rendered values | Unnecessary re-renders | Use `useRef` instead |
| Reading `window` during render | Hydration mismatch | Check in useEffect |
| Single-line if statements | Harder to read/debug | Use multiline with braces |
| Chained `createRoot().render()` | Less clear | Two separate statements |
| `//...` without space | Inconsistent style | Use `// ...` with space |
| Tabs for indentation | Inconsistent rendering | Use 2 spaces |
| Deprecated `ReactDOM.render` | Outdated API | Use `createRoot` |
| Fake package names | Confusing readers | Use `'./your-storage-layer'` |
| `PropsWithChildren` | Outdated pattern | Use `children?: React.ReactNode` |
| Missing `key` in lists | Causes warnings | Always include `key` prop |
---
## forwardRef and memo Patterns
### forwardRef with Named Function
```js
// ✅ Correct - named function for display name
const MyInput = forwardRef(function MyInput(props, ref) {
return <input {...props} ref={ref} />;
});
// 🚫 Wrong - anonymous function
const MyInput = forwardRef((props, ref) => {
return <input {...props} ref={ref} />;
});
```
### memo with Named Function
```js
// ✅ Correct - preserves component name
const Greeting = memo(function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
});
// 🚫 Wrong - loses component name in DevTools
const Greeting = memo(({ name }) => {
return <h1>Hello, {name}</h1>;
});
```
---
## MDX Component Decision Tree
### `<Pitfall>`
**Use for:** Common mistakes that cause bugs or unexpected behavior.
```mdx
<Pitfall>
React components must start with a capital letter or they won't work!
</Pitfall>
```
### `<Note>`
**Use for:** Important clarifications, conventions, or tips.
```mdx
<Note>
The convention is to name state variables like `[something, setSomething]`.
</Note>
```
### `<DeepDive>`
**Use for:** Optional deep technical content. **Must have `####` heading as first child.**
```mdx
<DeepDive>
#### Why does this work? {/*why-does-this-work*/}
Technical explanation that's optional for understanding the main concept...
</DeepDive>
```
### `<Sandpack>`
**Use for:** Interactive code examples.
```mdx
<Sandpack>
\`\`\`js
export default function App() {
return <h1>Hello</h1>;
}
\`\`\`
\`\`\`css
h1 { color: blue; }
\`\`\`
</Sandpack>
```
### `<Recipes>`
**Use for:** Multiple related examples showing variations.
```mdx
<Recipes titleText="Examples of useState" titleId="examples-basic">
#### Counter (number) {/*counter-number*/}
Description...
<Sandpack>
{/* code */}
</Sandpack>
<Solution />
#### Text field (string) {/*text-field-string*/}
Description...
<Sandpack>
{/* code */}
</Sandpack>
<Solution />
</Recipes>
```
### `<Challenges>`
**Use for:** End-of-page exercises (Learn pages only).
```mdx
<Challenges>
#### Fix the bug {/*fix-the-bug*/}
Problem description...
<Hint>
Optional hint text.
</Hint>
<Sandpack>
{/* problem code */}
</Sandpack>
<Solution>
Explanation...
<Sandpack>
{/* solution code */}
</Sandpack>
</Solution>
</Challenges>
```
---
## Sandpack Patterns
> **Comprehensive guidelines:** See `.claude/skills/docs-sandpack/SKILL.md` for complete Sandpack patterns including package.json usage, hidden/active files, file structure, and code size limits.
### Quick Reference
| Pattern | When to Use |
|---------|-------------|
| `hidden` | package.json, data files, API mocks, infrastructure |
| `active` | File containing primary teaching concept |
| Single file | Basic hooks, simple concepts (70% of examples) |
| Multi-file | Imports, context, component reuse (30% of examples) |
### File Naming
- Main file: ` ```js ` (no prefix)
- Supporting files: ` ```js src/FileName.js `
- Active file (reference pages): ` ```js src/File.js active `
- Hidden files: ` ```js src/data.js hidden `
- CSS: ` ```css `
- Package.json (for dependencies): ` ```json package.json `
### Line Highlighting
```mdx
\`\`\`js {2-4}
function Example() {
// These lines (2-4)
// will be
// highlighted
return null;
}
\`\`\`
```
### Code References (for callouts)
```mdx
\`\`\`js [[1, 4, "age"], [2, 4, "setAge"]]
// Creates numbered callouts pointing to specific code
\`\`\`
```
### Expected Errors (for intentionally broken examples)
```mdx
\`\`\`js {expectedErrors: {'react-compiler': [7]}}
// Line 7 will show as expected error
\`\`\`
```
### Multiple Files
```mdx
<Sandpack>
\`\`\`js src/App.js
import Gallery from './Gallery.js';
export default function App() {
return <Gallery />;
}
\`\`\`
\`\`\`js src/Gallery.js
export default function Gallery() {
return <h1>Gallery</h1>;
}
\`\`\`
\`\`\`css
h1 { color: purple; }
\`\`\`
</Sandpack>
```
### External Dependencies
```mdx
<Sandpack>
\`\`\`js
import { useImmer } from 'use-immer';
// ...
\`\`\`
\`\`\`json package.json
{
"dependencies": {
"immer": "1.7.3",
"use-immer": "0.5.1",
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest"
}
}
\`\`\`
</Sandpack>
```
---
## Common Patterns
### Showing Wrong vs Right Code
```mdx
\`\`\`js
// 🚩 Don't mutate state like this:
obj.x = 10;
setObj(obj);
\`\`\`
\`\`\`js
// ✅ Replace state with a new object:
setObj({
...obj,
x: 10
});
\`\`\`
```
### Table Comparisons
```mdx
| passing a function (correct) | calling a function (incorrect) |
| -------------------------------- | ---------------------------------- |
| `<button onClick={handleClick}>` | `<button onClick={handleClick()}>` |
```
### Linking to Other Pages
```mdx
[Read more about state](/learn/state-a-components-memory)
[See the `useState` reference](/reference/react/useState)
```
### Inline Code Annotations
Use `<CodeStep>` for numbered callouts in prose:
```mdx
The <CodeStep step={1}>current state</CodeStep> is initially set to the <CodeStep step={3}>initial state</CodeStep> you provided.
```
### Troubleshooting Sections
Error headings must follow this format:
```markdown
### I'm getting an error: "Too many re-renders" {/*too-many-re-renders*/}
This error usually means...
```
Not:
```markdown
### Too many re-renders error {/*too-many-re-renders*/}
```
---
## Blog Post Guidelines
### Updating Old Blog Posts
- Never break existing links; add redirects when URLs change
- Do not rewrite history; add update notes with dates instead of replacing text
- Use format: `**Update (Month Year):** New information here.`
### Announcing Features
- Do not promise or oversell features that are not yet available
- If a feature is "upcoming," say so explicitly
- Include FAQ sections for anticipated developer questions
- Focus on correctness over marketing language
---
## React 19+ Documentation Patterns
### Documenting API Changes
When APIs change between versions, document both patterns:
```mdx
Starting in React 19, you can render `<SomeContext>` as a provider:
\`\`\`js
<SomeContext value={value}>
{children}
</SomeContext>
\`\`\`
In older versions of React, use `<SomeContext.Provider>`:
\`\`\`js
<SomeContext.Provider value={value}>
{children}
</SomeContext.Provider>
\`\`\`
```
### Version Notes
- Use "Starting in React 19..." for new patterns
- Use "In older versions of React..." for legacy patterns
- Add version badges where appropriate

View File

@@ -13,6 +13,11 @@
},
"permissions": {
"allow": [
"Skill(docs-voice)",
"Skill(docs-components)",
"Skill(docs-sandpack)",
"Skill(docs-writer-learn)",
"Skill(docs-writer-reference)",
"Bash(yarn lint:*)",
"Bash(yarn lint-heading-ids:*)",
"Bash(yarn lint:fix:*)",

View File

@@ -1,58 +1,238 @@
---
name: docs-components
description: MDX component patterns for React documentation. Invoke when adding DeepDive, Pitfall, Note, Recipes, or Challenges to docs.
description: Comprehensive MDX component patterns (Note, Pitfall, DeepDive, Recipes, etc.) for all documentation types. Authoritative source for component usage, examples, and heading conventions.
---
# MDX Component Patterns
## `<Pitfall>`
## Quick Reference
Common mistakes that cause bugs. Use for errors readers will likely make.
### Component Decision Tree
| Need | Component |
|------|-----------|
| Helpful tip or terminology | `<Note>` |
| Common mistake warning | `<Pitfall>` |
| Advanced technical explanation | `<DeepDive>` |
| Canary-only feature | `<Canary>` or `<CanaryBadge />` |
| Server Components only | `<RSC>` |
| Deprecated API | `<Deprecated>` |
| Experimental/WIP | `<Wip>` |
| Visual diagram | `<Diagram>` |
| Multiple related examples | `<Recipes>` |
| Interactive code | `<Sandpack>` (see `/docs-sandpack`) |
| Console error display | `<ConsoleBlock>` |
| End-of-page exercises | `<Challenges>` (Learn pages only) |
### Heading Level Conventions
| Component | Heading Level |
|-----------|---------------|
| DeepDive title | `####` (h4) |
| Titled Pitfall | `#####` (h5) |
| Titled Note | `####` (h4) |
| Recipe items | `####` (h4) |
| Challenge items | `####` (h4) |
### Callout Spacing Rules
Callout components (Note, Pitfall, DeepDive) require a **blank line after the opening tag** before content begins.
**Never place consecutively:**
- `<Pitfall>` followed by `<Pitfall>` - Combine into one with titled subsections, or separate with prose
- `<Note>` followed by `<Note>` - Combine into one, or separate with prose
**Allowed consecutive patterns:**
- `<DeepDive>` followed by `<DeepDive>` - OK for multi-part explorations (see useMemo.md)
- `<Pitfall>` followed by `<DeepDive>` - OK when DeepDive explains "why" behind the Pitfall
**Separation content:** Prose paragraphs, code examples (Sandpack), or section headers.
**Why:** Consecutive warnings create a "wall of cautions" that overwhelms readers and causes important warnings to be skimmed.
**Incorrect:**
```mdx
<Pitfall>
Don't do X.
</Pitfall>
<Pitfall>
Don't do Y.
</Pitfall>
```
**Correct - combined:**
```mdx
<Pitfall>
React components must start with a capital letter or they won't work!
##### Don't do X {/*pitfall-x*/}
Explanation.
##### Don't do Y {/*pitfall-y*/}
Explanation.
</Pitfall>
```
**Correct - separated:**
```mdx
<Pitfall>
Don't do X.
</Pitfall>
This leads to another common mistake:
<Pitfall>
Don't do Y.
</Pitfall>
```
---
## `<Note>`
Important clarifications, conventions, or tips. Less severe than Pitfall.
### Simple Note
```mdx
<Note>
The convention is to name state variables like `[something, setSomething]`.
The optimization of caching return values is known as [_memoization_](https://en.wikipedia.org/wiki/Memoization).
</Note>
```
### Note with Title
Use `####` (h4) heading with an ID.
```mdx
<Note>
#### There is no directive for Server Components. {/*no-directive*/}
A common misunderstanding is that Server Components are denoted by `"use server"`, but there is no directive for Server Components. The `"use server"` directive is for Server Functions.
</Note>
```
### Version-Specific Note
```mdx
<Note>
Starting in React 19, you can render `<SomeContext>` as a provider.
In older versions of React, use `<SomeContext.Provider>`.
</Note>
```
---
## `<Pitfall>`
Common mistakes that cause bugs. Use for errors readers will likely make.
### Simple Pitfall
```mdx
<Pitfall>
We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives)
</Pitfall>
```
### Titled Pitfall
Use `#####` (h5) heading with an ID.
```mdx
<Pitfall>
##### Calling different memoized functions will read from different caches. {/*pitfall-different-caches*/}
To access the same cache, components must call the same memoized function.
</Pitfall>
```
### Pitfall with Wrong/Right Code
```mdx
<Pitfall>
##### `useFormStatus` will not return status information for a `<form>` rendered in the same component. {/*pitfall-same-component*/}
```js
function Form() {
// 🔴 `pending` will never be true
const { pending } = useFormStatus();
return <form action={submit}></form>;
}
```
Instead call `useFormStatus` from inside a component located inside `<form>`.
</Pitfall>
```
---
## `<DeepDive>`
Optional deep technical content. **First child must be `####` heading with ID.**
### Standard DeepDive
```mdx
<DeepDive>
#### Why does this work? {/*why-does-this-work*/}
#### Is using an updater always preferred? {/*is-updater-preferred*/}
Technical explanation that's optional for understanding the main concept...
You might hear a recommendation to always write code like `setAge(a => a + 1)` if the state you're setting is calculated from the previous state. There's no harm in it, but it's also not always necessary.
In most cases, there is no difference between these two approaches. React always makes sure that for intentional user actions, like clicks, the `age` state variable would be updated before the next click.
</DeepDive>
```
### Comparison DeepDive
For comparing related concepts:
```mdx
<DeepDive>
#### When should I use `cache`, `memo`, or `useMemo`? {/*cache-memo-usememo*/}
All mentioned APIs offer memoization but differ in what they memoize, who can access the cache, and when their cache is invalidated.
#### `useMemo` {/*deep-dive-usememo*/}
In general, you should use `useMemo` for caching expensive computations in Client Components across renders.
#### `cache` {/*deep-dive-cache*/}
In general, you should use `cache` in Server Components to memoize work that can be shared across components.
</DeepDive>
```
---
## `<Recipes>`
Multiple related examples showing variations. Each recipe needs `<Solution />`.
```mdx
<Recipes titleText="Examples of useState" titleId="examples-basic">
<Recipes titleText="Basic useState examples" titleId="examples-basic">
#### Counter (number) {/*counter-number*/}
Description...
In this example, the `count` state variable holds a number.
<Sandpack>
{/* code */}
@@ -62,7 +242,7 @@ Description...
#### Text field (string) {/*text-field-string*/}
Description...
In this example, the `text` state variable holds a string.
<Sandpack>
{/* code */}
@@ -73,6 +253,13 @@ Description...
</Recipes>
```
**Common titleText/titleId combinations:**
- "Basic [hookName] examples" / `examples-basic`
- "Examples of [concept]" / `examples-[concept]`
- "The difference between [A] and [B]" / `examples-[topic]`
---
## `<Challenges>`
End-of-page exercises. **Learn pages only.** Each challenge needs problem + solution Sandpack.
@@ -105,11 +292,158 @@ Explanation...
</Challenges>
```
**Guidelines:**
- Only at end of standard Learn pages
- No Challenges in chapter intros or tutorials
- Each challenge has `####` heading with ID
---
## `<Deprecated>`
For deprecated APIs. Content should explain what to use instead.
### Page-Level Deprecation
```mdx
<Deprecated>
In React 19, `forwardRef` is no longer necessary. Pass `ref` as a prop instead.
`forwardRef` will be deprecated in a future release. Learn more [here](/blog/2024/04/25/react-19#ref-as-a-prop).
</Deprecated>
```
### Method-Level Deprecation
```mdx
### `componentWillMount()` {/*componentwillmount*/}
<Deprecated>
This API has been renamed from `componentWillMount` to [`UNSAFE_componentWillMount`.](#unsafe_componentwillmount)
Run the [`rename-unsafe-lifecycles` codemod](codemod-link) to automatically update.
</Deprecated>
```
---
## `<RSC>`
For APIs that only work with React Server Components.
### Basic RSC
```mdx
<RSC>
`cache` is only for use with [React Server Components](/reference/rsc/server-components).
</RSC>
```
### Extended RSC (for Server Functions)
```mdx
<RSC>
Server Functions are for use in [React Server Components](/reference/rsc/server-components).
**Note:** Until September 2024, we referred to all Server Functions as "Server Actions".
</RSC>
```
---
## `<Canary>` and `<CanaryBadge />`
For features only available in Canary releases.
### Canary Wrapper (inline in Intro)
```mdx
<Intro>
`<Fragment>` lets you group elements without a wrapper node.
<Canary>Fragments can also accept refs, enabling interaction with underlying DOM nodes.</Canary>
</Intro>
```
### CanaryBadge in Section Headings
```mdx
### <CanaryBadge /> FragmentInstance {/*fragmentinstance*/}
```
### CanaryBadge in Props Lists
```mdx
* <CanaryBadge /> **optional** `ref`: A ref object from `useRef` or callback function.
```
### CanaryBadge in Caveats
```mdx
* <CanaryBadge /> If you want to pass `ref` to a Fragment, you can't use the `<>...</>` syntax.
```
---
## `<Diagram>`
Visual explanations of module dependencies, render trees, or data flow.
```mdx
<Diagram name="use_client_module_dependency" height={250} width={545} alt="A tree graph with the top node representing the module 'App.js'. 'App.js' has three children...">
`'use client'` segments the module dependency tree, marking `InspirationGenerator.js` and all dependencies as client-rendered.
</Diagram>
```
**Attributes:**
- `name`: Diagram identifier (used for image file)
- `height`: Height in pixels
- `width`: Width in pixels
- `alt`: Accessible description of the diagram
---
## `<CodeStep>` (Use Sparingly)
Numbered callouts in prose. Pairs with code block annotations.
**Important:** Use at most 2-3 colors in any given explanation. Excessive highlighting is distracting.
### Syntax
In code blocks:
```mdx
```js [[1, 4, "age"], [2, 4, "setAge"], [3, 4, "42"]]
import { useState } from 'react';
function MyComponent() {
const [age, setAge] = useState(42);
}
```
```
Format: `[[step_number, line_number, "text_to_highlight"], ...]`
In prose:
```mdx
1. The <CodeStep step={1}>current state</CodeStep> initially set to the <CodeStep step={3}>initial value</CodeStep>.
2. The <CodeStep step={2}>`set` function</CodeStep> that lets you change it.
```
### Guidelines
- Maximum 2-3 different colors per explanation
- Don't highlight every keyword - only key concepts
- Use for terms in prose, not entire code blocks
- Maintain consistent usage within a section
**Good use** - highlighting key concepts:
```mdx
@@ -121,21 +455,63 @@ React will compare the <CodeStep step={2}>dependencies</CodeStep> with the depen
When an <CodeStep step={1}>Activity</CodeStep> boundary is <CodeStep step={2}>hidden</CodeStep> during its <CodeStep step={3}>initial</CodeStep> render...
```
**Guidelines:**
- Maximum 2-3 different colors per explanation
- Don't highlight every keyword - only key concepts
- Use for terms in prose, not entire code blocks
- Maintain consistent usage within a section
---
## `<ConsoleBlock>`
Display console output (errors, warnings, logs).
```mdx
<ConsoleBlock level="error">
Uncaught Error: Too many re-renders.
</ConsoleBlock>
```
**Levels:** `error`, `warning`, `info`
---
## Component Usage by Page Type
### Reference Pages
For component placement rules specific to Reference pages, invoke `/docs-writer-reference`.
Key placement patterns:
- `<RSC>` goes before `<Intro>` at top of page
- `<Deprecated>` goes after `<Intro>` for page-level deprecation
- `<Deprecated>` goes after method heading for method-level deprecation
- `<Canary>` wrapper goes inline within `<Intro>`
- `<CanaryBadge />` appears in headings, props lists, and caveats
### Learn Pages
For Learn page structure and patterns, invoke `/docs-writer-learn`.
Key usage patterns:
- Challenges only at end of standard Learn pages
- No Challenges in chapter intros or tutorials
- DeepDive for optional advanced content
- CodeStep should be used sparingly
### Blog Pages
For Blog page structure and patterns, invoke `/docs-writer-blog`.
Key usage patterns:
- Generally avoid deep technical components
- Note and Pitfall OK for clarifications
- Prefer inline explanations over DeepDive
---
## Other Available Components
**Version/Status:** `<Canary>`, `<CanaryBadge />`, `<Experimental>`, `<ExperimentalBadge />`, `<Deprecated>`, `<RSC>`, `<RSCBadge />`, `<NextMajor>`, `<Wip>`
**Version/Status:** `<Experimental>`, `<ExperimentalBadge />`, `<RSCBadge />`, `<NextMajor>`, `<Wip>`
**Visuals:** `<Diagram>`, `<DiagramGroup>`, `<Illustration>`, `<IllustrationBlock>`, `<CodeDiagram>`, `<FullWidth>`
**Visuals:** `<DiagramGroup>`, `<Illustration>`, `<IllustrationBlock>`, `<CodeDiagram>`, `<FullWidth>`
**Console:** `<ConsoleBlock level="error|warning">`, `<ConsoleBlockMulti>`, `<ConsoleLogLine>`
**Console:** `<ConsoleBlockMulti>`, `<ConsoleLogLine>`
**Specialized:** `<TerminalBlock>`, `<BlogCard>`, `<TeamMember>`, `<YouTubeIframe>`, `<ErrorDecoder />`, `<LearnMore>`, `<Math>`, `<MathI>`, `<LanguageList>`

View File

@@ -1,10 +1,36 @@
---
name: docs-sandpack
description: Sandpack patterns for React documentation. Invoke when adding interactive code examples.
description: Use when adding interactive code examples to React docs.
---
# Sandpack Patterns
## Quick Start Template
Most examples are single-file. Copy this and modify:
```mdx
<Sandpack>
` ` `js
import { useState } from 'react';
export default function Example() {
const [value, setValue] = useState(0);
return (
<button onClick={() => setValue(value + 1)}>
Clicked {value} times
</button>
);
}
` ` `
</Sandpack>
```
---
## File Naming
| Pattern | Usage |
@@ -131,6 +157,50 @@ const mounted = useRef(false);
useEffect(() => { mounted.current = true; }, []);
```
## forwardRef and memo Patterns
### forwardRef - Use Named Function
```js
// ✅ Named function for DevTools display name
const MyInput = forwardRef(function MyInput(props, ref) {
return <input {...props} ref={ref} />;
});
// 🚫 Anonymous loses name
const MyInput = forwardRef((props, ref) => { ... });
```
### memo - Use Named Function
```js
// ✅ Preserves component name
const Greeting = memo(function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
});
```
## Line Length
- Prose: ~80 characters
- Code: ~60-70 characters
- Break long lines to avoid horizontal scrolling
## Anti-Patterns
| Pattern | Problem | Fix |
|---------|---------|-----|
| `const Comp = () => {}` | Not standard | `function Comp() {}` |
| `onClick={(event) => ...}` | Conflicts with global | `onClick={(e) => ...}` |
| `useState` for non-rendered values | Re-renders | Use `useRef` |
| Reading `window` during render | Hydration mismatch | Check in useEffect |
| Single-line if without braces | Harder to debug | Use multiline with braces |
| Chained `createRoot().render()` | Less clear | Two statements |
| `//...` without space | Inconsistent | `// ...` with space |
| Tabs | Inconsistent | 2 spaces |
| `ReactDOM.render` | Deprecated | Use `createRoot` |
| Fake package names | Confusing | Use `'./your-storage-layer'` |
| `PropsWithChildren` | Outdated | `children?: ReactNode` |
| Missing `key` in lists | Warnings | Always include key |
## Additional Code Quality Rules
### Always Include Keys in Lists
@@ -179,6 +249,68 @@ When modifying code in examples with line highlights (`{2-4}`), **always update
- Capitalize file names for component files: `Gallery.js` not `gallery.js`
- After initially explaining files are in `src/`, refer to files by name only: `Gallery.js` not `src/Gallery.js`
## Naming Conventions in Code
**Components:** PascalCase
- `Profile`, `Avatar`, `TodoList`, `PackingList`
**State variables:** Destructured pattern
- `const [count, setCount] = useState(0)`
- Booleans: `[isOnline, setIsOnline]`, `[isPacked, setIsPacked]`
- Status strings: `'typing'`, `'submitting'`, `'success'`, `'error'`
**Event handlers:**
- `handleClick`, `handleSubmit`, `handleAddTask`
**Props for callbacks:**
- `onClick`, `onChange`, `onAddTask`, `onSelect`
**Custom Hooks:**
- `useOnlineStatus`, `useChatRoom`, `useFormInput`
**Reducer actions:**
- Past tense: `'added'`, `'changed'`, `'deleted'`
- Snake_case compounds: `'changed_selection'`, `'sent_message'`
**Updater functions:** Single letter
- `setCount(n => n + 1)`
### Pedagogical Code Markers
**Wrong vs right code:**
```js
// 🔴 Avoid: redundant state and unnecessary Effect
// ✅ Good: calculated during rendering
```
**Console.log for lifecycle teaching:**
```js
console.log('✅ Connecting...');
console.log('❌ Disconnected.');
```
### Server/Client Labeling
```js
// Server Component
async function Notes() {
const notes = await db.notes.getAll();
}
// Client Component
"use client"
export default function Expandable({children}) {
const [expanded, setExpanded] = useState(false);
}
```
### Bundle Size Annotations
```js
import marked from 'marked'; // 35.9K (11.2K gzipped)
import sanitizeHtml from 'sanitize-html'; // 206K (63.3K gzipped)
```
---
## Sandpack Example Guidelines

View File

@@ -0,0 +1,137 @@
---
name: docs-voice
description: Use when writing any React documentation. Provides voice, tone, and style rules for all doc types.
---
# React Docs Voice & Style
## Universal Rules
- **Capitalize React terms** when referring to the React concept in headings or as standalone concepts:
- Core: Hook, Effect, State, Context, Ref, Component, Fragment
- Concurrent: Transition, Action, Suspense
- Server: Server Component, Client Component, Server Function, Server Action
- Patterns: Error Boundary
- Canary: Activity, View Transition, Transition Type
- **In prose:** Use lowercase when paired with descriptors: "state variable", "state updates", "event handler". Capitalize when the concept stands alone or in headings: "State is isolated and private"
- General usage stays lowercase: "the page transitions", "takes an action"
- **Product names:** ESLint, TypeScript, JavaScript, Next.js (not lowercase)
- **Bold** for key concepts: **state variable**, **event handler**
- **Italics** for new terms being defined: *event handlers*
- **Inline code** for APIs: `useState`, `startTransition`, `<Suspense>`
- **Avoid:** "simple", "easy", "just", time estimates
- Frame differences as "capabilities" not "advantages/disadvantages"
- Avoid passive voice and jargon
## Tone by Page Type
| Type | Tone | Example |
|------|------|---------|
| Learn | Conversational | "Here's what that looks like...", "You might be wondering..." |
| Reference | Technical | "Call `useState` at the top level...", "This Hook returns..." |
| Blog | Accurate | Focus on facts, not marketing |
**Note:** Pitfall and DeepDive components can use slightly more conversational phrasing ("You might wonder...", "It might be tempting...") even in Reference pages, since they're explanatory asides.
## Avoiding Jargon
**Pattern:** Explain behavior first, then name it.
✅ "React waits until all code in event handlers runs before processing state updates. This is called *batching*."
❌ "React uses batching to process state updates atomically."
**Terms to avoid or explain:**
| Jargon | Plain Language |
|--------|----------------|
| atomic | all-or-nothing, batched together |
| idempotent | same inputs, same output |
| deterministic | predictable, same result every time |
| memoize | remember the result, skip recalculating |
| referentially transparent | (avoid - describe the behavior) |
| invariant | rule that must always be true |
| reify | (avoid - describe what's being created) |
**Allowed technical terms in Reference pages:**
- "stale closures" - standard JS/React term, can be used in Caveats
- "stable identity" - React term for consistent object references across renders
- "reactive" - React term for values that trigger re-renders when changed
- These don't need explanation in Reference pages (readers are expected to know them)
**Use established analogies sparingly—once when introducing a concept, not repeatedly:**
| Concept | Analogy |
|---------|---------|
| Components/React | Kitchen (components as cooks, React as waiter) |
| Render phases | Restaurant ordering (trigger/render/commit) |
| State batching | Waiter collecting full order before going to kitchen |
| State behavior | Snapshot/photograph in time |
| State storage | React storing state "on a shelf" |
| State purpose | Component's memory |
| Pure functions | Recipes (same ingredients → same dish) |
| Pure functions | Math formulas (y = 2x) |
| Props | Adjustable "knobs" |
| Children prop | "Hole" to be filled by parent |
| Keys | File names in a folder |
| Curly braces in JSX | "Window into JavaScript" |
| Declarative UI | Taxi driver (destination, not turn-by-turn) |
| Imperative UI | Turn-by-turn navigation |
| State structure | Database normalization |
| Refs | "Secret pocket" React doesn't track |
| Effects/Refs | "Escape hatch" from React |
| Context | CSS inheritance / "Teleportation" |
| Custom Hooks | Design system |
## Common Prose Patterns
**Wrong vs Right code:**
```mdx
\`\`\`js
// 🚩 Don't mutate state:
obj.x = 10;
\`\`\`
\`\`\`js
// ✅ Replace with new object:
setObj({ ...obj, x: 10 });
\`\`\`
```
**Table comparisons:**
```mdx
| passing a function | calling a function |
| `onClick={handleClick}` | `onClick={handleClick()}` |
```
**Linking:**
```mdx
[Read about state](/learn/state-a-components-memory)
[See `useState` reference](/reference/react/useState)
```
## Code Style
- Prefer JSX over createElement
- Use const/let, never var
- Prefer named function declarations for top-level functions
- Arrow functions for callbacks that need `this` preservation
## Version Documentation
When APIs change between versions:
```mdx
Starting in React 19, render `<Context>` as a provider:
\`\`\`js
<SomeContext value={value}>{children}</SomeContext>
\`\`\`
In older versions:
\`\`\`js
<SomeContext.Provider value={value}>{children}</SomeContext.Provider>
\`\`\`
```
Patterns:
- "Starting in React 19..." for new APIs
- "In older versions of React..." for legacy patterns

View File

@@ -0,0 +1,756 @@
---
name: docs-writer-blog
description: Use when writing or editing files in src/content/blog/. Provides blog post structure and conventions.
---
# Blog Post Writer
## Persona
**Voice:** Official React team voice
**Tone:** Accurate, professional, forward-looking
## Voice & Style
For tone, capitalization, jargon, and prose patterns, invoke `/docs-voice`.
---
## Frontmatter Schema
All blog posts use this YAML frontmatter structure:
```yaml
---
title: "Title in Quotes"
author: Author Name(s)
date: YYYY/MM/DD
description: One or two sentence summary.
---
```
### Field Details
| Field | Format | Example |
|-------|--------|---------|
| `title` | Quoted string | `"React v19"`, `"React Conf 2024 Recap"` |
| `author` | Unquoted, comma + "and" for multiple | `The React Team`, `Dan Abramov and Lauren Tan` |
| `date` | `YYYY/MM/DD` with forward slashes | `2024/12/05` |
| `description` | 1-2 sentences, often mirrors intro | Summarizes announcement or content |
### Title Patterns by Post Type
| Type | Pattern | Example |
|------|---------|---------|
| Release | `"React vX.Y"` or `"React X.Y"` | `"React v19"` |
| Upgrade | `"React [VERSION] Upgrade Guide"` | `"How to Upgrade to React 18"` |
| Labs | `"React Labs: [Topic] [Month Year]"` | `"React Labs: What We've Been Working On February 2024"` |
| Conf | `"React Conf [YEAR] Recap"` | `"React Conf 2024 Recap"` |
| Feature | `"Introducing [Feature]"` or descriptive | `"Introducing react.dev"` |
| Security | `"[Severity] Security Vulnerability in [Component]"` | `"Critical Security Vulnerability in React Server Components"` |
---
## Author Byline
Immediately after frontmatter, add a byline:
```markdown
---
Month DD, YYYY by [Author Name](social-link)
---
```
### Conventions
- Full date spelled out: `December 05, 2024`
- Team posts link to `/community/team`: `[The React Team](/community/team)`
- Individual authors link to Twitter/X or Bluesky
- Multiple authors: Oxford comma before "and"
- Followed by horizontal rule `---`
**Examples:**
```markdown
December 05, 2024 by [The React Team](/community/team)
---
```
```markdown
May 3, 2023 by [Dan Abramov](https://bsky.app/profile/danabra.mov), [Sophie Alpert](https://twitter.com/sophiebits), and [Andrew Clark](https://twitter.com/acdlite)
---
```
---
## Universal Post Structure
All blog posts follow this structure:
1. **Frontmatter** (YAML)
2. **Author byline** with date
3. **Horizontal rule** (`---`)
4. **`<Intro>` component** (1-3 sentences)
5. **Horizontal rule** (`---`) (optional)
6. **Main content sections** (H2 with IDs)
7. **Closing section** (Changelog, Thanks, etc.)
---
## Post Type Templates
### Major Release Announcement
```markdown
---
title: "React vX.Y"
author: The React Team
date: YYYY/MM/DD
description: React X.Y is now available on npm! In this post, we'll give an overview of the new features.
---
Month DD, YYYY by [The React Team](/community/team)
---
<Intro>
React vX.Y is now available on npm!
</Intro>
In our [Upgrade Guide](/blog/YYYY/MM/DD/react-xy-upgrade-guide), we shared step-by-step instructions for upgrading. In this post, we'll give an overview of what's new.
- [What's new in React X.Y](#whats-new)
- [Improvements](#improvements)
- [How to upgrade](#how-to-upgrade)
---
## What's new in React X.Y {/*whats-new*/}
### Feature Name {/*feature-name*/}
[Problem this solves. Before/after code examples.]
For more information, see the docs for [`Feature`](/reference/react/Feature).
---
## Improvements in React X.Y {/*improvements*/}
### Improvement Name {/*improvement-name*/}
[Description of improvement.]
---
## How to upgrade {/*how-to-upgrade*/}
See [How to Upgrade to React X.Y](/blog/YYYY/MM/DD/react-xy-upgrade-guide) for step-by-step instructions.
---
## Changelog {/*changelog*/}
### React {/*react*/}
* Add `useNewHook` for [purpose]. ([#12345](https://github.com/facebook/react/pull/12345) by [@contributor](https://github.com/contributor))
---
_Thanks to [Name](url) for reviewing this post._
```
### Upgrade Guide
```markdown
---
title: "React [VERSION] Upgrade Guide"
author: Author Name
date: YYYY/MM/DD
description: Step-by-step instructions for upgrading to React [VERSION].
---
Month DD, YYYY by [Author Name](social-url)
---
<Intro>
[Summary of upgrade and what this guide covers.]
</Intro>
<Note>
#### Stepping stone version {/*stepping-stone*/}
[If applicable, describe intermediate upgrade steps.]
</Note>
In this post, we will guide you through the steps for upgrading:
- [Installing](#installing)
- [Codemods](#codemods)
- [Breaking changes](#breaking-changes)
- [New deprecations](#new-deprecations)
---
## Installing {/*installing*/}
```bash
npm install --save-exact react@^X.Y.Z react-dom@^X.Y.Z
```
## Codemods {/*codemods*/}
<Note>
#### Run all React [VERSION] codemods {/*run-all-codemods*/}
```bash
npx codemod@latest react/[VERSION]/migration-recipe
```
</Note>
## Breaking changes {/*breaking-changes*/}
### Removed: `apiName` {/*removed-api-name*/}
`apiName` was deprecated in [Month YYYY (vX.X.X)](link).
```js
// Before
[old code]
// After
[new code]
```
<Note>
Codemod [description]:
```bash
npx codemod@latest react/[VERSION]/codemod-name
```
</Note>
## New deprecations {/*new-deprecations*/}
### Deprecated: `apiName` {/*deprecated-api-name*/}
[Explanation and migration path.]
---
Thanks to [Contributor](link) for reviewing this post.
```
### React Labs Research Update
```markdown
---
title: "React Labs: What We've Been Working On [Month Year]"
author: Author1, Author2, and Author3
date: YYYY/MM/DD
description: In React Labs posts, we write about projects in active research and development.
---
Month DD, YYYY by [Author1](url), [Author2](url), and [Author3](url)
---
<Intro>
In React Labs posts, we write about projects in active research and development. We've made significant progress since our [last update](/blog/previous-labs-post), and we'd like to share our progress.
</Intro>
[Optional: Roadmap disclaimer about timelines]
---
## Feature Name {/*feature-name*/}
<Note>
`<FeatureName />` is now available in React's Canary channel.
</Note>
[Description of feature, motivation, current status.]
### Subsection {/*subsection*/}
[Details, examples, use cases.]
---
## Research Area {/*research-area*/}
[Problem space description. Status communication.]
This research is still early. We'll share more when we're further along.
---
_Thanks to [Reviewer](url) for reviewing this post._
Thanks for reading, and see you in the next update!
```
### React Conf Recap
```markdown
---
title: "React Conf [YEAR] Recap"
author: Author1 and Author2
date: YYYY/MM/DD
description: Last week we hosted React Conf [YEAR]. In this post, we'll summarize the talks and announcements.
---
Month DD, YYYY by [Author1](url) and [Author2](url)
---
<Intro>
Last week we hosted React Conf [YEAR] [where we announced [key announcements]].
</Intro>
---
The entire [day 1](youtube-url) and [day 2](youtube-url) streams are available online.
## Day 1 {/*day-1*/}
_[Watch the full day 1 stream here.](youtube-url)_
[Description of day 1 opening and keynote highlights.]
Watch the full day 1 keynote here:
<YouTubeIframe src="https://www.youtube.com/embed/VIDEO_ID" />
## Day 2 {/*day-2*/}
_[Watch the full day 2 stream here.](youtube-url)_
[Day 2 summary.]
<YouTubeIframe src="https://www.youtube.com/embed/VIDEO_ID" />
## Q&A {/*q-and-a*/}
* [Q&A Title](youtube-url) hosted by [Host](url)
## And more... {/*and-more*/}
We also heard talks including:
* [Talk Title](youtube-url) by [Speaker](url)
## Thank you {/*thank-you*/}
Thank you to all the staff, speakers, and participants who made React Conf [YEAR] possible.
See you next time!
```
### Feature/Tool Announcement
```markdown
---
title: "Introducing [Feature Name]"
author: Author Name
date: YYYY/MM/DD
description: Today we are announcing [feature]. In this post, we'll explain [what this post covers].
---
Month DD, YYYY by [Author Name](url)
---
<Intro>
Today we are [excited/thrilled] to announce [feature]. [What this means for users.]
</Intro>
---
## tl;dr {/*tldr*/}
* Key announcement point with [relevant link](/path).
* What users can do now.
* Availability or adoption information.
## What is [Feature]? {/*what-is-feature*/}
[Explanation of the feature/tool.]
## Why we built this {/*why-we-built-this*/}
[Motivation, history, problem being solved.]
## Getting started {/*getting-started*/}
To install [feature]:
<TerminalBlock>
npm install package-name
</TerminalBlock>
[You can find more documentation here.](/path/to/docs)
## What's next {/*whats-next*/}
[Future plans and next steps.]
## Thank you {/*thank-you*/}
[Acknowledgments to contributors.]
---
Thanks to [Reviewer](url) for reviewing this post.
```
### Security Announcement
```markdown
---
title: "[Severity] Security Vulnerability in [Component]"
author: The React Team
date: YYYY/MM/DD
description: Brief summary of the vulnerability. A fix has been published. We recommend upgrading immediately.
---
Month DD, YYYY by [The React Team](/community/team)
---
<Intro>
[One or two sentences summarizing the vulnerability.]
We recommend upgrading immediately.
</Intro>
---
On [date], [researcher] reported a security vulnerability that allows [description].
This vulnerability was disclosed as [CVE-YYYY-NNNNN](https://www.cve.org/CVERecord?id=CVE-YYYY-NNNNN) and is rated CVSS [score].
The vulnerability is present in versions [list] of:
* [package-name](https://www.npmjs.com/package/package-name)
## Immediate Action Required {/*immediate-action-required*/}
A fix was introduced in versions [linked versions]. Upgrade immediately.
### Affected frameworks {/*affected-frameworks*/}
[List of affected frameworks with npm links.]
### Vulnerability overview {/*vulnerability-overview*/}
[Technical explanation of the vulnerability.]
## Update Instructions {/*update-instructions*/}
### Framework Name {/*update-framework-name*/}
```bash
npm install package@version
```
## Timeline {/*timeline*/}
* **November 29th**: [Researcher] reported the vulnerability.
* **December 1st**: Fix was created and validated.
* **December 3rd**: Fix published and CVE disclosed.
## Attribution {/*attribution*/}
Thank you to [Researcher Name](url) for discovering and reporting this vulnerability.
```
---
## Heading Conventions
### ID Syntax
All headings require IDs using CSS comment syntax:
```markdown
## Heading Text {/*heading-id*/}
```
### ID Rules
- Lowercase
- Kebab-case (hyphens for spaces)
- Remove special characters (apostrophes, colons, backticks)
- Concise but descriptive
### Heading Patterns
| Context | Example |
|---------|---------|
| Feature section | `## New Feature: Automatic Batching {/*new-feature-automatic-batching*/}` |
| New hook | `### New hook: \`useActionState\` {/*new-hook-useactionstate*/}` |
| API in backticks | `### \`<Activity />\` {/*activity*/}` |
| Removed API | `#### Removed: \`propTypes\` {/*removed-proptypes*/}` |
| tl;dr section | `## tl;dr {/*tldr*/}` |
---
## Component Usage Guide
### Blog-Appropriate Components
| Component | Usage in Blog |
|-----------|---------------|
| `<Intro>` | **Required** - Opening summary after byline |
| `<Note>` | Callouts, caveats, important clarifications |
| `<Pitfall>` | Warnings about common mistakes |
| `<DeepDive>` | Optional technical deep dives (use sparingly) |
| `<TerminalBlock>` | CLI/installation commands |
| `<ConsoleBlock>` | Console error/warning output |
| `<ConsoleBlockMulti>` | Multi-line console output |
| `<YouTubeIframe>` | Conference video embeds |
| `<Diagram>` | Visual explanations |
| `<InlineToc />` | Auto-generated table of contents |
### `<Intro>` Pattern
Always wrap opening paragraph:
```markdown
<Intro>
React 19 is now available on npm!
</Intro>
```
### `<Note>` Patterns
**Simple note:**
```markdown
<Note>
For React Native users, React 18 ships with the New Architecture.
</Note>
```
**Titled note (H4 inside):**
```markdown
<Note>
#### React 18.3 has also been published {/*react-18-3*/}
To help with the upgrade, we've published `react@18.3`...
</Note>
```
### `<TerminalBlock>` Pattern
```markdown
<TerminalBlock>
npm install react@latest react-dom@latest
</TerminalBlock>
```
### `<YouTubeIframe>` Pattern
```markdown
<YouTubeIframe src="https://www.youtube.com/embed/VIDEO_ID" />
```
---
## Link Patterns
### Internal Links
| Type | Pattern | Example |
|------|---------|---------|
| Blog post | `/blog/YYYY/MM/DD/slug` | `/blog/2024/12/05/react-19` |
| API reference | `/reference/react/HookName` | `/reference/react/useState` |
| Learn section | `/learn/topic-name` | `/learn/react-compiler` |
| Community | `/community/team` | `/community/team` |
### External Links
| Type | Pattern |
|------|---------|
| GitHub PR | `[#12345](https://github.com/facebook/react/pull/12345)` |
| GitHub user | `[@username](https://github.com/username)` |
| Twitter/X | `[@username](https://x.com/username)` |
| Bluesky | `[Name](https://bsky.app/profile/handle)` |
| CVE | `[CVE-YYYY-NNNNN](https://www.cve.org/CVERecord?id=CVE-YYYY-NNNNN)` |
| npm package | `[package](https://www.npmjs.com/package/package)` |
### "See docs" Pattern
```markdown
For more information, see the docs for [`useActionState`](/reference/react/useActionState).
```
---
## Changelog Format
### Bullet Pattern
```markdown
* Add `useTransition` for concurrent rendering. ([#10426](https://github.com/facebook/react/pull/10426) by [@acdlite](https://github.com/acdlite))
* Fix `useReducer` observing incorrect props. ([#22445](https://github.com/facebook/react/pull/22445) by [@josephsavona](https://github.com/josephsavona))
```
**Structure:** `Verb` + backticked API + description + `([#PR](url) by [@user](url))`
**Verbs:** Add, Fix, Remove, Make, Improve, Allow, Deprecate
### Section Organization
```markdown
## Changelog {/*changelog*/}
### React {/*react*/}
* [changes]
### React DOM {/*react-dom*/}
* [changes]
```
---
## Acknowledgments Format
### Post-closing Thanks
```markdown
---
Thanks to [Name](url), [Name](url), and [Name](url) for reviewing this post.
```
Or italicized:
```markdown
_Thanks to [Name](url) for reviewing this post._
```
### Update Notes
For post-publication updates:
```markdown
<Note>
[Updated content]
-----
_Updated January 26, 2026._
</Note>
```
---
## Tone & Length by Post Type
| Type | Tone | Length | Key Elements |
|------|------|--------|--------------|
| Release | Celebratory, informative | Medium-long | Feature overview, upgrade link, changelog |
| Upgrade | Instructional, precise | Long | Step-by-step, codemods, breaking changes |
| Labs | Transparent, exploratory | Medium | Status updates, roadmap disclaimers |
| Conf | Enthusiastic, community-focused | Medium | YouTube embeds, speaker credits |
| Feature | Excited, explanatory | Medium | tl;dr, "why", getting started |
| Security | Urgent, factual | Short-medium | Immediate action, timeline, CVE |
---
## Do's and Don'ts
**Do:**
- Focus on facts over marketing
- Say "upcoming" explicitly for unreleased features
- Include FAQ sections for major announcements
- Credit contributors and link to GitHub
- Use "we" voice for team posts
- Link to upgrade guides from release posts
- Include table of contents for long posts
- End with acknowledgments
**Don't:**
- Promise features not yet available
- Rewrite history (add update notes instead)
- Break existing URLs
- Use hyperbolic language ("revolutionary", "game-changing")
- Skip the `<Intro>` component
- Forget heading IDs
- Use heavy component nesting in blogs
- Make time estimates or predictions
---
## Updating Old Posts
- Never break existing URLs; add redirects when URLs change
- Don't rewrite history; add update notes instead:
```markdown
<Note>
[Updated information]
-----
_Updated Month Year._
</Note>
```
---
## Critical Rules
1. **Heading IDs required:** `## Title {/*title-id*/}`
2. **`<Intro>` required:** Every post starts with `<Intro>` component
3. **Byline required:** Date + linked author(s) after frontmatter
4. **Date format:** Frontmatter uses `YYYY/MM/DD`, byline uses `Month DD, YYYY`
5. **Link to docs:** New APIs must link to reference documentation
6. **Security posts:** Always include "We recommend upgrading immediately"
---
## Components Reference
For complete MDX component patterns, invoke `/docs-components`.
Blog posts commonly use: `<Intro>`, `<Note>`, `<Pitfall>`, `<TerminalBlock>`, `<ConsoleBlock>`, `<YouTubeIframe>`, `<DeepDive>`, `<Diagram>`.
Prefer inline explanations over heavy component usage.

View File

@@ -1,66 +1,299 @@
---
name: docs-writer-learn
description: Auto-suggested when working on src/content/learn/**/*.md files. Provides Learn page structure and tone guidance.
description: Use when writing or editing files in src/content/learn/. Provides Learn page structure and tone.
---
# Learn Page Writer
## Template Structure
## Persona
**Voice:** Patient teacher guiding a friend through concepts
**Tone:** Conversational, warm, encouraging
## Voice & Style
For tone, capitalization, jargon, and prose patterns, invoke `/docs-voice`.
## Page Structure Variants
### 1. Standard Learn Page (Most Common)
```mdx
---
title: Your Page Title
title: Page Title
---
<Intro>
Opening paragraph (1-2 sentences). Use *italics* for new terms.
1-3 sentences introducing the concept. Use *italics* for new terms.
</Intro>
<YouWillLearn>
* Learning outcome (3-5 items)
* Learning outcome 1
* Learning outcome 2
* Learning outcome 3-5
</YouWillLearn>
## First Section {/*first-section*/}
Content with Sandpack examples...
## Section Name {/*section-id*/}
Content with Sandpack examples, Pitfalls, Notes, DeepDives...
## Another Section {/*another-section*/}
More content...
<Recap>
* Summary bullet points
* Summary point 1
* Summary point 2
* Summary points 3-9
</Recap>
<Challenges>
{/* End-of-page exercises */}
#### Challenge title {/*challenge-id*/}
Description...
<Hint>
Optional guidance (single paragraph)
</Hint>
<Sandpack>
{/* Starting code */}
</Sandpack>
<Solution>
Explanation...
<Sandpack>
{/* Fixed code */}
</Sandpack>
</Solution>
</Challenges>
```
## Tone
### 2. Chapter Introduction Page
Conversational and friendly:
- "Here's what that looks like..."
- "You might be wondering..."
- "Let's see how this works..."
For pages that introduce a chapter (like describing-the-ui.md, managing-state.md):
## Component Decision Tree
```mdx
<YouWillLearn isChapter={true}>
| When you need to... | Use |
|---------------------|-----|
| Warn about common mistakes that cause bugs | `<Pitfall>` |
| Clarify a convention or tip | `<Note>` |
| Explain optional deep technical details | `<DeepDive>` |
| Show multiple related variations | `<Recipes>` |
| Add end-of-page exercises | `<Challenges>` |
* [Sub-page title](/learn/sub-page-name) to learn...
* [Another page](/learn/another-page) to learn...
For component patterns, invoke `/docs-components`. For Sandpack patterns, invoke `/docs-sandpack`.
</YouWillLearn>
## Preview Section {/*section-id*/}
Preview description with mini Sandpack example
<LearnMore path="/learn/sub-page-name">
Read **[Page Title](/learn/sub-page-name)** to learn how to...
</LearnMore>
## What's next? {/*whats-next*/}
Head over to [First Page](/learn/first-page) to start reading this chapter page by page!
```
**Important:** Chapter intro pages do NOT include `<Recap>` or `<Challenges>` sections.
### 3. Tutorial Page
For step-by-step tutorials (like tutorial-tic-tac-toe.md):
```mdx
<Intro>
Brief statement of what will be built
</Intro>
<Note>
Alternative learning path offered
</Note>
Table of contents (prose listing of major sections)
## Setup {/*setup*/}
...
## Main Content {/*main-content*/}
Progressive code building with ### subsections
No YouWillLearn, Recap, or Challenges
Ends with ordered list of "extra credit" improvements
```
### 4. Reference-Style Learn Page
For pages with heavy API documentation (like typescript.md):
```mdx
<YouWillLearn>
* [Link to section](#section-anchor)
* [Link to another section](#another-section)
</YouWillLearn>
## Sections with ### subsections
## Further learning {/*further-learning*/}
No Recap or Challenges
```
## Heading ID Conventions
All headings require IDs in `{/*kebab-case*/}` format:
```markdown
## Section Title {/*section-title*/}
### Subsection Title {/*subsection-title*/}
#### DeepDive Title {/*deepdive-title*/}
```
**ID Generation Rules:**
- Lowercase everything
- Replace spaces with hyphens
- Remove apostrophes, quotes
- Remove or convert special chars (`:`, `?`, `!`, `.`, parentheses)
**Examples:**
- "What's React?" → `{/*whats-react*/}`
- "Step 1: Create the context" → `{/*step-1-create-the-context*/}`
- "Conditional (ternary) operator (? :)" → `{/*conditional-ternary-operator--*/}`
## Teaching Patterns
### Problem-First Teaching
Show broken/problematic code BEFORE the solution:
1. Present problematic approach with `// 🔴 Avoid:` comment
2. Explain WHY it's wrong (don't just say it is)
3. Show the solution with `// ✅ Good:` comment
4. Invite experimentation
### Progressive Complexity
Build understanding in layers:
1. Show simplest working version
2. Identify limitation or repetition
3. Introduce solution incrementally
4. Show complete solution
5. Invite experimentation: "Try changing..."
### Numbered Step Patterns
For multi-step processes:
**As section headings:**
```markdown
### Step 1: Action to take {/*step-1-action*/}
### Step 2: Next action {/*step-2-next-action*/}
```
**As inline lists:**
```markdown
To implement this:
1. **Declare** `inputRef` with the `useRef` Hook.
2. **Pass it** as `<input ref={inputRef}>`.
3. **Read** the input DOM node from `inputRef.current`.
```
### Interactive Invitations
After Sandpack examples, encourage experimentation:
- "Try changing X to Y. See how...?"
- "Try it in the sandbox above!"
- "Click each button separately:"
- "Have a guess!"
- "Verify that..."
### Decision Questions
Help readers build intuition:
> "When you're not sure whether some code should be in an Effect or in an event handler, ask yourself *why* this code needs to run."
## Component Placement Order
1. `<Intro>` - First after frontmatter
2. `<YouWillLearn>` - After Intro (standard/chapter pages)
3. Body content with `<Note>`, `<Pitfall>`, `<DeepDive>` placed contextually
4. `<Recap>` - Before Challenges (standard pages only)
5. `<Challenges>` - End of page (standard pages only)
For component structure and syntax, invoke `/docs-components`.
## Code Examples
For Sandpack file structure, naming conventions, code style, and pedagogical markers, invoke `/docs-sandpack`.
## Cross-Referencing
### When to Link
**Link to /learn:**
- Explaining concepts or mental models
- Teaching how things work together
- Tutorials and guides
- "Why" questions
**Link to /reference:**
- API details, Hook signatures
- Parameter lists and return values
- Rules and restrictions
- "What exactly" questions
### Link Formats
```markdown
[concept name](/learn/page-name)
[`useState`](/reference/react/useState)
[section link](/learn/page-name#section-id)
[MDN](https://developer.mozilla.org/...)
```
## Section Dividers
**Important:** Learn pages typically do NOT use `---` dividers. The heading hierarchy provides sufficient structure. Only consider dividers in exceptional cases like separating main content from meta/contribution sections.
## Do's and Don'ts
**Do:**
- Use "you" to address the reader
- Show broken code before fixes
- Explain behavior before naming concepts
- Build concepts progressively
- Include interactive Sandpack examples
- Use established analogies consistently
- Place Pitfalls AFTER explaining concepts
- Invite experimentation with "Try..." phrases
**Don't:**
- Use "simple", "easy", "just", or time estimates
- Reference concepts not yet introduced
- Skip required components for page type
- Use passive voice without reason
- Place Pitfalls before teaching the concept
- Use `---` dividers between sections
- Create unnecessary abstraction in examples
- Place consecutive Pitfalls or Notes without separating prose (combine or separate)
## Critical Rules
1. **Heading IDs required:** `## Title {/*title-id*/}` (lowercase, hyphens)
2. **Capitalize React terms** when referring to the React concept (not general usage):
- Core: Hook, Effect, State, Context, Ref, Component, Fragment
- Concurrent: Transition, Action, Suspense
- Server: Server Component, Client Component, Server Function, Server Action
- Patterns: Error Boundary
- Canary: Activity, View Transition, Transition Type
- General usage stays lowercase: "the page transitions" (not React), "takes an action" (not React)
3. **DeepDive must start with `####` heading**
4. **Sandpack main file needs `export default`**
5. **Avoid:** "simple", "easy", "just", time estimates
1. **All headings require IDs:** `## Title {/*title-id*/}`
2. **Chapter intros use `isChapter={true}` and `<LearnMore>`**
3. **Tutorial pages omit YouWillLearn/Recap/Challenges**
4. **Problem-first teaching:** Show broken → explain → fix
5. **No consecutive Pitfalls/Notes:** See `/docs-components` Callout Spacing Rules
For component patterns, invoke `/docs-components`. For Sandpack patterns, invoke `/docs-sandpack`.

View File

@@ -1,11 +1,61 @@
---
name: docs-writer-reference
description: Auto-suggested when working on src/content/reference/**/*.md files. Provides Reference page structure and tone guidance.
description: Reference page structure, templates, and writing patterns for src/content/reference/. For components, see /docs-components. For code examples, see /docs-sandpack.
---
# Reference Page Writer
## Template Structure
## Quick Reference
### Page Type Decision Tree
1. Is it a Hook? Use **Type A (Hook/Function)**
2. Is it a React component (`<Something>`)? Use **Type B (Component)**
3. Is it a compiler configuration option? Use **Type C (Configuration)**
4. Is it a directive (`'use something'`)? Use **Type D (Directive)**
5. Is it an ESLint rule? Use **Type E (ESLint Rule)**
6. Is it listing multiple APIs? Use **Type F (Index/Category)**
### Component Selection
For component selection and patterns, invoke `/docs-components`.
---
## Voice & Style
**Voice:** Authoritative technical reference writer
**Tone:** Precise, comprehensive, neutral
For tone, capitalization, jargon, and prose patterns, invoke `/docs-voice`.
**Do:**
- Start with single-line description: "`useState` is a React Hook that lets you..."
- Include Parameters, Returns, Caveats sections for every API
- Document edge cases most developers will encounter
- Use section dividers between major sections
- Include "See more examples below" links
- Be assertive, not hedging - "This is designed for..." not "This helps avoid issues with..."
- State facts, not benefits - "The callback always accesses the latest values" not "This helps avoid stale closures"
- Use minimal but meaningful names - `onEvent` or `onTick` over `onSomething`
**Don't:**
- Skip the InlineToc component
- Omit error cases or caveats
- Use conversational language
- Mix teaching with reference (that's Learn's job)
- Document past bugs or fixed issues
- Include niche edge cases (e.g., `this` binding, rare class patterns)
- Add phrases explaining "why you'd want this" - the Usage section examples do that
- Exception: Pitfall and DeepDive asides can use slightly conversational phrasing
---
## Page Templates
### Type A: Hook/Function
**When to use:** Documenting React hooks and standalone functions (useState, useEffect, memo, lazy, etc.)
```mdx
---
@@ -13,6 +63,7 @@ title: hookName
---
<Intro>
`hookName` is a React Hook that lets you [brief description].
```js
@@ -31,6 +82,12 @@ const result = hookName(arg)
Call `hookName` at the top level of your component to...
```js
[signature example with annotations]
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `arg`: Description of the parameter.
@@ -55,63 +112,774 @@ Explanation with Sandpack examples...
How to solve it...
```
## Formatting Details
---
### Type B: Component
**When to use:** Documenting React components (Suspense, Fragment, Activity, StrictMode)
```mdx
---
title: <ComponentName>
---
<Intro>
`<ComponentName>` lets you [primary action].
```js
<ComponentName prop={value}>
<Children />
</ComponentName>
```
</Intro>
<InlineToc />
---
## Reference {/*reference*/}
### `<ComponentName>` {/*componentname*/}
[Component purpose and behavior]
#### Props {/*props*/}
* `propName`: Description of the prop...
* **optional** `optionalProp`: Description...
#### Caveats {/*caveats*/}
* [Caveats specific to this component]
```
**Key differences from Hook pages:**
- Title uses JSX syntax: `<ComponentName>`
- Uses `#### Props` instead of `#### Parameters`
- Reference heading uses JSX: `` ### `<ComponentName>` ``
---
### Type C: Configuration
**When to use:** Documenting React Compiler configuration options
```mdx
---
title: optionName
---
<Intro>
The `optionName` option [controls/specifies/determines] [what it does].
</Intro>
```js
{
optionName: 'value' // Quick example
}
```
<InlineToc />
---
## Reference {/*reference*/}
### `optionName` {/*optionname*/}
[Description of the option's purpose]
#### Type {/*type*/}
```
'value1' | 'value2' | 'value3'
```
#### Default value {/*default-value*/}
`'value1'`
#### Options {/*options*/}
- **`'value1'`** (default): Description
- **`'value2'`**: Description
- **`'value3'`**: Description
#### Caveats {/*caveats*/}
* [Usage caveats]
```
---
### Type D: Directive
**When to use:** Documenting directives like 'use server', 'use client', 'use memo'
```mdx
---
title: "'use directive'"
titleForTitleTag: "'use directive' directive"
---
<RSC>
`'use directive'` is for use with [React Server Components](/reference/rsc/server-components).
</RSC>
<Intro>
`'use directive'` marks [what it marks] for [purpose].
```js {1}
function MyComponent() {
'use directive';
// ...
}
```
</Intro>
<InlineToc />
---
## Reference {/*reference*/}
### `'use directive'` {/*use-directive*/}
Add `'use directive'` at the beginning of [location] to [action].
#### Caveats {/*caveats*/}
* `'use directive'` must be at the very beginning...
* The directive must be written with single or double quotes, not backticks.
* [Other placement/syntax caveats]
```
**Key characteristics:**
- Title includes quotes: `title: "'use server'"`
- Uses `titleForTitleTag` for browser tab title
- `<RSC>` block appears before `<Intro>`
- Caveats focus on placement and syntax requirements
---
### Type E: ESLint Rule
**When to use:** Documenting ESLint plugin rules
```mdx
---
title: rule-name
---
<Intro>
Validates that [what the rule checks].
</Intro>
## Rule Details {/*rule-details*/}
[Explanation of why this rule exists and React's underlying assumptions]
## Common Violations {/*common-violations*/}
[Description of violation patterns]
### Invalid {/*invalid*/}
Examples of incorrect code for this rule:
```js
// X Missing dependency
useEffect(() => {
console.log(count);
}, []); // Missing 'count'
```
### Valid {/*valid*/}
Examples of correct code for this rule:
```js
// checkmark All dependencies included
useEffect(() => {
console.log(count);
}, [count]);
```
## Troubleshooting {/*troubleshooting*/}
### [Problem description] {/*problem-slug*/}
[Solution]
## Options {/*options*/}
[Configuration options if applicable]
```
**Key characteristics:**
- Intro is a single "Validates that..." sentence
- Uses "Invalid"/"Valid" sections with emoji-prefixed code comments
- Rule Details explains "why" not just "what"
---
### Type F: Index/Category
**When to use:** Overview pages listing multiple APIs in a category
```mdx
---
title: "Built-in React [Type]"
---
<Intro>
*Concept* let you [purpose]. Brief scope statement.
</Intro>
---
## Category Name {/*category-name*/}
*Concept* explanation with [Learn section link](/learn/topic).
To [action], use one of these [Type]:
* [`apiName`](/reference/react/apiName) lets you [action].
* [`apiName`](/reference/react/apiName) declares [thing].
```js
function Example() {
const value = useHookName(args);
}
```
---
## Your own [Type] {/*your-own-type*/}
You can also [define your own](/learn/topic) as JavaScript functions.
```
**Key characteristics:**
- Title format: "Built-in React [Type]"
- Italicized concept definitions
- Horizontal rules between sections
- Closes with "Your own [Type]" section
---
## Advanced Patterns
### Multi-Function Documentation
**When to use:** When a hook returns a function that needs its own documentation (useState's setter, useReducer's dispatch)
```md
### `hookName(args)` {/*hookname*/}
[Main hook documentation]
#### Parameters {/*parameters*/}
#### Returns {/*returns*/}
#### Caveats {/*caveats*/}
---
### `set` functions, like `setSomething(nextState)` {/*setstate*/}
The `set` function returned by `hookName` lets you [action].
#### Parameters {/*setstate-parameters*/}
#### Returns {/*setstate-returns*/}
#### Caveats {/*setstate-caveats*/}
```
**Key conventions:**
- Horizontal rule (`---`) separates main hook from returned function
- Heading IDs include prefix: `{/*setstate-parameters*/}` vs `{/*parameters*/}`
- Use generic names: "set functions" not "setCount"
---
### Compound Return Objects
**When to use:** When a function returns an object with multiple properties/methods (createContext)
```md
### `createContext(defaultValue)` {/*createcontext*/}
[Main function documentation]
#### Returns {/*returns*/}
`createContext` returns a context object.
**The context object itself does not hold any information.** It represents...
* `SomeContext` lets you provide the context value.
* `SomeContext.Consumer` is an alternative way to read context.
---
### `SomeContext` Provider {/*provider*/}
[Documentation for Provider]
#### Props {/*provider-props*/}
---
### `SomeContext.Consumer` {/*consumer*/}
[Documentation for Consumer]
#### Props {/*consumer-props*/}
```
---
## Writing Patterns
### Opening Lines by Page Type
| Page Type | Pattern | Example |
|-----------|---------|---------|
| Hook | `` `hookName` is a React Hook that lets you [action]. `` | "`useState` is a React Hook that lets you add a state variable to your component." |
| Component | `` `<ComponentName>` lets you [action]. `` | "`<Suspense>` lets you display a fallback until its children have finished loading." |
| API | `` `apiName` lets you [action]. `` | "`memo` lets you skip re-rendering a component when its props are unchanged." |
| Configuration | `` The `optionName` option [controls/specifies/determines] [what]. `` | "The `target` option specifies which React version the compiler generates code for." |
| Directive | `` `'directive'` [marks/opts/prevents] [what] for [purpose]. `` | "`'use server'` marks a function as callable from the client." |
| ESLint Rule | `` Validates that [condition]. `` | "Validates that dependency arrays for React hooks contain all necessary dependencies." |
---
### Parameter Patterns
**Simple parameter:**
```md
* `paramName`: Description of what it does.
```
**Optional parameter:**
```md
* **optional** `paramName`: Description of what it does.
```
**Parameter with special function behavior:**
```md
* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
* If you pass a function as `initialState`, it will be treated as an _initializer function_. It should be pure, should take no arguments, and should return a value of any type.
```
**Callback parameter with sub-parameters:**
```md
* `subscribe`: A function that takes a single `callback` argument and subscribes it to the store. When the store changes, it should invoke the provided `callback`. The `subscribe` function should return a function that cleans up the subscription.
```
**Nested options object:**
```md
* **optional** `options`: An object with options for this React root.
* **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary.
* **optional** `onUncaughtError`: Callback called when an error is thrown and not caught.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by `useId`.
```
---
### Return Value Patterns
**Single value return:**
```md
`hookName` returns the current value. The value will be the same as `initialValue` during the first render.
```
**Array return (numbered list):**
```md
`useState` returns an array with exactly two values:
1. The current state. During the first render, it will match the `initialState` you have passed.
2. The [`set` function](#setstate) that lets you update the state to a different value and trigger a re-render.
```
**Object return (bulleted list):**
```md
`createElement` returns a React element object with a few properties:
* `type`: The `type` you have passed.
* `props`: The `props` you have passed except for `ref` and `key`.
* `ref`: The `ref` you have passed. If missing, `null`.
* `key`: The `key` you have passed, coerced to a string. If missing, `null`.
```
**Promise return:**
```md
`prerender` returns a Promise:
- If rendering is successful, the Promise will resolve to an object containing:
- `prelude`: a [Web Stream](MDN-link) of HTML.
- `postponed`: a JSON-serializable object for resumption.
- If rendering fails, the Promise will be rejected.
```
**Wrapped function return:**
```md
`cache` returns a cached version of `fn` with the same type signature. It does not call `fn` in the process.
When calling `cachedFn` with given arguments, it first checks if a cached result exists. If cached, it returns the result. If not, it calls `fn`, stores the result, and returns it.
```
---
### Caveats Patterns
**Standard Hook caveat (almost always first for Hooks):**
```md
* `useXxx` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
```
**Stable identity caveat (for returned functions):**
```md
* The `set` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire.
```
**Strict Mode caveat:**
```md
* In Strict Mode, React will **call your render function twice** in order to help you find accidental impurities. This is development-only behavior and does not affect production.
```
**Caveat with code example:**
```md
* It's not recommended to _suspend_ a render based on a store value returned by `useSyncExternalStore`. For example, the following is discouraged:
```js
const selectedProductId = useSyncExternalStore(...);
const data = use(fetchItem(selectedProductId)) // X Don't suspend based on store value
```
```
**Canary caveat:**
```md
* <CanaryBadge /> If you want to pass `ref` to a Fragment, you can't use the `<>...</>` syntax.
```
---
### Troubleshooting Patterns
**Heading format (first person problem statements):**
```md
### I've updated the state, but logging gives me the old value {/*old-value*/}
### My initializer or updater function runs twice {/*runs-twice*/}
### I want to read the latest state from a callback {/*read-latest-state*/}
```
**Error message format:**
```md
### I'm getting an error: "Too many re-renders" {/*too-many-rerenders*/}
### I'm getting an error: "Rendered more hooks than during the previous render" {/*more-hooks*/}
```
**Lint error format:**
```md
### I'm getting a lint error: "[exact error message]" {/*lint-error-slug*/}
```
**Problem-solution structure:**
1. State the problem with code showing the issue
2. Explain why it happens
3. Provide the solution with corrected code
4. Link to Learn section for deeper understanding
---
### Code Comment Conventions
For code comment conventions (wrong/right, legacy/recommended, server/client labeling, bundle size annotations), invoke `/docs-sandpack`.
---
### Link Description Patterns
| Pattern | Example |
|---------|---------|
| "lets you" + action | "`memo` lets you skip re-rendering when props are unchanged." |
| "declares" + thing | "`useState` declares a state variable that you can update directly." |
| "reads" + thing | "`useContext` reads and subscribes to a context." |
| "connects" + thing | "`useEffect` connects a component to an external system." |
| "Used with" | "Used with [`useContext`.](/reference/react/useContext)" |
| "Similar to" | "Similar to [`useTransition`.](/reference/react/useTransition)" |
---
## Component Patterns
For comprehensive MDX component patterns (Note, Pitfall, DeepDive, Recipes, Deprecated, RSC, Canary, Diagram, Code Steps), invoke `/docs-components`.
For Sandpack-specific patterns and code style, invoke `/docs-sandpack`.
### Reference-Specific Component Rules
**Component placement in Reference pages:**
- `<RSC>` goes before `<Intro>` at top of page
- `<Deprecated>` goes after `<Intro>` for page-level deprecation
- `<Deprecated>` goes after method heading for method-level deprecation
- `<Canary>` wrapper goes inline within `<Intro>`
- `<CanaryBadge />` appears in headings, props lists, and caveats
**Troubleshooting-specific components:**
- Use first-person problem headings
- Cross-reference Pitfall IDs when relevant
**Callout spacing:**
- Never place consecutive Pitfalls or consecutive Notes
- Combine related warnings into one with titled subsections, or separate with prose/code
- Consecutive DeepDives OK for multi-part explorations
- See `/docs-components` Callout Spacing Rules
---
## Content Principles
### Intro Section
- Single non-wrapping opening line describing the API purpose:
- Hooks: `` `useHookName` is a React Hook that lets you [capability]. ``
- Other APIs: `` `apiName` lets you [capability]. ``
- Code signature showing usage with `?` for optional parameters:
```js
const [state, setState] = useState(initialState)
const cachedFn = useCallback(fn, dependencies)
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn?);
```
- **One sentence, ~15 words max** - State what the Hook does, not how it works
- ✅ "`useEffectEvent` is a React Hook that lets you separate events from Effects."
- ❌ "`useEffectEvent` is a React Hook that lets you extract non-reactive logic from your Effects into a reusable function called an Effect Event."
### Parameters Section
- Use bullet format: `* \`paramName\`: description`
- Mark optional params: `* **optional** \`paramName\`: description`
- Optional params in signature use `?`: `useOptimistic(state, updateFn?)`
### Reference Code Example
- Show just the API call (5-10 lines), not a full component
- Move full component examples to Usage section
### Returns Section
- Single return: prose description
- Multiple returns (like useState): use numbered list:
```
1. `state`: The current state value...
2. `setState`: A function to update the state...
```
### Usage Section Structure
1. **First example: Core mental model** - Show the canonical use case with simplest concrete example
2. **Subsequent examples: Canonical use cases** - Name the *why* (e.g., "Avoid reconnecting to external systems"), show a concrete *how*
- Prefer broad canonical use cases over multiple narrow concrete examples
- The section title IS the teaching - "When would I use this?" should be answered by the heading
### Code Examples
- Show import and 5-10 lines of practical usage
- Link to usage: `[See more examples below.](#usage)`
### What to Include vs. Exclude
- **Never** document past bugs or fixed issues
- **Include** edge cases most developers will encounter
- **Exclude** niche edge cases (e.g., `this` binding, rare class patterns)
## Tone
### Caveats Section
- Include rules the linter enforces or that cause immediate errors
- Include fundamental usage restrictions
- Exclude implementation details unless they affect usage
- Exclude repetition of things explained elsewhere
- Keep each caveat to one sentence when possible
Precise and technical: "Call `useState` at the top level...", "This Hook returns..."
### Troubleshooting Section
- Error headings only: "I'm getting an error: '[message]'" format
- Never document past bugs - if it's fixed, it doesn't belong here
- Focus on errors developers will actually encounter today
## Component Decision Tree
### DeepDive Content
- **Goldilocks principle** - Deep enough for curious developers, short enough to not overwhelm
- Answer "why is it designed this way?" - not exhaustive technical details
- Readers who skip it should miss nothing essential for using the API
- If the explanation is getting long, you're probably explaining too much
| When you need to... | Use |
|---------------------|-----|
| Warn about common mistakes that cause bugs | `<Pitfall>` |
| Clarify a convention or tip | `<Note>` |
| Explain optional deep technical details | `<DeepDive>` |
| Show multiple related variations | `<Recipes>` |
---
For component patterns, invoke `/docs-components`. For Sandpack patterns, invoke `/docs-sandpack`.
## Domain-Specific Guidance
### Hooks
**Returned function documentation:**
- Document setter/dispatch functions as separate `###` sections
- Use generic names: "set functions" not "setCount"
- Include stable identity caveat for returned functions
**Dependency array documentation:**
- List what counts as reactive values
- Explain when dependencies are ignored
- Link to removing effect dependencies guide
**Recipes usage:**
- Group related examples with meaningful titleText
- Each recipe has brief intro, Sandpack, and `<Solution />`
---
### Components
**Props documentation:**
- Use `#### Props` instead of `#### Parameters`
- Mark optional props with `**optional**` prefix
- Use `<CanaryBadge />` inline for canary-only props
**JSX syntax in titles/headings:**
- Frontmatter title: `title: <Suspense>`
- Reference heading: `` ### `<Suspense>` {/*suspense*/} ``
---
### React-DOM
**Common props linking:**
```md
`<input>` supports all [common element props.](/reference/react-dom/components/common#common-props)
```
**Props categorization:**
- Controlled vs uncontrolled props grouped separately
- Form-specific props documented with action patterns
- MDN links for standard HTML attributes
**Environment-specific notes:**
```mdx
<Note>
This API is specific to Node.js. Environments with [Web Streams](MDN-link), like Deno and modern edge runtimes, should use [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) instead.
</Note>
```
**Progressive enhancement:**
- Document benefits for users without JavaScript
- Explain Server Function + form action integration
- Show hidden form field and `.bind()` patterns
---
### RSC
**RSC banner (before Intro):**
Always place `<RSC>` component before `<Intro>` for Server Component-only APIs.
**Serialization type lists:**
When documenting Server Function arguments, list supported types:
```md
Supported types for Server Function arguments:
* Primitives
* [string](MDN-link)
* [number](MDN-link)
* Iterables containing serializable values
* [Array](MDN-link)
* [Map](MDN-link)
Notably, these are not supported:
* React elements, or [JSX](/learn/writing-markup-with-jsx)
* Functions (other than Server Functions)
```
**Bundle size comparisons:**
- Show "Not included in bundle" for server-only imports
- Annotate client bundle sizes with gzip: `// 35.9K (11.2K gzipped)`
---
### Compiler
**Configuration page structure:**
- Type (union type or interface)
- Default value
- Options/Valid values with descriptions
**Directive documentation:**
- Placement requirements are critical
- Mode interaction tables showing combinations
- "Use sparingly" + "Plan for removal" patterns for escape hatches
**Library author guides:**
- Audience-first intro
- Benefits/Why section
- Numbered step-by-step setup
---
### ESLint
**Rule Details section:**
- Explain "why" not just "what"
- Focus on React's underlying assumptions
- Describe consequences of violations
**Invalid/Valid sections:**
- Standard intro: "Examples of [in]correct code for this rule:"
- Use X emoji for invalid, checkmark for valid
- Show inline comments explaining the violation
**Configuration options:**
- Show shared settings (preferred)
- Show rule-level options (backward compatibility)
- Note precedence when both exist
---
## Edge Cases
For deprecated, canary, and version-specific component patterns (placement, syntax, examples), invoke `/docs-components`.
**Quick placement rules:**
- `<Deprecated>` after `<Intro>` for page-level, after heading for method-level
- `<Canary>` wrapper inline in Intro, `<CanaryBadge />` in headings/props/caveats
- Version notes use `<Note>` with "Starting in React 19..." pattern
**Removed APIs on index pages:**
```md
## Removed APIs {/*removed-apis*/}
These APIs were removed in React 19:
* [`render`](https://18.react.dev/reference/react-dom/render): use [`createRoot`](/reference/react-dom/client/createRoot) instead.
```
Link to previous version docs (18.react.dev) for removed API documentation.
---
## Critical Rules
1. **Heading IDs required:** `## Title {/*title-id*/}` (lowercase, hyphens)
2. **Capitalize React terms** when referring to the React concept (not general usage):
- Core: Hook, Effect, State, Context, Ref, Component, Fragment
- Concurrent: Transition, Action, Suspense
- Server: Server Component, Client Component, Server Function, Server Action
- Patterns: Error Boundary
- Canary: Activity, View Transition, Transition Type
- General usage stays lowercase: "the page transitions" (not React), "takes an action" (not React)
3. **DeepDive must start with `####` heading**
4. **Sandpack main file needs `export default`**
5. **Active file syntax:** ` ```js src/File.js active `
6. **Avoid:** "simple", "easy", "just", time estimates
7. **Error headings in Troubleshooting:** Use `### I'm getting an error: "[message]" {/*id*/}`
2. **Sandpack main file needs `export default`**
3. **Active file syntax:** ` ```js src/File.js active `
4. **Error headings in Troubleshooting:** Use `### I'm getting an error: "[message]" {/*id*/}`
5. **Section dividers (`---`)** required between headings (see Section Dividers below)
6. **InlineToc required:** Always include `<InlineToc />` after Intro
7. **Consistent parameter format:** Use `* \`paramName\`: description` with `**optional**` prefix for optional params
8. **Numbered lists for array returns:** When hooks return arrays, use numbered lists in Returns section
9. **Generic names for returned functions:** Use "set functions" not "setCount"
10. **Props vs Parameters:** Use `#### Props` for Components (Type B), `#### Parameters` for Hooks/APIs (Type A)
11. **RSC placement:** `<RSC>` component goes before `<Intro>`, not after
12. **Canary markers:** Use `<Canary>` wrapper inline in Intro, `<CanaryBadge />` in headings/props
13. **Deprecated placement:** `<Deprecated>` goes after `<Intro>` for page-level, after heading for method-level
14. **Code comment emojis:** Use X for wrong, checkmark for correct in code examples
15. **No consecutive Pitfalls/Notes:** Combine into one component with titled subsections, or separate with prose/code (see `/docs-components`)
For component heading level conventions (DeepDive, Pitfall, Note, Recipe headings), see `/docs-components`.
### Section Dividers
Use `---` horizontal rules to visually separate major sections:
- **After `<InlineToc />`** - Before `## Reference` heading
- **Between API subsections** - Between different function/hook definitions (e.g., between `useState()` and `set functions`)
- **Before `## Usage`** - Separates API reference from examples
- **Before `## Troubleshooting`** - Separates content from troubleshooting
- **Between EVERY Usage subsections** - When switching to a new major use case
Always have a blank line before and after `---`.
### Section ID Conventions
| Section | ID Format |
|---------|-----------|
| Main function | `{/*functionname*/}` |
| Returned function | `{/*setstate*/}`, `{/*dispatch*/}` |
| Sub-section of returned function | `{/*setstate-parameters*/}` |
| Troubleshooting item | `{/*problem-description-slug*/}` |
| Pitfall | `{/*pitfall-description*/}` |
| Deep dive | `{/*deep-dive-topic*/}` |

View File

@@ -0,0 +1,335 @@
---
name: react-expert
description: Use when researching React APIs or concepts for documentation. Use when you need authoritative usage examples, caveats, warnings, or errors for a React feature.
---
# React Expert Research Skill
## Overview
This skill produces exhaustive documentation research on any React API or concept by searching authoritative sources (tests, source code, PRs, issues) rather than relying on LLM training knowledge.
<CRITICAL>
**Skepticism Mandate:** You must be skeptical of your own knowledge. Claude is often trained on outdated or incorrect React patterns. Treat source material as the sole authority. If findings contradict your prior understanding, explicitly flag this discrepancy.
**Red Flags - STOP if you catch yourself thinking:**
- "I know this API does X" → Find source evidence first
- "Common pattern is Y" → Verify in test files
- Generating example code → Must have source file reference
</CRITICAL>
## Invocation
```
/react-expert useTransition
/react-expert suspense boundaries
/react-expert startTransition
```
## Sources (Priority Order)
1. **React Repo Tests** - Most authoritative for actual behavior
2. **React Source Code** - Warnings, errors, implementation details
3. **Git History** - Commit messages with context
4. **GitHub PRs & Comments** - Design rationale (via `gh` CLI)
5. **GitHub Issues** - Confusion/questions (facebook/react + reactjs/react.dev)
6. **React Working Group** - Design discussions for newer APIs
7. **Flow Types** - Source of truth for type signatures
8. **TypeScript Types** - Note discrepancies with Flow
9. **Current react.dev docs** - Baseline (not trusted as complete)
**No web search** - No Stack Overflow, blog posts, or web searches. GitHub API via `gh` CLI is allowed.
## Workflow
### Step 1: Setup React Repo
First, ensure the React repo is available locally:
```bash
# Check if React repo exists, clone or update
if [ -d ".claude/react" ]; then
cd .claude/react && git pull origin main
else
git clone --depth=100 https://github.com/facebook/react.git .claude/react
fi
```
Get the current commit hash for the research document:
```bash
cd .claude/react && git rev-parse --short HEAD
```
### Step 2: Dispatch 6 Parallel Research Agents
Spawn these agents IN PARALLEL using the Task tool. Each agent receives the skepticism preamble:
> "You are researching React's `<TOPIC>`. CRITICAL: Do NOT rely on your prior knowledge about this API. Your training may contain outdated or incorrect patterns. Only report what you find in the source files. If your findings contradict common understanding, explicitly highlight this discrepancy."
| Agent | subagent_type | Focus | Instructions |
|-------|---------------|-------|--------------|
| test-explorer | Explore | Test files for usage patterns | Search `.claude/react/packages/*/src/__tests__/` for test files mentioning the topic. Extract actual usage examples WITH file paths and line numbers. |
| source-explorer | Explore | Warnings/errors in source | Search `.claude/react/packages/*/src/` for console.error, console.warn, and error messages mentioning the topic. Document trigger conditions. |
| git-historian | Explore | Commit messages | Run `git log --all --grep="<topic>" --oneline -50` in `.claude/react`. Read full commit messages for context. |
| pr-researcher | Explore | PRs introducing/modifying API | Run `gh pr list -R facebook/react --search "<topic>" --state all --limit 20`. Read key PR descriptions and comments. |
| issue-hunter | Explore | Issues showing confusion | Search issues in both `facebook/react` and `reactjs/react.dev` repos. Look for common questions and misunderstandings. |
| types-inspector | Explore | Flow + TypeScript signatures | Find Flow types in `.claude/react/packages/*/src/*.js` (look for `@flow` annotations). Find TS types in `.claude/react/packages/*/index.d.ts`. Note discrepancies. |
### Step 3: Agent Prompts
Use these exact prompts when spawning agents:
#### test-explorer
```
You are researching React's <TOPIC>.
CRITICAL: Do NOT rely on your prior knowledge about this API. Your training may contain outdated or incorrect patterns. Only report what you find in the source files.
Your task: Find test files in .claude/react that demonstrate <TOPIC> usage.
1. Search for test files: Glob for `**/__tests__/**/*<topic>*` and `**/__tests__/**/*.js` then grep for <topic>
2. For each relevant test file, extract:
- The test description (describe/it blocks)
- The actual usage code
- Any assertions about behavior
- Edge cases being tested
3. Report findings with exact file paths and line numbers
Format your output as:
## Test File: <path>
### Test: "<test description>"
```javascript
<exact code from test>
```
**Behavior:** <what the test asserts>
```
#### source-explorer
```
You are researching React's <TOPIC>.
CRITICAL: Do NOT rely on your prior knowledge about this API. Only report what you find in the source files.
Your task: Find warnings, errors, and implementation details for <TOPIC>.
1. Search .claude/react/packages/*/src/ for:
- console.error mentions of <topic>
- console.warn mentions of <topic>
- Error messages mentioning <topic>
- The main implementation file
2. For each warning/error, document:
- The exact message text
- The condition that triggers it
- The source file and line number
Format your output as:
## Warnings & Errors
| Message | Trigger Condition | Source |
|---------|------------------|--------|
| "<exact message>" | <condition> | <file:line> |
## Implementation Notes
<key details from source code>
```
#### git-historian
```
You are researching React's <TOPIC>.
CRITICAL: Do NOT rely on your prior knowledge. Only report what you find in git history.
Your task: Find commit messages that explain <TOPIC> design decisions.
1. Run: cd .claude/react && git log --all --grep="<topic>" --oneline -50
2. For significant commits, read full message: git show <hash> --stat
3. Look for:
- Initial introduction of the API
- Bug fixes (reveal edge cases)
- Behavior changes
- Deprecation notices
Format your output as:
## Key Commits
### <short hash> - <subject>
**Date:** <date>
**Context:** <why this change was made>
**Impact:** <what behavior changed>
```
#### pr-researcher
```
You are researching React's <TOPIC>.
CRITICAL: Do NOT rely on your prior knowledge. Only report what you find in PRs.
Your task: Find PRs that introduced or modified <TOPIC>.
1. Run: gh pr list -R facebook/react --search "<topic>" --state all --limit 20 --json number,title,url
2. For promising PRs, read details: gh pr view <number> -R facebook/react
3. Look for:
- The original RFC/motivation
- Design discussions in comments
- Alternative approaches considered
- Breaking changes
Format your output as:
## Key PRs
### PR #<number>: <title>
**URL:** <url>
**Summary:** <what it introduced/changed>
**Design Rationale:** <why this approach>
**Discussion Highlights:** <key points from comments>
```
#### issue-hunter
```
You are researching React's <TOPIC>.
CRITICAL: Do NOT rely on your prior knowledge. Only report what you find in issues.
Your task: Find issues that reveal common confusion about <TOPIC>.
1. Search facebook/react: gh issue list -R facebook/react --search "<topic>" --state all --limit 20 --json number,title,url
2. Search reactjs/react.dev: gh issue list -R reactjs/react.dev --search "<topic>" --state all --limit 20 --json number,title,url
3. For each issue, identify:
- What the user was confused about
- What the resolution was
- Any gotchas revealed
Format your output as:
## Common Confusion
### Issue #<number>: <title>
**Repo:** <facebook/react or reactjs/react.dev>
**Confusion:** <what they misunderstood>
**Resolution:** <correct understanding>
**Gotcha:** <if applicable>
```
#### types-inspector
```
You are researching React's <TOPIC>.
CRITICAL: Do NOT rely on your prior knowledge. Only report what you find in type definitions.
Your task: Find and compare Flow and TypeScript type signatures for <TOPIC>.
1. Flow types (source of truth): Search .claude/react/packages/*/src/*.js for @flow annotations related to <topic>
2. TypeScript types: Search .claude/react/packages/*/index.d.ts and @types/react
3. Compare and note any discrepancies
Format your output as:
## Flow Types (Source of Truth)
**File:** <path>
```flow
<exact type definition>
```
## TypeScript Types
**File:** <path>
```typescript
<exact type definition>
```
## Discrepancies
<any differences between Flow and TS definitions>
```
### Step 4: Synthesize Results
After all agents complete, combine their findings into a single research document.
**DO NOT add information from your own knowledge.** Only include what agents found in sources.
### Step 5: Save Output
Write the final document to `.claude/research/<topic>.md`
Replace spaces in topic with hyphens (e.g., "suspense boundaries" → "suspense-boundaries.md")
## Output Document Template
```markdown
# React Research: <topic>
> Generated by /react-expert on YYYY-MM-DD
> Sources: React repo (commit <hash>), N PRs, M issues
## Summary
[Brief summary based SOLELY on source findings, not prior knowledge]
## API Signature
### Flow Types (Source of Truth)
[From types-inspector agent]
### TypeScript Types
[From types-inspector agent]
### Discrepancies
[Any differences between Flow and TS]
## Usage Examples
### From Tests
[From test-explorer agent - with file:line references]
### From PRs/Issues
[Real-world patterns from discussions]
## Caveats & Gotchas
[Each with source link]
- **<gotcha>** - Source: <link>
## Warnings & Errors
| Message | Trigger Condition | Source File |
|---------|------------------|-------------|
[From source-explorer agent]
## Common Confusion
[From issue-hunter agent]
## Design Decisions
[From git-historian and pr-researcher agents]
## Source Links
### Commits
- <hash>: <description>
### Pull Requests
- PR #<number>: <title> - <url>
### Issues
- Issue #<number>: <title> - <url>
```
## Common Mistakes to Avoid
1. **Trusting prior knowledge** - If you "know" something about the API, find the source evidence anyway
2. **Generating example code** - Every code example must come from an actual source file
3. **Skipping agents** - All 6 agents must run; each provides unique perspective
4. **Summarizing without sources** - Every claim needs a file:line or PR/issue reference
5. **Using web search** - No Stack Overflow, no blog posts, no social media
## Verification Checklist
Before finalizing the research document:
- [ ] React repo is at `.claude/react` with known commit hash
- [ ] All 6 agents were spawned in parallel
- [ ] Every code example has a source file reference
- [ ] Warnings/errors table has source locations
- [ ] No claims made without source evidence
- [ ] Discrepancies between Flow/TS types documented
- [ ] Source links section is complete

View File

@@ -0,0 +1,20 @@
---
name: review-docs
description: Use when reviewing React documentation for structure, components, and style compliance
---
CRITICAL: do not load these skills yourself.
Run these tasks in parallel for the given file(s). Each agent checks different aspects—not all apply to every file:
- [ ] Ask docs-reviewer agent to review {files} with docs-writer-learn (only for files in src/content/learn/).
- [ ] Ask docs-reviewer agent to review {files} with docs-writer-reference (only for files in src/content/reference/).
- [ ] Ask docs-reviewer agent to review {files} with docs-writer-blog (only for files in src/content/blog/).
- [ ] Ask docs-reviewer agent to review {files} with docs-voice (all documentation files).
- [ ] Ask docs-reviewer agent to review {files} with docs-components (all documentation files).
- [ ] Ask docs-reviewer agent to review {files} with docs-sandpack (files containing Sandpack examples).
If no file is specified, check git status for modified MDX files in `src/content/`.
The docs-reviewer will return a checklist of the issues it found. Respond with the full checklist and line numbers from all agents, and prompt the user to create a plan to fix these issues.

View File

@@ -1,3 +1,4 @@
scripts
plugins
next.config.js
.claude/

1
.gitignore vendored
View File

@@ -42,3 +42,4 @@ public/rss.xml
# claude local settings
.claude/*.local.*
.claude/react/