diff --git a/.claude/agents/docs-reviewer.md b/.claude/agents/docs-reviewer.md new file mode 100644 index 00000000..af0a856e --- /dev/null +++ b/.claude/agents/docs-reviewer.md @@ -0,0 +1,28 @@ +--- +name: docs-reviewer +description: "Lean docs reviewer that dispatches reviews docs for a particular skill." +model: opus +color: cyan +--- + +You are a direct, critical, expert reviewer for React documentation. + +Your role is to use given skills to validate given doc pages for consistency, correctness, and adherence to established patterns. + +Complete this process: + +## 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. + +## Phase 2: Validate + +1. Read the docs files given. +2. Review each file with the task list to verify. + +## Phase 3: Respond + +You must respond with a checklist of the issues you identified, and line number. + +DO NOT respond with passed validations, ONLY respond with the problems. diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..4648ad90 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,31 @@ +{ + "skills": { + "suggest": [ + { + "pattern": "src/content/learn/**/*.md", + "skill": "docs-writer-learn" + }, + { + "pattern": "src/content/reference/**/*.md", + "skill": "docs-writer-reference" + } + ] + }, + "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:*)", + "Bash(yarn tsc:*)", + "Bash(yarn check-all:*)", + "Bash(yarn fix-headings:*)", + "Bash(yarn deadlinks:*)", + "Bash(yarn prettier:diff:*)" + ] + } +} diff --git a/.claude/skills/docs-components/SKILL.md b/.claude/skills/docs-components/SKILL.md new file mode 100644 index 00000000..4b75f27a --- /dev/null +++ b/.claude/skills/docs-components/SKILL.md @@ -0,0 +1,518 @@ +--- +name: docs-components +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 + +## Quick Reference + +### Component Decision Tree + +| Need | Component | +|------|-----------| +| Helpful tip or terminology | `` | +| Common mistake warning | `` | +| Advanced technical explanation | `` | +| Canary-only feature | `` or `` | +| Server Components only | `` | +| Deprecated API | `` | +| Experimental/WIP | `` | +| Visual diagram | `` | +| Multiple related examples | `` | +| Interactive code | `` (see `/docs-sandpack`) | +| Console error display | `` | +| End-of-page exercises | `` (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:** +- `` followed by `` - Combine into one with titled subsections, or separate with prose +- `` followed by `` - Combine into one, or separate with prose + +**Allowed consecutive patterns:** +- `` followed by `` - OK for multi-part explorations (see useMemo.md) +- `` followed by `` - 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 + +Don't do X. + + + +Don't do Y. + +``` + +**Correct - combined:** +```mdx + + +##### Don't do X {/*pitfall-x*/} +Explanation. + +##### Don't do Y {/*pitfall-y*/} +Explanation. + + +``` + +**Correct - separated:** +```mdx + +Don't do X. + + +This leads to another common mistake: + + +Don't do Y. + +``` + +--- + +## `` + +Important clarifications, conventions, or tips. Less severe than Pitfall. + +### Simple Note + +```mdx + + +The optimization of caching return values is known as [_memoization_](https://en.wikipedia.org/wiki/Memoization). + + +``` + +### Note with Title + +Use `####` (h4) heading with an ID. + +```mdx + + +#### 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. + + +``` + +### Version-Specific Note + +```mdx + + +Starting in React 19, you can render `` as a provider. + +In older versions of React, use ``. + + +``` + +--- + +## `` + +Common mistakes that cause bugs. Use for errors readers will likely make. + +### Simple Pitfall + +```mdx + + +We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives) + + +``` + +### Titled Pitfall + +Use `#####` (h5) heading with an ID. + +```mdx + + +##### 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 with Wrong/Right Code + +```mdx + + +##### `useFormStatus` will not return status information for a `
` rendered in the same component. {/*pitfall-same-component*/} + +```js +function Form() { + // πŸ”΄ `pending` will never be true + const { pending } = useFormStatus(); + return
; +} +``` + +Instead call `useFormStatus` from inside a component located inside `
`. + + +``` + +--- + +## `` + +Optional deep technical content. **First child must be `####` heading with ID.** + +### Standard DeepDive + +```mdx + + +#### Is using an updater always preferred? {/*is-updater-preferred*/} + +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. + + +``` + +### Comparison DeepDive + +For comparing related concepts: + +```mdx + + +#### 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. + + +``` + +--- + +## `` + +Multiple related examples showing variations. Each recipe needs ``. + +```mdx + + +#### Counter (number) {/*counter-number*/} + +In this example, the `count` state variable holds a number. + + +{/* code */} + + + + +#### Text field (string) {/*text-field-string*/} + +In this example, the `text` state variable holds a string. + + +{/* code */} + + + + + +``` + +**Common titleText/titleId combinations:** +- "Basic [hookName] examples" / `examples-basic` +- "Examples of [concept]" / `examples-[concept]` +- "The difference between [A] and [B]" / `examples-[topic]` + +--- + +## `` + +End-of-page exercises. **Learn pages only.** Each challenge needs problem + solution Sandpack. + +```mdx + + +#### Fix the bug {/*fix-the-bug*/} + +Problem description... + + +Optional hint text. + + + +{/* problem code */} + + + + +Explanation... + + +{/* solution code */} + + + + + +``` + +**Guidelines:** +- Only at end of standard Learn pages +- No Challenges in chapter intros or tutorials +- Each challenge has `####` heading with ID + +--- + +## `` + +For deprecated APIs. Content should explain what to use instead. + +### Page-Level Deprecation + +```mdx + + +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). + + +``` + +### Method-Level Deprecation + +```mdx +### `componentWillMount()` {/*componentwillmount*/} + + + +This API has been renamed from `componentWillMount` to [`UNSAFE_componentWillMount`.](#unsafe_componentwillmount) + +Run the [`rename-unsafe-lifecycles` codemod](codemod-link) to automatically update. + + +``` + +--- + +## `` + +For APIs that only work with React Server Components. + +### Basic RSC + +```mdx + + +`cache` is only for use with [React Server Components](/reference/rsc/server-components). + + +``` + +### Extended RSC (for Server Functions) + +```mdx + + +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". + + +``` + +--- + +## `` and `` + +For features only available in Canary releases. + +### Canary Wrapper (inline in Intro) + +```mdx + + +`` lets you group elements without a wrapper node. + +Fragments can also accept refs, enabling interaction with underlying DOM nodes. + + +``` + +### CanaryBadge in Section Headings + +```mdx +### FragmentInstance {/*fragmentinstance*/} +``` + +### CanaryBadge in Props Lists + +```mdx +* **optional** `ref`: A ref object from `useRef` or callback function. +``` + +### CanaryBadge in Caveats + +```mdx +* If you want to pass `ref` to a Fragment, you can't use the `<>...` syntax. +``` + +--- + +## `` + +Visual explanations of module dependencies, render trees, or data flow. + +```mdx + +`'use client'` segments the module dependency tree, marking `InspirationGenerator.js` and all dependencies as client-rendered. + +``` + +**Attributes:** +- `name`: Diagram identifier (used for image file) +- `height`: Height in pixels +- `width`: Width in pixels +- `alt`: Accessible description of the diagram + +--- + +## `` (Use Sparingly) + +Numbered callouts in prose. Pairs with code block annotations. + +### 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 current state initially set to the initial value. +2. The `set` function 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 +React will compare the dependencies with the dependencies you passed... +``` + +🚫 **Avoid** - excessive highlighting: +```mdx +When an Activity boundary is hidden during its initial render... +``` + +--- + +## `` + +Display console output (errors, warnings, logs). + +```mdx + +Uncaught Error: Too many re-renders. + +``` + +**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: +- `` goes before `` at top of page +- `` goes after `` for page-level deprecation +- `` goes after method heading for method-level deprecation +- `` wrapper goes inline within `` +- `` 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:** ``, ``, ``, ``, `` + +**Visuals:** ``, ``, ``, ``, `` + +**Console:** ``, `` + +**Specialized:** ``, ``, ``, ``, ``, ``, ``, ``, `` + +See existing docs for usage examples of these components. diff --git a/.claude/skills/docs-sandpack/SKILL.md b/.claude/skills/docs-sandpack/SKILL.md new file mode 100644 index 00000000..0904a98c --- /dev/null +++ b/.claude/skills/docs-sandpack/SKILL.md @@ -0,0 +1,447 @@ +--- +name: docs-sandpack +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 + + +` ` `js +import { useState } from 'react'; + +export default function Example() { + const [value, setValue] = useState(0); + + return ( + + ); +} +` ` ` + + +``` + +--- + +## File Naming + +| Pattern | Usage | +|---------|-------| +| ` ```js ` | Main file (no prefix) | +| ` ```js src/FileName.js ` | Supporting files | +| ` ```js src/File.js active ` | Active file (reference pages) | +| ` ```js src/data.js hidden ` | Hidden files | +| ` ```css ` | CSS styles | +| ` ```json package.json ` | External dependencies | + +**Critical:** Main file must have `export default`. + +## Line Highlighting + +```mdx +```js {2-4} +function Example() { + // Lines 2-4 + // will be + // highlighted + return null; +} +``` + +## Code References (numbered callouts) + +```mdx +```js [[1, 4, "age"], [2, 4, "setAge"]] +// Creates numbered markers pointing to "age" and "setAge" on line 4 +``` + +## Expected Errors (intentionally broken examples) + +```mdx +```js {expectedErrors: {'react-compiler': [7]}} +// Line 7 shows as expected error +``` + +## Multi-File Example + +```mdx + + +```js src/App.js +import Gallery from './Gallery.js'; + +export default function App() { + return ; +} +``` + +```js src/Gallery.js +export default function Gallery() { + return

Gallery

; +} +``` + +```css +h1 { color: purple; } +``` + + +``` + +## External Dependencies + +```mdx + + +```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" + } +} +``` + + +``` + +## Code Style in Sandpack (Required) + +Sandpack examples are held to strict code style standards: + +1. **Function declarations** for components (not arrows) +2. **`e`** for event parameters +3. **Single quotes** in JSX +4. **`const`** unless reassignment needed +5. **Spaces in destructuring**: `({ props })` not `({props})` +6. **Two-line createRoot**: separate declaration and render call +7. **Multiline if statements**: always use braces + +### Don't Create Hydration Mismatches + +Sandpack examples must produce the same output on server and client: + +```js +// 🚫 This will cause hydration warnings +export default function App() { + const isClient = typeof window !== 'undefined'; + return
{isClient ? 'Client' : 'Server'}
; +} +``` + +### Use Ref for Non-Rendered State + +```js +// 🚫 Don't trigger re-renders for non-visual state +const [mounted, setMounted] = useState(false); +useEffect(() => { setMounted(true); }, []); + +// βœ… Use ref instead +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 ; +}); + +// 🚫 Anonymous loses name +const MyInput = forwardRef((props, ref) => { ... }); +``` + +### memo - Use Named Function +```js +// βœ… Preserves component name +const Greeting = memo(function Greeting({ name }) { + return

Hello, {name}

; +}); +``` + +## 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 +```js +// βœ… Correct +{items.map(item =>
  • {item.name}
  • )} + +// 🚫 Wrong - missing key +{items.map(item =>
  • {item.name}
  • )} +``` + +### Use Realistic Import Paths +```js +// βœ… Correct - descriptive path +import { fetchData } from './your-data-layer'; + +// 🚫 Wrong - looks like a real npm package +import { fetchData } from 'cool-data-lib'; +``` + +### Console.log Labels +```js +// βœ… Correct - labeled for clarity +console.log('User:', user); +console.log('Component Stack:', errorInfo.componentStack); + +// 🚫 Wrong - unlabeled +console.log(user); +``` + +### Keep Delays Reasonable +```js +// βœ… Correct - 1-1.5 seconds +setTimeout(() => setLoading(false), 1000); + +// 🚫 Wrong - too long, feels sluggish +setTimeout(() => setLoading(false), 3000); +``` + +## Updating Line Highlights + +When modifying code in examples with line highlights (`{2-4}`), **always update the highlight line numbers** to match the new code. Incorrect line numbers cause rendering crashes. + +## File Name Conventions + +- 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 + +### Package.json Rules + +**Include package.json when:** +- Using external npm packages (immer, remarkable, leaflet, toastify-js, etc.) +- Demonstrating experimental/canary React features +- Requiring specific React versions (`react: beta`, `react: 19.0.0-rc-*`) + +**Omit package.json when:** +- Example uses only built-in React features +- No external dependencies needed +- Teaching basic hooks, state, or components + +**Always mark package.json as hidden:** +```mdx +```json package.json hidden +{ + "dependencies": { + "react": "latest", + "react-dom": "latest", + "react-scripts": "latest", + "immer": "1.7.3" + } +} +``` +``` + +**Version conventions:** +- Use `"latest"` for stable features +- Use exact versions only when compatibility requires it +- Include minimal dependencies (just what the example needs) + +### Hidden File Patterns + +**Always hide these file types:** + +| File Type | Reason | +|-----------|--------| +| `package.json` | Configuration not the teaching point | +| `sandbox.config.json` | Sandbox setup is boilerplate | +| `public/index.html` | HTML structure not the focus | +| `src/data.js` | When it contains sample/mock data | +| `src/api.js` | When showing API usage, not implementation | +| `src/styles.css` | When styling is not the lesson | +| `src/router.js` | Supporting infrastructure | +| `src/actions.js` | Server action implementation details | + +**Rationale:** +- Reduces cognitive load +- Keeps focus on the primary concept +- Creates cleaner, more focused examples + +**Example:** +```mdx +```js src/data.js hidden +export const items = [ + { id: 1, name: 'Item 1' }, + { id: 2, name: 'Item 2' }, +]; +``` +``` + +### Active File Patterns + +**Mark as active when:** +- File contains the primary teaching concept +- Learner should focus on this code first +- Component demonstrates the hook/pattern being taught + +**Effect of the `active` marker:** +- Sets initial editor tab focus when Sandpack loads +- Signals "this is what you should study" +- Works with hidden files to create focused examples + +**Most common active file:** `src/index.js` or `src/App.js` + +**Example:** +```mdx +```js src/App.js active +// This file will be focused when example loads +export default function App() { + // ... +} +``` +``` + +### File Structure Guidelines + +| Scenario | Structure | Reason | +|----------|-----------|--------| +| Basic hook usage | Single file | Simple, focused | +| Teaching imports | 2-3 files | Shows modularity | +| Context patterns | 4-5 files | Realistic structure | +| Complex state | 3+ files | Separation of concerns | + +**Single File Examples (70% of cases):** +- Use for simple concepts +- 50-200 lines typical +- Best for: Counter, text inputs, basic hooks + +**Multi-File Examples (30% of cases):** +- Use when teaching modularity/imports +- Use for context patterns (4-5 files) +- Use when component is reused + +**File Naming:** +- Main component: `App.js` (capitalized) +- Component files: `Gallery.js`, `Button.js` (capitalized) +- Data files: `data.js` (lowercase) +- Utility files: `utils.js` (lowercase) +- Context files: `TasksContext.js` (named after what they provide) + +### Code Size Limits + +- Single file: **<200 lines** +- Multi-file total: **150-300 lines** +- Main component: **100-150 lines** +- Supporting files: **20-40 lines each** + +### CSS Guidelines + +**Always:** +- Include minimal CSS for demo interactivity +- Use semantic class names (`.panel`, `.button-primary`, `.panel-dark`) +- Support light/dark themes when showing UI concepts +- Keep CSS visible (never hidden) + +**Size Guidelines:** +- Minimal (5-10 lines): Basic button styling, spacing +- Medium (15-30 lines): Panel styling, form layouts +- Complex (40+ lines): Only for layout-focused examples diff --git a/.claude/skills/docs-voice/SKILL.md b/.claude/skills/docs-voice/SKILL.md new file mode 100644 index 00000000..124e5f04 --- /dev/null +++ b/.claude/skills/docs-voice/SKILL.md @@ -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`, `` +- **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 `` as a provider: +\`\`\`js +{children} +\`\`\` + +In older versions: +\`\`\`js +{children} +\`\`\` +``` + +Patterns: +- "Starting in React 19..." for new APIs +- "In older versions of React..." for legacy patterns diff --git a/.claude/skills/docs-writer-blog/SKILL.md b/.claude/skills/docs-writer-blog/SKILL.md new file mode 100644 index 00000000..ef28225f --- /dev/null +++ b/.claude/skills/docs-writer-blog/SKILL.md @@ -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. **`` 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) + +--- + + + +React vX.Y is now available on npm! + + + +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) + +--- + + + +[Summary of upgrade and what this guide covers.] + + + + + +#### Stepping stone version {/*stepping-stone*/} + +[If applicable, describe intermediate upgrade steps.] + + + +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*/} + + + +#### Run all React [VERSION] codemods {/*run-all-codemods*/} + +```bash +npx codemod@latest react/[VERSION]/migration-recipe +``` + + + +## 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] +``` + + + +Codemod [description]: + +```bash +npx codemod@latest react/[VERSION]/codemod-name +``` + + + +## 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) + +--- + + + +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. + + + +[Optional: Roadmap disclaimer about timelines] + +--- + +## Feature Name {/*feature-name*/} + + + +`` is now available in React's Canary channel. + + + +[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) + +--- + + + +Last week we hosted React Conf [YEAR] [where we announced [key announcements]]. + + + +--- + +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: + + + +## Day 2 {/*day-2*/} + +_[Watch the full day 2 stream here.](youtube-url)_ + +[Day 2 summary.] + + + +## 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) + +--- + + + +Today we are [excited/thrilled] to announce [feature]. [What this means for users.] + + + +--- + +## 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]: + + +npm install package-name + + +[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) + +--- + + + +[One or two sentences summarizing the vulnerability.] + +We recommend upgrading immediately. + + + +--- + +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*/}` | +| Removed API | `#### Removed: \`propTypes\` {/*removed-proptypes*/}` | +| tl;dr section | `## tl;dr {/*tldr*/}` | + +--- + +## Component Usage Guide + +### Blog-Appropriate Components + +| Component | Usage in Blog | +|-----------|---------------| +| `` | **Required** - Opening summary after byline | +| `` | Callouts, caveats, important clarifications | +| `` | Warnings about common mistakes | +| `` | Optional technical deep dives (use sparingly) | +| `` | CLI/installation commands | +| `` | Console error/warning output | +| `` | Multi-line console output | +| `` | Conference video embeds | +| `` | Visual explanations | +| `` | Auto-generated table of contents | + +### `` Pattern + +Always wrap opening paragraph: + +```markdown + + +React 19 is now available on npm! + + +``` + +### `` Patterns + +**Simple note:** +```markdown + + +For React Native users, React 18 ships with the New Architecture. + + +``` + +**Titled note (H4 inside):** +```markdown + + +#### React 18.3 has also been published {/*react-18-3*/} + +To help with the upgrade, we've published `react@18.3`... + + +``` + +### `` Pattern + +```markdown + +npm install react@latest react-dom@latest + +``` + +### `` Pattern + +```markdown + +``` + +--- + +## 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 + + +[Updated content] + +----- + +_Updated January 26, 2026._ + + +``` + +--- + +## 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 `` 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 + + + [Updated information] + + ----- + + _Updated Month Year._ + + + ``` + +--- + +## Critical Rules + +1. **Heading IDs required:** `## Title {/*title-id*/}` +2. **`` required:** Every post starts with `` 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: ``, ``, ``, ``, ``, ``, ``, ``. + +Prefer inline explanations over heavy component usage. diff --git a/.claude/skills/docs-writer-learn/SKILL.md b/.claude/skills/docs-writer-learn/SKILL.md new file mode 100644 index 00000000..57dc9ef7 --- /dev/null +++ b/.claude/skills/docs-writer-learn/SKILL.md @@ -0,0 +1,299 @@ +--- +name: docs-writer-learn +description: Use when writing or editing files in src/content/learn/. Provides Learn page structure and tone. +--- + +# Learn Page Writer + +## 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: Page Title +--- + + +1-3 sentences introducing the concept. Use *italics* for new terms. + + + + +* Learning outcome 1 +* Learning outcome 2 +* Learning outcome 3-5 + + + +## Section Name {/*section-id*/} + +Content with Sandpack examples, Pitfalls, Notes, DeepDives... + +## Another Section {/*another-section*/} + +More content... + + + +* Summary point 1 +* Summary point 2 +* Summary points 3-9 + + + + + +#### Challenge title {/*challenge-id*/} + +Description... + + +Optional guidance (single paragraph) + + + +{/* Starting code */} + + + +Explanation... + + +{/* Fixed code */} + + + + +``` + +### 2. Chapter Introduction Page + +For pages that introduce a chapter (like describing-the-ui.md, managing-state.md): + +```mdx + + +* [Sub-page title](/learn/sub-page-name) to learn... +* [Another page](/learn/another-page) to learn... + + + +## Preview Section {/*section-id*/} + +Preview description with mini Sandpack example + + + +Read **[Page Title](/learn/sub-page-name)** to learn how to... + + + +## 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 `` or `` sections. + +### 3. Tutorial Page + +For step-by-step tutorials (like tutorial-tic-tac-toe.md): + +```mdx + +Brief statement of what will be built + + + +Alternative learning path offered + + +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 + + +* [Link to section](#section-anchor) +* [Link to another section](#another-section) + + + +## 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 ``. +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. `` - First after frontmatter +2. `` - After Intro (standard/chapter pages) +3. Body content with ``, ``, `` placed contextually +4. `` - Before Challenges (standard pages only) +5. `` - 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. **All headings require IDs:** `## Title {/*title-id*/}` +2. **Chapter intros use `isChapter={true}` and ``** +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`. diff --git a/.claude/skills/docs-writer-reference/SKILL.md b/.claude/skills/docs-writer-reference/SKILL.md new file mode 100644 index 00000000..e63c00fc --- /dev/null +++ b/.claude/skills/docs-writer-reference/SKILL.md @@ -0,0 +1,885 @@ +--- +name: docs-writer-reference +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 + +## Quick Reference + +### Page Type Decision Tree + +1. Is it a Hook? Use **Type A (Hook/Function)** +2. Is it a React component (``)? 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 +--- +title: hookName +--- + + + +`hookName` is a React Hook that lets you [brief description]. + +```js +const result = hookName(arg) +``` + + + + + +--- + +## Reference {/*reference*/} + +### `hookName(arg)` {/*hookname*/} + +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. + +#### Returns {/*returns*/} +Description of return value. + +#### Caveats {/*caveats*/} +* Important caveat about usage. + +--- + +## Usage {/*usage*/} + +### Common Use Case {/*common-use-case*/} +Explanation with Sandpack examples... + +--- + +## Troubleshooting {/*troubleshooting*/} + +### Common Problem {/*common-problem*/} +How to solve it... +``` + +--- + +### Type B: Component + +**When to use:** Documenting React components (Suspense, Fragment, Activity, StrictMode) + +```mdx +--- +title: +--- + + + +`` lets you [primary action]. + +```js + + + +``` + + + + + +--- + +## Reference {/*reference*/} + +### `` {/*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: `` +- Uses `#### Props` instead of `#### Parameters` +- Reference heading uses JSX: `` ### `` `` + +--- + +### Type C: Configuration + +**When to use:** Documenting React Compiler configuration options + +```mdx +--- +title: optionName +--- + + + +The `optionName` option [controls/specifies/determines] [what it does]. + + + +```js +{ + optionName: 'value' // Quick example +} +``` + + + +--- + +## 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" +--- + + + +`'use directive'` is for use with [React Server Components](/reference/rsc/server-components). + + + + + +`'use directive'` marks [what it marks] for [purpose]. + +```js {1} +function MyComponent() { + 'use directive'; + // ... +} +``` + + + + + +--- + +## 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 +- `` block appears before `` +- Caveats focus on placement and syntax requirements + +--- + +### Type E: ESLint Rule + +**When to use:** Documenting ESLint plugin rules + +```mdx +--- +title: rule-name +--- + + +Validates that [what the rule checks]. + + +## 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]" +--- + + + +*Concept* let you [purpose]. Brief scope statement. + + + +--- + +## 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 | `` `` lets you [action]. `` | "`` 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 +* 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:** +- `` goes before `` at top of page +- `` goes after `` for page-level deprecation +- `` goes after method heading for method-level deprecation +- `` wrapper goes inline within `` +- `` 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 +- **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." + +### Reference Code Example +- Show just the API call (5-10 lines), not a full component +- Move full component examples to Usage section + +### 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 + +### 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) + +### 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 + +### 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 + +### 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 + +--- + +## 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 `` + +--- + +### Components + +**Props documentation:** +- Use `#### Props` instead of `#### Parameters` +- Mark optional props with `**optional**` prefix +- Use `` inline for canary-only props + +**JSX syntax in titles/headings:** +- Frontmatter title: `title: ` +- Reference heading: `` ### `` {/*suspense*/} `` + +--- + +### React-DOM + +**Common props linking:** +```md +`` 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 + + +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. + + +``` + +**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 `` component before `` 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:** +- `` after `` for page-level, after heading for method-level +- `` wrapper inline in Intro, `` in headings/props/caveats +- Version notes use `` 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. **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 `` 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:** `` component goes before ``, not after +12. **Canary markers:** Use `` wrapper inline in Intro, `` in headings/props +13. **Deprecated placement:** `` goes after `` 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 ``** - 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*/}` | diff --git a/.claude/skills/react-expert/SKILL.md b/.claude/skills/react-expert/SKILL.md new file mode 100644 index 00000000..5ebcdee3 --- /dev/null +++ b/.claude/skills/react-expert/SKILL.md @@ -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. + + +**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 + + +## 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 ``. 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="" --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 "" --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 . + +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 usage. + +1. Search for test files: Glob for `**/__tests__/**/**` and `**/__tests__/**/*.js` then grep for +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: +### Test: "" +```javascript + +``` +**Behavior:** +``` + +#### source-explorer +``` +You are researching React's . + +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 . + +1. Search .claude/react/packages/*/src/ for: + - console.error mentions of + - console.warn mentions of + - Error messages mentioning + - 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 | +|---------|------------------|--------| +| "" | | | + +## Implementation Notes + +``` + +#### git-historian +``` +You are researching React's . + +CRITICAL: Do NOT rely on your prior knowledge. Only report what you find in git history. + +Your task: Find commit messages that explain design decisions. + +1. Run: cd .claude/react && git log --all --grep="" --oneline -50 +2. For significant commits, read full message: git show --stat +3. Look for: + - Initial introduction of the API + - Bug fixes (reveal edge cases) + - Behavior changes + - Deprecation notices + +Format your output as: +## Key Commits +### - +**Date:** +**Context:** +**Impact:** +``` + +#### pr-researcher +``` +You are researching React's . + +CRITICAL: Do NOT rely on your prior knowledge. Only report what you find in PRs. + +Your task: Find PRs that introduced or modified . + +1. Run: gh pr list -R facebook/react --search "" --state all --limit 20 --json number,title,url +2. For promising PRs, read details: gh pr view -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 #: +**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 diff --git a/.claude/skills/review-docs/SKILL.md b/.claude/skills/review-docs/SKILL.md new file mode 100644 index 00000000..61a6a0e0 --- /dev/null +++ b/.claude/skills/review-docs/SKILL.md @@ -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. + + diff --git a/.eslintignore b/.eslintignore index 4738cb69..3c83df82 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ scripts plugins next.config.js +.claude/ diff --git a/.gitignore b/.gitignore index 99f4615e..ff88094d 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,7 @@ public/fonts/**/Optimistic_*.woff2 # rss public/rss.xml + +# claude local settings +.claude/*.local.* +.claude/react/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..3a081e6d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,52 @@ +# CLAUDE.md + +This file provides guidance to Claude Code when working with this repository. + +## Project Overview + +This is the React documentation website (react.dev), built with Next.js 15.1.11 and React 19. Documentation is written in MDX format. + +## Development Commands + +```bash +yarn build # Production build +yarn lint # Run ESLint +yarn lint:fix # Auto-fix lint issues +yarn tsc # TypeScript type checking +yarn check-all # Run prettier, lint:fix, tsc, and rss together +``` + +## Project Structure + +``` +src/ +β”œβ”€β”€ content/ # Documentation content (MDX files) +β”‚ β”œβ”€β”€ learn/ # Tutorial/learning content +β”‚ β”œβ”€β”€ reference/ # API reference docs +β”‚ β”œβ”€β”€ blog/ # Blog posts +β”‚ └── community/ # Community pages +β”œβ”€β”€ components/ # React components +β”œβ”€β”€ pages/ # Next.js pages +β”œβ”€β”€ hooks/ # Custom React hooks +β”œβ”€β”€ utils/ # Utility functions +└── styles/ # CSS/Tailwind styles +``` + +## Code Conventions + +### TypeScript/React +- Functional components only +- Tailwind CSS for styling + +### Documentation Style + +When editing files in `src/content/`, the appropriate skill will be auto-suggested: +- `src/content/learn/` - Learn page structure and tone +- `src/content/reference/` - Reference page structure and tone + +For MDX components (DeepDive, Pitfall, Note, etc.), invoke `/docs-components`. +For Sandpack code examples, invoke `/docs-sandpack`. + +See `.claude/docs/react-docs-patterns.md` for comprehensive style guidelines. + +Prettier is used for formatting (config in `.prettierrc`). diff --git a/next.config.js b/next.config.js index fe88a09a..f8ec196e 100644 --- a/next.config.js +++ b/next.config.js @@ -19,6 +19,30 @@ const nextConfig = { scrollRestoration: true, reactCompiler: true, }, + async rewrites() { + return { + beforeFiles: [ + // Serve markdown when Accept header prefers text/markdown + // Useful for LLM agents - https://www.skeptrune.com/posts/use-the-accept-header-to-serve-markdown-instead-of-html-to-llms/ + { + source: '/:path((?!llms.txt).*)', + has: [ + { + type: 'header', + key: 'accept', + value: '(.*text/markdown.*)', + }, + ], + destination: '/api/md/:path*', + }, + // Explicit .md extension also serves markdown + { + source: '/:path*.md', + destination: '/api/md/:path*', + }, + ], + }; + }, env: {}, webpack: (config, {dev, isServer, ...options}) => { if (process.env.ANALYZE) { diff --git a/package.json b/package.json index 55fcc0a5..8cb25773 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "classnames": "^2.2.6", "debounce": "^1.2.1", "github-slugger": "^1.3.0", - "next": "15.1.11", + "next": "15.1.12", "next-remote-watch": "^1.0.0", "parse-numeric-range": "^1.2.0", "react": "^19.0.0", diff --git a/src/components/Layout/Feedback.tsx b/src/components/Layout/Feedback.tsx deleted file mode 100644 index fe927251..00000000 --- a/src/components/Layout/Feedback.tsx +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/* - * Copyright (c) Facebook, Inc. and its affiliates. - */ - -import {useState} from 'react'; -import {useRouter} from 'next/router'; -import cn from 'classnames'; - -export function Feedback({onSubmit = () => {}}: {onSubmit?: () => void}) { - const {asPath} = useRouter(); - const cleanedPath = asPath.split(/[\?\#]/)[0]; - // Reset on route changes. - return <SendFeedback key={cleanedPath} onSubmit={onSubmit} />; -} - -const thumbsUpIcon = ( - <svg - width="16" - height="18" - viewBox="0 0 16 18" - fill="none" - xmlns="http://www.w3.org/2000/svg"> - <path - fillRule="evenodd" - clipRule="evenodd" - d="M9.36603 0.384603C9.36605 0.384617 9.36601 0.384588 9.36603 0.384603L9.45902 0.453415C9.99732 0.851783 10.3873 1.42386 10.5654 2.07648C10.7435 2.72909 10.6993 3.42385 10.44 4.04763L9.27065 6.86008H12.6316C13.5249 6.86008 14.3817 7.22121 15.0134 7.86402C15.6451 8.50683 16 9.37868 16 10.2877V13.7154C16 14.8518 15.5564 15.9416 14.7668 16.7451C13.9771 17.5486 12.9062 18 11.7895 18H5.05263C3.71259 18 2.42743 17.4583 1.47988 16.4941C0.532325 15.5299 0 14.2221 0 12.8585V11.2511C2.40928e-06 9.87711 0.463526 8.54479 1.31308 7.47688L6.66804 0.745592C6.98662 0.345136 7.44414 0.08434 7.94623 0.0171605C8.4483 -0.0500155 8.95656 0.0815891 9.36603 0.384603ZM8.37542 1.77064C8.31492 1.72587 8.23987 1.70646 8.16579 1.71637C8.09171 1.72628 8.02415 1.76477 7.97708 1.82393L2.62213 8.55522C2.0153 9.31801 1.68421 10.2697 1.68421 11.2511V12.8585C1.68421 13.7676 2.03909 14.6394 2.67079 15.2822C3.30249 15.925 4.15927 16.2862 5.05263 16.2862H11.7895C12.4595 16.2862 13.1021 16.0153 13.5759 15.5332C14.0496 15.0511 14.3158 14.3972 14.3158 13.7154V10.2877C14.3158 9.83321 14.1383 9.39729 13.8225 9.07588C13.5066 8.75448 13.0783 8.57392 12.6316 8.57392H8C7.71763 8.57392 7.45405 8.4299 7.29806 8.19039C7.14206 7.95087 7.11442 7.64774 7.22445 7.38311L8.88886 3.37986C9 3.11253 9.01896 2.81477 8.94262 2.53507C8.8663 2.25541 8.69921 2.01027 8.46853 1.83954L8.37542 1.77064Z" - fill="currentColor" - /> - </svg> -); - -const thumbsDownIcon = ( - <svg - width="16" - height="18" - viewBox="0 0 16 18" - fill="none" - xmlns="http://www.w3.org/2000/svg"> - <path - fillRule="evenodd" - clipRule="evenodd" - d="M6.63397 17.6154C6.63395 17.6154 6.63399 17.6154 6.63397 17.6154L6.54098 17.5466C6.00268 17.1482 5.61269 16.5761 5.43458 15.9235C5.25648 15.2709 5.30069 14.5761 5.56004 13.9524L6.72935 11.1399L3.36842 11.1399C2.47506 11.1399 1.61829 10.7788 0.986585 10.136C0.354883 9.49316 8.1991e-07 8.62132 8.99384e-07 7.71225L1.19904e-06 4.28458C1.29838e-06 3.14824 0.443605 2.05844 1.23323 1.25492C2.02286 0.451403 3.09383 -1.12829e-06 4.21053 -1.03067e-06L10.9474 -4.41715e-07C12.2874 -3.24565e-07 13.5726 0.541687 14.5201 1.50591C15.4677 2.47013 16 3.77789 16 5.1415L16 6.74893C16 8.12289 15.5365 9.45521 14.6869 10.5231L9.33196 17.2544C9.01338 17.6549 8.55586 17.9157 8.05377 17.9828C7.5517 18.05 7.04344 17.9184 6.63397 17.6154ZM7.62458 16.2294C7.68508 16.2741 7.76013 16.2935 7.83421 16.2836C7.90829 16.2737 7.97585 16.2352 8.02292 16.1761L13.3779 9.44478C13.9847 8.68199 14.3158 7.73033 14.3158 6.74892L14.3158 5.1415C14.3158 4.23242 13.9609 3.36058 13.3292 2.71777C12.6975 2.07496 11.8407 1.71383 10.9474 1.71383L4.21053 1.71383C3.5405 1.71383 2.89793 1.98468 2.42415 2.46679C1.95038 2.94889 1.68421 3.60277 1.68421 4.28458L1.68421 7.71225C1.68421 8.16679 1.86166 8.60271 2.1775 8.92411C2.49335 9.24552 2.92174 9.42608 3.36842 9.42608L8 9.42608C8.28237 9.42608 8.54595 9.5701 8.70195 9.80961C8.85794 10.0491 8.88558 10.3523 8.77555 10.6169L7.11114 14.6201C7 14.8875 6.98105 15.1852 7.05738 15.4649C7.1337 15.7446 7.30079 15.9897 7.53147 16.1605L7.62458 16.2294Z" - fill="currentColor" - /> - </svg> -); - -function sendGAEvent(isPositive: boolean) { - const category = isPositive ? 'like_button' : 'dislike_button'; - const value = isPositive ? 1 : 0; - // Fragile. Don't change unless you've tested the network payload - // and verified that the right events actually show up in GA. - // @ts-ignore - gtag('event', 'feedback', { - event_category: category, - event_label: window.location.pathname, - event_value: value, - }); -} - -function SendFeedback({onSubmit}: {onSubmit: () => void}) { - const [isSubmitted, setIsSubmitted] = useState(false); - return ( - <div - className={cn( - 'max-w-custom-xs w-80 lg:w-auto py-3 shadow-lg rounded-lg m-4 bg-wash dark:bg-gray-95 px-4 flex', - {exit: isSubmitted} - )}> - <p className="w-full text-lg font-bold text-primary dark:text-primary-dark me-4"> - {isSubmitted ? 'Thank you for your feedback!' : 'Is this page useful?'} - </p> - {!isSubmitted && ( - <button - aria-label="Yes" - className="px-3 rounded-lg bg-secondary-button dark:bg-secondary-button-dark text-primary dark:text-primary-dark me-2" - onClick={() => { - setIsSubmitted(true); - onSubmit(); - sendGAEvent(true); - }}> - {thumbsUpIcon} - </button> - )} - {!isSubmitted && ( - <button - aria-label="No" - className="px-3 rounded-lg bg-secondary-button dark:bg-secondary-button-dark text-primary dark:text-primary-dark" - onClick={() => { - setIsSubmitted(true); - onSubmit(); - sendGAEvent(false); - }}> - {thumbsDownIcon} - </button> - )} - </div> - ); -} diff --git a/src/components/Layout/SidebarNav/SidebarNav.tsx b/src/components/Layout/SidebarNav/SidebarNav.tsx index 77beb4d7..678d483c 100644 --- a/src/components/Layout/SidebarNav/SidebarNav.tsx +++ b/src/components/Layout/SidebarNav/SidebarNav.tsx @@ -12,7 +12,6 @@ import {Suspense} from 'react'; import * as React from 'react'; import cn from 'classnames'; -import {Feedback} from '../Feedback'; import {SidebarRouteTree} from '../Sidebar/SidebarRouteTree'; import type {RouteItem} from '../getRouteMeta'; @@ -63,9 +62,6 @@ export default function SidebarNav({ </Suspense> <div className="h-20" /> </nav> - <div className="fixed bottom-0 hidden lg:block"> - <Feedback /> - </div> </aside> </div> </div> diff --git a/src/components/Layout/TopNav/TopNav.tsx b/src/components/Layout/TopNav/TopNav.tsx index 14809893..efc90ed2 100644 --- a/src/components/Layout/TopNav/TopNav.tsx +++ b/src/components/Layout/TopNav/TopNav.tsx @@ -29,7 +29,6 @@ import {IconHamburger} from 'components/Icon/IconHamburger'; import {IconSearch} from 'components/Icon/IconSearch'; import {Search} from 'components/Search'; import {Logo} from '../../Logo'; -import {Feedback} from '../Feedback'; import {SidebarRouteTree} from '../Sidebar'; import type {RouteItem} from '../getRouteMeta'; import {siteConfig} from 'siteConfig'; @@ -448,9 +447,6 @@ export default function TopNav({ </Suspense> <div className="h-16" /> </nav> - <div className="fixed bottom-0 hidden lg:block"> - <Feedback /> - </div> </aside> </div> )} diff --git a/src/content/blog/2025/12/03/critical-security-vulnerability-in-react-server-components.md b/src/content/blog/2025/12/03/critical-security-vulnerability-in-react-server-components.md index ffef6119..310a8411 100644 --- a/src/content/blog/2025/12/03/critical-security-vulnerability-in-react-server-components.md +++ b/src/content/blog/2025/12/03/critical-security-vulnerability-in-react-server-components.md @@ -62,13 +62,15 @@ An unauthenticated attacker could craft a malicious HTTP request to any Server F These instructions have been updated to include the new vulnerabilities: -- **Denial of Service - High Severity**: [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184) (CVSS 7.5) +- **Denial of Service - High Severity**: [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184) and [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779) (CVSS 7.5) - **Source Code Exposure - Medium Severity**: [CVE-2025-55183](https://www.cve.org/CVERecord?id=CVE-2025-55183) (CVSS 5.3) - -They also include the additional case found, patched, and disclosed as [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779). +- **Denial of Service - High Severity**: January 26, 2026 [CVE-2026-23864](https://www.cve.org/CVERecord?id=CVE-2026-23864) (CVSS 7.5) See the [follow-up blog post](/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components) for more info. +----- + +_Updated January 26, 2026._ </Note> ### Next.js {/*update-next-js*/} @@ -77,18 +79,21 @@ All users should upgrade to the latest patched version in their release line: ```bash npm install next@14.2.35 // for 13.3.x, 13.4.x, 13.5.x, 14.x -npm install next@15.0.7 // for 15.0.x -npm install next@15.1.11 // for 15.1.x -npm install next@15.2.8 // for 15.2.x -npm install next@15.3.8 // for 15.3.x -npm install next@15.4.10 // for 15.4.x -npm install next@15.5.9 // for 15.5.x -npm install next@16.0.10 // for 16.0.x +npm install next@15.0.8 // for 15.0.x +npm install next@15.1.12 // for 15.1.x +npm install next@15.2.9 // for 15.2.x +npm install next@15.3.9 // for 15.3.x +npm install next@15.4.11 // for 15.4.x +npm install next@15.5.10 // for 15.5.x +npm install next@16.0.11 // for 16.0.x +npm install next@16.1.5 // for 16.1.x npm install next@15.6.0-canary.60 // for 15.x canary releases npm install next@16.1.0-canary.19 // for 16.x canary releases ``` +15.0.8, 15.1.12, 15.2.9, 15.3.9, 15.4.10, 15.5.10, 15.6.0-canary.61, 16.0.11, 16.1.5 + If you are on version `13.3` or later version of Next.js 13 (`13.3.x`, `13.4.x`, or `13.5.x`) please upgrade to version `14.2.35`. If you are on `next@14.3.0-canary.77` or a later canary release, downgrade to the latest stable 14.x release: diff --git a/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md b/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md index 119317ed..6845e2f2 100644 --- a/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md +++ b/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md @@ -9,6 +9,8 @@ description: Security researchers have found and disclosed two additional vulner December 11, 2025 by [The React Team](/community/team) +_Updated January 26, 2026._ + --- <Intro> @@ -23,7 +25,7 @@ Security researchers have found and disclosed two additional vulnerabilities in The new vulnerabilities are disclosed as: -- **Denial of Service - High Severity**: [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184) and [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779) (CVSS 7.5) +- **Denial of Service - High Severity**: [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184), [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779), and [CVE-2026-23864](https://www.cve.org/CVERecord?id=CVE-2026-23864) (CVSS 7.5) - **Source Code Exposure - Medium Severity**: [CVE-2025-55183](https://www.cve.org/CVERecord?id=CVE-2025-55183) (CVSS 5.3) We recommend upgrading immediately due to the severity of the newly disclosed vulnerabilities. @@ -32,12 +34,16 @@ We recommend upgrading immediately due to the severity of the newly disclosed vu #### The patches published earlier are vulnerable. {/*the-patches-published-earlier-are-vulnerable*/} -If you already updated for the Critical Security Vulnerability last week, you will need to update again. +If you already updated for the previous vulnerabilities, you will need to update again. -If you updated to 19.0.2, 19.1.3, and 19.2.2, [these are incomplete](#additional-fix-published) and you will need to update again. +If you updated to 19.0.3, 19.1.4, and 19.2.3, [these are incomplete](#additional-fix-published), and you will need to update again. Please see [the instructions in the previous post](/blog/2025/12/03/critical-security-vulnerability-in-react-server-components#update-instructions) for upgrade steps. +----- + +_Updated January 26, 2026._ + </Note> Further details of these vulnerabilities will be provided after the rollout of the fixes are complete. @@ -46,13 +52,13 @@ Further details of these vulnerabilities will be provided after the rollout of t These vulnerabilities are present in the same packages and versions as [CVE-2025-55182](/blog/2025/12/03/critical-security-vulnerability-in-react-server-components). -This includes versions 19.0.0, 19.0.1, 19.0.2, 19.1.0, 19.1.1, 19.1.2, 19.1.2, 19.2.0, 19.2.1 and 19.2.2 of: +This includes 19.0.0, 19.0.1, 19.0.2, 19.0.3, 19.1.0, 19.1.1, 19.1.2, 19.1.3, 19.2.0, 19.2.1, 19.2.2, and 19.2.3 of: * [react-server-dom-webpack](https://www.npmjs.com/package/react-server-dom-webpack) * [react-server-dom-parcel](https://www.npmjs.com/package/react-server-dom-parcel) * [react-server-dom-turbopack](https://www.npmjs.com/package/react-server-dom-turbopack?activeTab=readme) -Fixes were backported to versions 19.0.3, 19.1.4, and 19.2.3. If you are using any of the above packages please upgrade to any of the fixed versions immediately. +Fixes were backported to versions 19.0.4, 19.1.5, and 19.2.4. If you are using any of the above packages please upgrade to any of the fixed versions immediately. As before, if your app’s React code does not use a server, your app is not affected by these vulnerabilities. If your app does not use a framework, bundler, or bundler plugin that supports React Server Components, your app is not affected by these vulnerabilities. @@ -72,7 +78,7 @@ Additional disclosures can be frustrating, but they are generally a sign of a he Some React frameworks and bundlers depended on, had peer dependencies for, or included the vulnerable React packages. The following React frameworks & bundlers are affected: [next](https://www.npmjs.com/package/next), [react-router](https://www.npmjs.com/package/react-router), [waku](https://www.npmjs.com/package/waku), [@parcel/rsc](https://www.npmjs.com/package/@parcel/rsc), [@vite/rsc-plugin](https://www.npmjs.com/package/@vitejs/plugin-rsc), and [rwsdk](https://www.npmjs.com/package/rwsdk). -Please see [the instructions in the previous post](https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components#update-instructions) for upgrade steps. +Please see [the instructions in the previous post](/blog/2025/12/03/critical-security-vulnerability-in-react-server-components#update-instructions) for upgrade steps. ### Hosting Provider Mitigations {/*hosting-provider-mitigations*/} @@ -94,29 +100,47 @@ This is required to mitigate the security advisories, but you do not need to upd See [this issue](https://github.com/facebook/react-native/issues/54772#issuecomment-3617929832) for more information. -## High Severity: Denial of Service {/*high-severity-denial-of-service*/} +--- -**CVEs:** [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184) and [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779) +## High Severity: Multiple Denial of Service {/*high-severity-multiple-denial-of-service*/} + +**CVEs:** [CVE-2026-23864](https://www.cve.org/CVERecord?id=CVE-2026-23864) **Base Score:** 7.5 (High) +**Date**: January 26, 2025 -Security researchers have discovered that a malicious HTTP request can be crafted and sent to any Server Functions endpoint that, when deserialized by React, can cause an infinite loop that hangs the server process and consumes CPU. Even if your app does not implement any React Server Function endpoints it may still be vulnerable if your app supports React Server Components. +Security researchers discovered additional DoS vulnerabilities still exist in React Server Components. -This creates a vulnerability vector where an attacker may be able to deny users from accessing the product, and potentially have a performance impact on the server environment. +The vulnerabilities are triggered by sending specially crafted HTTP requests to Server Function endpoints, and could lead to server crashes, out-of-memory exceptions or excessive CPU usage; depending on the vulnerable code path being exercised, the application configuration and application code. -The patches published today mitigate by preventing the infinite loop. +The patches published January 26th mitigate these DoS vulnerabilities. <Note> -#### Additional fix published {/*additional-fix-published*/} +#### Additional fixes published {/*additional-fix-published*/} The original fix addressing the DoS in [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184) was incomplete. -This left versions 19.0.2, 19.1.3, 19.2.2 vulnerable. Versions 19.0.3, 19.1.4, 19.2.3 are safe. +This left previous versions vulnerable. Versions 19.0.4, 19.1.5, 19.2.4 are safe. + +----- -We've fixed the additional cases and filed [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779) for the vulnerable versions. +_Updated January 26, 2026._ </Note> +--- + +## High Severity: Denial of Service {/*high-severity-denial-of-service*/} + +**CVEs:** [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184) and [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779) +**Base Score:** 7.5 (High) + +Security researchers have discovered that a malicious HTTP request can be crafted and sent to any Server Functions endpoint that, when deserialized by React, can cause an infinite loop that hangs the server process and consumes CPU. Even if your app does not implement any React Server Function endpoints it may still be vulnerable if your app supports React Server Components. + +This creates a vulnerability vector where an attacker may be able to deny users from accessing the product, and potentially have a performance impact on the server environment. + +The patches published today mitigate by preventing the infinite loop. + ## Medium Severity: Source Code Exposure {/*low-severity-source-code-exposure*/} **CVE:** [CVE-2025-55183](https://www.cve.org/CVERecord?id=CVE-2025-55183) @@ -170,9 +194,9 @@ Always verify against production bundles. * **December 11th**: Additional DoS reported to [Meta Bug Bounty](https://bugbounty.meta.com/) by Shinsaku Nomura. * **December 11th**: Patches published and publicly disclosed as [CVE-2025-55183](https://www.cve.org/CVERecord?id=CVE-2025-55183) and [CVE-2025-55184](https://www.cve.org/CVERecord?id=CVE-2025-55184). * **December 11th**: Missing DoS case found internally, patched and publicly disclosed as [CVE-2025-67779](https://www.cve.org/CVERecord?id=CVE-2025-67779). - +* **January 26th**: Additional DoS cases found, patched, and publicly disclosed as [CVE-2026-23864](https://www.cve.org/CVERecord?id=CVE-2026-23864). --- ## Attribution {/*attribution*/} -Thank you to [Andrew MacPherson (AndrewMohawk)](https://github.com/AndrewMohawk) for reporting the Source Code Exposure, [RyotaK](https://ryotak.net) from GMO Flatt Security Inc and Shinsaku Nomura of Bitforest Co., Ltd. for reporting the Denial of Service vulnerabilities. +Thank you to [Andrew MacPherson (AndrewMohawk)](https://github.com/AndrewMohawk) for reporting the Source Code Exposure, [RyotaK](https://ryotak.net) from GMO Flatt Security Inc and Shinsaku Nomura of Bitforest Co., Ltd. for reporting the Denial of Service vulnerabilities. Thank you to [Mufeed VH](https://x.com/mufeedvh) from [Winfunc Research](https://winfunc.com), [Joachim Viide](https://jviide.iki.fi), [RyotaK](https://ryotak.net) from [GMO Flatt Security Inc](https://flatt.tech/en/) and Xiangwei Zhang of Tencent Security YUNDING LAB for reporting the additional DoS vulnerabilities. diff --git a/src/content/learn/separating-events-from-effects.md b/src/content/learn/separating-events-from-effects.md index 7903cb36..5f6ce4ee 100644 --- a/src/content/learn/separating-events-from-effects.md +++ b/src/content/learn/separating-events-from-effects.md @@ -568,7 +568,7 @@ label { display: block; margin-top: 10px; } </Sandpack> -You can think of Effect Events as being very similar to event handlers. The main difference is that event handlers run in response to a user interactions, whereas Effect Events are triggered by you from Effects. Effect Events let you "break the chain" between the reactivity of Effects and code that should not be reactive. +You can think of Effect Events as being very similar to event handlers. The main difference is that event handlers run in response to user interactions, whereas Effect Events are triggered by you from Effects. Effect Events let you "break the chain" between the reactivity of Effects and code that should not be reactive. ### Reading latest props and state with Effect Events {/*reading-latest-props-and-state-with-effect-events*/} diff --git a/src/content/reference/react/ViewTransition.md b/src/content/reference/react/ViewTransition.md index acf59ac3..9f451edd 100644 --- a/src/content/reference/react/ViewTransition.md +++ b/src/content/reference/react/ViewTransition.md @@ -1052,8 +1052,6 @@ Just like any Transition, React waits for data and new CSS (`<link rel="styleshe If it's inside a new Suspense boundary instance, then the fallback is shown first. After the Suspense boundary fully loads, it triggers the `<ViewTransition>` to animate the reveal to the content. -Currently, this only happens for client-side Transition. In the future, this will also animate Suspense boundary for streaming SSR when content from the server suspends during the initial load. - There are two ways to animate Suspense boundaries depending on where you place the `<ViewTransition>`: Update: diff --git a/src/content/reference/react/useOptimistic.md b/src/content/reference/react/useOptimistic.md index b69a532f..250e43a3 100644 --- a/src/content/reference/react/useOptimistic.md +++ b/src/content/reference/react/useOptimistic.md @@ -7,7 +7,7 @@ title: useOptimistic `useOptimistic` is a React Hook that lets you optimistically update the UI. ```js - const [optimisticState, addOptimistic] = useOptimistic(state, updateFn); +const [optimisticState, setOptimistic] = useOptimistic(value, reducer?); ``` </Intro> @@ -18,24 +18,18 @@ title: useOptimistic ## Reference {/*reference*/} -### `useOptimistic(state, updateFn)` {/*use*/} +### `useOptimistic(value, reducer?)` {/*useoptimistic*/} -`useOptimistic` is a React Hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending. - -This state is called the "optimistic" state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete. +Call `useOptimistic` at the top level of your component to create optimistic state for a value. ```js import { useOptimistic } from 'react'; -function AppContainer() { - const [optimisticState, addOptimistic] = useOptimistic( - state, - // updateFn - (currentState, optimisticValue) => { - // merge and return new state - // with optimistic value - } - ); +function MyComponent({name, todos}) { + const [optimisticAge, setOptimisticAge] = useOptimistic(28); + const [optimisticName, setOptimisticName] = useOptimistic(name); + const [optimisticTodos, setOptimisticTodos] = useOptimistic(todos, todoReducer); + // ... } ``` @@ -43,89 +37,1047 @@ function AppContainer() { #### Parameters {/*parameters*/} -* `state`: the value to be returned initially and whenever no action is pending. -* `updateFn(currentState, optimisticValue)`: a function that takes the current state and the optimistic value passed to `addOptimistic` and returns the resulting optimistic state. It must be a pure function. `updateFn` takes in two parameters. The `currentState` and the `optimisticValue`. The return value will be the merged value of the `currentState` and `optimisticValue`. - +* `value`: The value returned when there are no pending Actions. +* **optional** `reducer(currentState, action)`: The reducer function that specifies how the optimistic state gets updated. It must be pure, should take the current state and reducer action arguments, and should return the next optimistic state. #### Returns {/*returns*/} -* `optimisticState`: The resulting optimistic state. It is equal to `state` unless an action is pending, in which case it is equal to the value returned by `updateFn`. -* `addOptimistic`: `addOptimistic` is the dispatching function to call when you have an optimistic update. It takes one argument, `optimisticValue`, of any type and will call the `updateFn` with `state` and `optimisticValue`. +`useOptimistic` returns an array with exactly two values: + +1. `optimisticState`: The current optimistic state. It is equal to `value` unless an Action is pending, in which case it is equal to the state returned by `reducer` (or the value passed to the set function if no `reducer` was provided). +2. The [`set` function](#setoptimistic) that lets you update the optimistic state to a different value inside an Action. + +--- + +### `set` functions, like `setOptimistic(optimisticState)` {/*setoptimistic*/} + +The `set` function returned by `useOptimistic` lets you update the state for the duration of an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). You can pass the next state directly, or a function that calculates it from the previous state: + +```js +const [optimisticLike, setOptimisticLike] = useOptimistic(false); +const [optimisticSubs, setOptimisticSubs] = useOptimistic(subs); + +function handleClick() { + startTransition(async () => { + setOptimisticLike(true); + setOptimisticSubs(a => a + 1); + await saveChanges(); + }); +} +``` + +#### Parameters {/*setoptimistic-parameters*/} + +* `optimisticState`: The value that you want the optimistic state to be during an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). If you provided a `reducer` to `useOptimistic`, this value will be passed as the second argument to your reducer. It can be a value of any type. + * If you pass a function as `optimisticState`, it will be treated as an _updater function_. It must be pure, should take the pending state as its only argument, and should return the next optimistic state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying the queued updaters to the previous state similar to [`useState` updaters](/reference/react/useState#setstate-parameters). + +#### Returns {/*setoptimistic-returns*/} + +`set` functions do not have a return value. + +#### Caveats {/*setoptimistic-caveats*/} + +* The `set` function must be called inside an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). If you call the setter outside an Action, [React will show a warning](#an-optimistic-state-update-occurred-outside-a-transition-or-action) and the optimistic state will briefly render. + +<DeepDive> + +#### How optimistic state works {/*how-optimistic-state-works*/} + +`useOptimistic` lets you show a temporary value while a Action is in progress: + +```js +const [value, setValue] = useState('a'); +const [optimistic, setOptimistic] = useOptimistic(value); + +startTransition(async () => { + setOptimistic('b'); + const newValue = await saveChanges('b'); + setValue(newValue); +}); +``` + +When the setter is called inside an Action, `useOptimistic` will trigger a re-render to show that state while the Action is in progress. Otherwise, the `value` passed to `useOptimistic` is returned. + +This state is called the "optimistic" because it is used to immediately present the user with the result of performing an Action, even though the Action actually takes time to complete. + +**How the update flows** + +1. **Update immediately**: When `setOptimistic('b')` is called, React immediately renders with `'b'`. + +2. **(Optional) await in Action**: If you await in the Action, React continues showing `'b'`. + +3. **Transition scheduled**: `setValue(newValue)` schedules an update to the real state. + +4. **(Optional) wait for Suspense**: If `newValue` suspends, React continues showing `'b'`. + +5. **Single render commit**: Finally, the `newValue` is commits for `value` and `optimistic`. + +There's no extra render to "clear" the optimistic state. The optimistic and real state converge in the same render when the Transition completes. + +<Note> + +#### Optimistic state is temporary {/*optimistic-state-is-temporary*/} + +Optimistic state is only renders while an Action is in progress, otherwise `value` is rendered. + +If `saveChanges` returned `'c'`, then both `value` and `optimistic` will be `'c'`, not `'b'`. + +</Note> + +**How the final state is determined** + +The `value` argument to `useOptimistic` determines what displays after the Action finishes. How this works depends on the pattern you use: + +- **Hardcoded values** like `useOptimistic(false)`: After the Action, `state` is still `false`, so the UI shows `false`. This is useful for pending states where you always start from `false`. + +- **Props or state passed in** like `useOptimistic(isLiked)`: If the parent updates `isLiked` during the Action, the new value is used after the Action completes. This is how the UI reflects the result of the Action. + +- **Reducer pattern** like `useOptimistic(items, fn)`: If `items` changes while the Action is pending, React re-runs your `reducer` with the new `items` to recalculate the state. This keeps your optimistic additions on top of the latest data. + +**What happens when the Action fails** + +If the Action throws an error, the Transition still ends, and React renders with whatever `value` currently is. Since the parent typically only updates `value` on success, a failure means `value` hasn't changed, so the UI shows what it showed before the optimistic update. You can catch the error to show a message to the user. + +</DeepDive> --- ## Usage {/*usage*/} -### Optimistically updating forms {/*optimistically-updating-with-forms*/} +### Adding optimistic state to a component {/*adding-optimistic-state-to-a-component*/} + +Call `useOptimistic` at the top level of your component to declare one or more optimistic states. + +```js [[1, 4, "age"], [1, 5, "name"], [1, 6, "todos"], [2, 4, "optimisticAge"], [2, 5, "optimisticName"], [2, 6, "optimisticTodos"], [3, 4, "setOptimisticAge"], [3, 5, "setOptimisticName"], [3, 6, "setOptimisticTodos"], [4, 6, "reducer"]] +import { useOptimistic } from 'react'; + +function MyComponent({age, name, todos}) { + const [optimisticAge, setOptimisticAge] = useOptimistic(age); + const [optimisticName, setOptimisticName] = useOptimistic(name); + const [optimisticTodos, setOptimisticTodos] = useOptimistic(todos, reducer); + // ... +``` + +`useOptimistic` returns an array with exactly two items: + +1. The <CodeStep step={2}>optimistic state</CodeStep>, initially set to the <CodeStep step={1}>value</CodeStep> provided. +2. The <CodeStep step={3}>set function</CodeStep> that lets you temporarily change the state during an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). + * If a <CodeStep step={4}>reducer</CodeStep> is provided, it will run before returning the optimistic state. + +To use the <CodeStep step={2}>optimistic state</CodeStep>, call the `set` function inside an Action. + +Actions are functions called inside `startTransition`: + +```js {3} +function onAgeChange(e) { + startTransition(async () => { + setOptimisticAge(42); + const newAge = await postAge(42); + setAge(newAge); + }); +} +``` + +React will render the optimistic state `42` first while the `age` remains the current age. The Action waits for POST, and then renders the `newAge` for both `age` and `optimisticAge`. + +See [How optimistic state works](#how-optimistic-state-works) for a deep dive. + +<Note> + +When using [Action props](/reference/react/useTransition#exposing-action-props-from-components), you can call the set function without `startTransition`: + +```js [[3, 2, "setOptimisticName"]] +async function submitAction() { + setOptimisticName('Taylor'); + await updateName('Taylor'); +} +``` + +This works because Action props are already called inside `startTransition`. + +For an example, see: [Using optimistic state in Action props](#using-optimistic-state-in-action-props). + +</Note> + +--- + +### Using optimistic state in Action props {/*using-optimistic-state-in-action-props*/} + +In an [Action prop](/reference/react/useTransition#exposing-action-props-from-components), you can call the optimistic setter directly without `startTransition`. + +This example sets optimistic state inside a `<form>` `submitAction` prop: + +<Sandpack> + +```js src/App.js +import { useState, startTransition } from 'react'; +import EditName from './EditName'; + +export default function App() { + const [name, setName] = useState('Alice'); + + return <EditName name={name} action={setName} />; +} +``` + +```js src/EditName.js active +import { useOptimistic, startTransition } from 'react'; +import { updateName } from './actions.js'; + +export default function EditName({ name, action }) { + const [optimisticName, setOptimisticName] = useOptimistic(name); + + async function submitAction(formData) { + const newName = formData.get('name'); + setOptimisticName(newName); + + const updatedName = await updateName(newName); + startTransition(() => { + action(updatedName); + }) + } + + return ( + <form action={submitAction}> + <p>Your name is: {optimisticName}</p> + <p> + <label>Change it: </label> + <input + type="text" + name="name" + disabled={name !== optimisticName} + /> + </p> + </form> + ); +} +``` + +```js src/actions.js hidden +export async function updateName(name) { + await new Promise((res) => setTimeout(res, 1000)); + return name; +} +``` + +</Sandpack> + +In this example, when the user submits the form, the `optimisticName` updates immediately to show the `newName` optimistically while the server request is in progress. When the request completes, `name` and `optimisticName` are rendered with the actual `updatedName` from the response. + +<DeepDive> + +#### Why doesn't this need `startTransition`? {/*why-doesnt-this-need-starttransition*/} + +By convention, props called inside `startTransition` are named with "Action". -The `useOptimistic` Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server's response to reflect the changes, the interface is immediately updated with the expected outcome. +Since `submitAction` is named with "Action", you know it's already called inside `startTransition`. -For example, when a user types a message into the form and hits the "Send" button, the `useOptimistic` Hook allows the message to immediately appear in the list with a "Sending..." label, even before the message is actually sent to a server. This "optimistic" approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the "Sending..." label is removed. +See [Exposing `action` prop from components](/reference/react/useTransition#exposing-action-props-from-components) for the Action prop pattern. + +</DeepDive> + +--- + +### Adding optimistic state to Action props {/*adding-optimistic-state-to-action-props*/} + +When creating an [Action prop](/reference/react/useTransition#exposing-action-props-from-components), you can add `useOptimistic` to show immediate feedback. + +Here's a button that shows "Submitting..." while the `action` is pending: <Sandpack> +```js src/App.js +import { useState, startTransition } from 'react'; +import Button from './Button'; +import { submitForm } from './actions.js'; + +export default function App() { + const [count, setCount] = useState(0); + return ( + <div> + <Button action={async () => { + await submitForm(); + startTransition(() => { + setCount(c => c + 1); + }); + }}>Increment</Button> + {count > 0 && <p>Submitted {count}!</p>} + </div> + ); +} +``` + +```js src/Button.js active +import { useOptimistic, startTransition } from 'react'; + +export default function Button({ action, children }) { + const [isPending, setIsPending] = useOptimistic(false); + + return ( + <button + disabled={isPending} + onClick={() => { + startTransition(async () => { + setIsPending(true); + await action(); + }); + }} + > + {isPending ? 'Submitting...' : children} + </button> + ); +} +``` + +```js src/actions.js hidden +export async function submitForm() { + await new Promise((res) => setTimeout(res, 1000)); +} +``` + +</Sandpack> + +When the button is clicked, `setIsPending(true)` uses optimistic state to immediately show "Submitting..." and disable the button. When the Action is done, `isPending` is rendered as `false` automatically. + +This pattern automatically shows a pending state however `action` prop is used with `Button`: + +```js +// Show pending state for a state update +<Button action={() => { setState(c => c + 1) }} /> + +// Show pending state for a navigation +<Button action={() => { navigate('/done') }} /> + +// Show pending state for a POST +<Button action={async () => { await fetch(/* ... */) }} /> + +// Show pending state for any combination +<Button action={async () => { + setState(c => c + 1); + await fetch(/* ... */); + navigate('/done'); +}} /> +``` + +The pending state will be shown until everything in the `action` prop is finished. + +<Note> + +You can also use [`useTransition`](/reference/react/useTransition) to get pending state via `isPending`. + +The difference is that `useTransition` gives you the `startTransition` function, while `useOptimistic` works with any Transition. Use whichever fits your component's needs. + +</Note> + +--- + +### Updating props or state optimistically {/*updating-props-or-state-optimistically*/} + +You can wrap props or state in `useOptimistic` to update it immediately while an Action is in progress. + +In this example, `LikeButton` receives `isLiked` as a prop and immediately toggles it when clicked: + +<Sandpack> ```js src/App.js -import { useOptimistic, useState, useRef, startTransition } from "react"; -import { deliverMessage } from "./actions.js"; - -function Thread({ messages, sendMessageAction }) { - const formRef = useRef(); - function formAction(formData) { - addOptimisticMessage(formData.get("message")); - formRef.current.reset(); +import { useState, useOptimistic, startTransition } from 'react'; +import { toggleLike } from './actions.js'; + +export default function App() { + const [isLiked, setIsLiked] = useState(false); + const [optimisticIsLiked, setOptimisticIsLiked] = useOptimistic(isLiked); + + function handleClick() { startTransition(async () => { - await sendMessageAction(formData); + const newValue = !optimisticIsLiked + console.log('⏳ setting optimistic state: ' + newValue); + + setOptimisticIsLiked(newValue); + const updatedValue = await toggleLike(newValue); + + startTransition(() => { + console.log('⏳ setting real state: ' + updatedValue ); + setIsLiked(updatedValue); + }); }); } - const [optimisticMessages, addOptimisticMessage] = useOptimistic( - messages, - (state, newMessage) => [ - { - text: newMessage, - sending: true - }, - ...state, - ] + + if (optimisticIsLiked !== isLiked) { + console.log('βœ… rendering optmistic state: ' + optimisticIsLiked); + } else { + console.log('βœ… rendering real value: ' + optimisticIsLiked); + } + + + return ( + <button onClick={handleClick}> + {optimisticIsLiked ? '❀️ Unlike' : '🀍 Like'} + </button> + ); +} +``` + +```js src/actions.js hidden +export async function toggleLike(value) { + return await new Promise((res) => setTimeout(() => res(value), 1000)); + // In a real app, this would update the server +} +``` + +```js src/index.js hidden +import React from 'react'; +import {createRoot} from 'react-dom/client'; +import './styles.css'; + +import App from './App'; + +const root = createRoot(document.getElementById('root')); +// Not using StrictMode so double render logs are not shown. +root.render(<App />); +``` + +</Sandpack> + +When the button is clicked, `setOptimisticIsLiked` immediately updates the displayed state to show the heart as liked. Meanwhile, `await toggleLike` runs in the background. When the `await` completes, `setIsLiked` parent updates the "real" `isLiked` state, and the optimistic state is rendered to match this new value. + +<Note> + +This example reads from `optimisticIsLiked` to calculate the next value. This works when the base state won't change, but if the base state might change while your Action is pending, you may want to use a state updater or the reducer. + +See [Updating state based on the current state](#updating-state-based-on-current-state) for an example. + +</Note> + +--- + +### Updating multiple values together {/*updating-multiple-values-together*/} + +When an optimistic update affects multiple related values, use a reducer to update them together. This ensures the UI stays consistent. + +Here's a follow button that updates both the follow state and follower count: + +<Sandpack> + +```js src/App.js +import { useState, startTransition } from 'react'; +import { followUser, unfollowUser } from './actions.js'; +import FollowButton from './FollowButton'; + +export default function App() { + const [user, setUser] = useState({ + name: 'React', + isFollowing: false, + followerCount: 10500 + }); + + async function followAction(shouldFollow) { + if (shouldFollow) { + await followUser(user.name); + } else { + await unfollowUser(user.name); + } + startTransition(() => { + setUser(current => ({ + ...current, + isFollowing: shouldFollow, + followerCount: current.followerCount + (shouldFollow ? 1 : -1) + })); + }); + } + + return <FollowButton user={user} followAction={followAction} />; +} +``` + +```js src/FollowButton.js active +import { useOptimistic, startTransition } from 'react'; + +export default function FollowButton({ user, followAction }) { + const [optimisticState, updateOptimistic] = useOptimistic( + { isFollowing: user.isFollowing, followerCount: user.followerCount }, + (current, isFollowing) => ({ + isFollowing, + followerCount: current.followerCount + (isFollowing ? 1 : -1) + }) ); + function handleClick() { + const newFollowState = !optimisticState.isFollowing; + startTransition(async () => { + updateOptimistic(newFollowState); + await followAction(newFollowState); + }); + } + return ( - <> - <form action={formAction} ref={formRef}> - <input type="text" name="message" placeholder="Hello!" /> - <button type="submit">Send</button> - </form> - {optimisticMessages.map((message, index) => ( - <div key={index}> - {message.text} - {!!message.sending && <small> (Sending...)</small>} - </div> - ))} - - </> + <div> + <p><strong>{user.name}</strong></p> + <p>{optimisticState.followerCount} followers</p> + <button onClick={handleClick}> + {optimisticState.isFollowing ? 'Unfollow' : 'Follow'} + </button> + </div> ); } +``` + +```js src/actions.js hidden +export async function followUser(name) { + await new Promise((res) => setTimeout(res, 1000)); +} + +export async function unfollowUser(name) { + await new Promise((res) => setTimeout(res, 1000)); +} +``` + +</Sandpack> + +The reducer receives the new `isFollowing` value and calculates both the new follow state and the updated follower count in a single update. This ensures the button text and count always stay in sync. + + +<DeepDive> + +#### Choosing between updaters and reducers {/*choosing-between-updaters-and-reducers*/} + +`useOptimistic` supports two patterns for calculating state based on current state: + +**Updater functions** work like [useState updaters](/reference/react/useState#updating-state-based-on-the-previous-state). Pass a function to the setter: + +```js +const [optimistic, setOptimistic] = useOptimistic(value); +setOptimistic(current => !current); +``` + +**Reducers** separate the update logic from the setter call: + +```js +const [optimistic, dispatch] = useOptimistic(value, (current, action) => { + // Calculate next state based on current and action +}); +dispatch(action); +``` + +**Use updaters** for calculations where the setter call naturally describes the update. This is similar to using `setState(prev => ...)` with `useState`. + +**Use reducers** when you need to pass data to the update (like which item to add) or when handling multiple types of updates with a single hook. + +**Why use a reducer?** + +Reducers are essential when the base state might change while your Transition is pending. If `todos` changes while your add is pending (for example, another user added a todo), React will re-run your reducer with the new `todos` to recalculate what to show. This ensures your new todo is added to the latest list, not an outdated copy. + +An updater function like `setOptimistic(prev => [...prev, newItem])` would only see the state from when the Transition started, missing any updates that happened during the async work. + +</DeepDive> + +--- + +### Optimistically adding to a list {/*optimistically-adding-to-a-list*/} + +When you need to optimistically add items to a list, use a `reducer`: + +<Sandpack> + +```js src/App.js +import { useState, startTransition } from 'react'; +import { addTodo } from './actions.js'; +import TodoList from './TodoList'; export default function App() { - const [messages, setMessages] = useState([ - { text: "Hello there!", sending: false, key: 1 } + const [todos, setTodos] = useState([ + { id: 1, text: 'Learn React' } ]); - async function sendMessageAction(formData) { - const sentMessage = await deliverMessage(formData.get("message")); + + async function addTodoAction(newTodo) { + const savedTodo = await addTodo(newTodo); startTransition(() => { - setMessages((messages) => [{ text: sentMessage }, ...messages]); - }) + setTodos(todos => [...todos, savedTodo]); + }); + } + + return <TodoList todos={todos} addTodoAction={addTodoAction} />; +} +``` + +```js src/TodoList.js active +import { useOptimistic, startTransition } from 'react'; + +export default function TodoList({ todos, addTodoAction }) { + const [optimisticTodos, addOptimisticTodo] = useOptimistic( + todos, + (currentTodos, newTodo) => [ + ...currentTodos, + { id: newTodo.id, text: newTodo.text, pending: true } + ] + ); + + function handleAddTodo(text) { + const newTodo = { id: crypto.randomUUID(), text: text }; + startTransition(async () => { + addOptimisticTodo(newTodo); + await addTodoAction(newTodo); + }); } - return <Thread messages={messages} sendMessageAction={sendMessageAction} />; + + return ( + <div> + <button onClick={() => handleAddTodo('New todo')}>Add Todo</button> + <ul> + {optimisticTodos.map(todo => ( + <li key={todo.id}> + {todo.text} {todo.pending && "(Adding...)"} + </li> + ))} + </ul> + </div> + ); } ``` -```js src/actions.js -export async function deliverMessage(message) { +```js src/actions.js hidden +export async function addTodo(todo) { await new Promise((res) => setTimeout(res, 1000)); - return message; + // In a real app, this would save to the server + return { ...todo, pending: false }; } ``` +</Sandpack> + +The `reducer` receives the current list of todos and the new todo to add. This is important because if the `todos` prop changes while your add is pending (for example, another user added a todo), React will update your optimistic state by re-running the reducer with the updated list. This ensures your new todo is added to the latest list, not an outdated copy. + +<Note> + +Each optimistic item includes a `pending: true` flag so you can show loading state for individual items. When the server responds and the parent updates the canonical `todos` list with the saved item, the optimistic state updates to the confirmed item without the pending flag. + +</Note> + +--- + +### Handling multiple `action` types {/*handling-multiple-action-types*/} + +When you need to handle multiple types of optimistic updates (like adding and removing items), use a reducer pattern with `action` objects. + +This shopping cart example shows how to handle add and remove with a single reducer: + +<Sandpack> + +```js src/App.js +import { useState, startTransition } from 'react'; +import { addToCart, removeFromCart, updateQuantity } from './actions.js'; +import ShoppingCart from './ShoppingCart'; + +export default function App() { + const [cart, setCart] = useState([]); + + const cartActions = { + async add(item) { + await addToCart(item); + startTransition(() => { + setCart(current => { + const exists = current.find(i => i.id === item.id); + if (exists) { + return current.map(i => + i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i + ); + } + return [...current, { ...item, quantity: 1 }]; + }); + }); + }, + async remove(id) { + await removeFromCart(id); + startTransition(() => { + setCart(current => current.filter(item => item.id !== id)); + }); + }, + async updateQuantity(id, quantity) { + await updateQuantity(id, quantity); + startTransition(() => { + setCart(current => + current.map(item => + item.id === id ? { ...item, quantity } : item + ) + ); + }); + } + }; + + return <ShoppingCart cart={cart} cartActions={cartActions} />; +} +``` + +```js src/ShoppingCart.js active +import { useOptimistic, startTransition } from 'react'; + +export default function ShoppingCart({ cart, cartActions }) { + const [optimisticCart, dispatch] = useOptimistic( + cart, + (currentCart, action) => { + switch (action.type) { + case 'add': + const exists = currentCart.find(item => item.id === action.item.id); + if (exists) { + return currentCart.map(item => + item.id === action.item.id + ? { ...item, quantity: item.quantity + 1, pending: true } + : item + ); + } + return [...currentCart, { ...action.item, quantity: 1, pending: true }]; + case 'remove': + return currentCart.filter(item => item.id !== action.id); + case 'update_quantity': + return currentCart.map(item => + item.id === action.id + ? { ...item, quantity: action.quantity, pending: true } + : item + ); + default: + return currentCart; + } + } + ); + + function handleAdd(item) { + startTransition(async () => { + dispatch({ type: 'add', item }); + await cartActions.add(item); + }); + } + + function handleRemove(id) { + startTransition(async () => { + dispatch({ type: 'remove', id }); + await cartActions.remove(id); + }); + } + + function handleUpdateQuantity(id, quantity) { + startTransition(async () => { + dispatch({ type: 'update_quantity', id, quantity }); + await cartActions.updateQuantity(id, quantity); + }); + } + + const total = optimisticCart.reduce( + (sum, item) => sum + item.price * item.quantity, + 0 + ); + + return ( + <div> + <h2>Shopping Cart</h2> + <div style={{ marginBottom: 16 }}> + <button onClick={() => handleAdd({ + id: 1, name: 'T-Shirt', price: 25 + })}> + Add T-Shirt ($25) + </button>{' '} + <button onClick={() => handleAdd({ + id: 2, name: 'Mug', price: 15 + })}> + Add Mug ($15) + </button> + </div> + {optimisticCart.length === 0 ? ( + <p>Your cart is empty</p> + ) : ( + <ul> + {optimisticCart.map(item => ( + <li key={item.id}> + {item.name} - ${item.price} Γ— + {item.quantity} + {' '}= ${item.price * item.quantity} + <button + onClick={() => handleRemove(item.id)} + style={{ marginLeft: 8 }} + > + Remove + </button> + {item.pending && ' ...'} + </li> + ))} + </ul> + )} + <p><strong>Total: ${total}</strong></p> + </div> + ); +} +``` + +```js src/actions.js hidden +export async function addToCart(item) { + await new Promise((res) => setTimeout(res, 800)); +} + +export async function removeFromCart(id) { + await new Promise((res) => setTimeout(res, 800)); +} + +export async function updateQuantity(id, quantity) { + await new Promise((res) => setTimeout(res, 800)); +} +``` </Sandpack> + +The reducer handles three `action` types (`add`, `remove`, `update_quantity`) and returns the new optimistic state for each. Each `action` sets a `pending: true` flag so you can show visual feedback while the [Server Function](/reference/rsc/server-functions) runs. + +--- + +### Optimistic delete with error recovery {/*optimistic-delete-with-error-recovery*/} + +When deleting items optimistically, you should handle the case where the Action fails. + +This example shows how to display an error message when a delete fails, and the UI automatically rolls back to show the item again. + +<Sandpack> + +```js src/App.js +import { useState, startTransition } from 'react'; +import { deleteItem } from './actions.js'; +import ItemList from './ItemList'; + +export default function App() { + const [items, setItems] = useState([ + { id: 1, name: 'Learn React' }, + { id: 2, name: 'Build an app' }, + { id: 3, name: 'Deploy to production' }, + ]); + + async function deleteAction(id) { + await deleteItem(id); + startTransition(() => { + setItems(current => current.filter(item => item.id !== id)); + }); + } + + return <ItemList items={items} deleteAction={deleteAction} />; +} +``` + +```js src/ItemList.js active +import { useState, useOptimistic, startTransition } from 'react'; + +export default function ItemList({ items, deleteAction }) { + const [error, setError] = useState(null); + const [optimisticItems, removeItem] = useOptimistic( + items, + (currentItems, idToRemove) => + currentItems.map(item => + item.id === idToRemove + ? { ...item, deleting: true } + : item + ) + ); + + function handleDelete(id) { + setError(null); + startTransition(async () => { + removeItem(id); + try { + await deleteAction(id); + } catch (e) { + setError(e.message); + } + }); + } + + return ( + <div> + <h2>Your Items</h2> + <ul> + {optimisticItems.map(item => ( + <li + key={item.id} + style={{ + opacity: item.deleting ? 0.5 : 1, + textDecoration: item.deleting ? 'line-through' : 'none', + transition: 'opacity 0.2s' + }} + > + {item.name} + <button + onClick={() => handleDelete(item.id)} + disabled={item.deleting} + style={{ marginLeft: 8 }} + > + {item.deleting ? 'Deleting...' : 'Delete'} + </button> + </li> + ))} + </ul> + {error && ( + <p style={{ color: 'red', padding: 8, background: '#fee' }}> + {error} + </p> + )} + </div> + ); +} +``` + +```js src/actions.js hidden +export async function deleteItem(id) { + await new Promise((res) => setTimeout(res, 1000)); + // Item 3 always fails to demonstrate error recovery + if (id === 3) { + throw new Error('Cannot delete. Permission denied.'); + } +} +``` + +</Sandpack> + +Try deleting 'Deploy to production'. When the delete fails, the item automatically reappears in the list. + +--- + +## Troubleshooting {/*troubleshooting*/} + +### I'm getting an error: "An optimistic state update occurred outside a Transition or Action" {/*an-optimistic-state-update-occurred-outside-a-transition-or-action*/} + +You may see this error: + +<ConsoleBlockMulti> + +<ConsoleLogLine level="error"> + +An optimistic state update occurred outside a Transition or Action. To fix, move the update to an Action, or wrap with `startTransition`. + +</ConsoleLogLine> + +</ConsoleBlockMulti> + +The optimistic setter function must be called inside `startTransition`: + +```js +// 🚩 Incorrect: outside a Transition +function handleClick() { + setOptimistic(newValue); // Warning! + // ... +} + +// βœ… Correct: inside a Transition +function handleClick() { + startTransition(async () => { + setOptimistic(newValue); + // ... + }); +} + +// βœ… Also correct: inside an Action prop +function submitAction(formData) { + setOptimistic(newValue); + // ... +} +``` + +When you call the setter outside an Action, the optimistic state will briefly appear and then immediately revert back to the original value. This happens because there's no Transition to "hold" the optimistic state while your Action runs. + +### I'm getting an error: "Cannot update optimistic state while rendering" {/*cannot-update-optimistic-state-while-rendering*/} + +You may see this error: + +<ConsoleBlockMulti> + +<ConsoleLogLine level="error"> + +Cannot update optimistic state while rendering. + +</ConsoleLogLine> + +</ConsoleBlockMulti> + +This error occurs when you call the optimistic setter during the render phase of a component. You can only call it from event handlers, effects, or other callbacks: + +```js +// 🚩 Incorrect: calling during render +function MyComponent({ items }) { + const [isPending, setPending] = useOptimistic(false); + + // This runs during render - not allowed! + setPending(true); + + // ... +} + +// βœ… Correct: calling inside startTransition +function MyComponent({ items }) { + const [isPending, setPending] = useOptimistic(false); + + function handleClick() { + startTransition(() => { + setPending(true); + // ... + }); + } + + // ... +} + +// βœ… Also correct: calling from an Action +function MyComponent({ items }) { + const [isPending, setPending] = useOptimistic(false); + + function action() { + setPending(true); + // ... + } + + // ... +} +``` + +### My optimistic updates show stale values {/*my-optimistic-updates-show-stale-values*/} + +If your optimistic state seems to be based on old data, consider using an updater function or reducer to calculate the optimistic state relative to the current state. + +```js +// May show stale data if state changes during Action +const [optimistic, setOptimistic] = useOptimistic(count); +setOptimistic(5); // Always sets to 5, even if count changed + +// Better: relative updates handle state changes correctly +const [optimistic, adjust] = useOptimistic(count, (current, delta) => current + delta); +adjust(1); // Always adds 1 to whatever the current count is +``` + +See [Updating state based on the current state](#updating-state-based-on-current-state) for details. + +### I don't know if my optimistic update is pending {/*i-dont-know-if-my-optimistic-update-is-pending*/} + +To know when `useOptimistic` is pending, you have three options: + +1. **Check if `optimisticValue === value`** + +```js +const [optimistic, setOptimistic] = useOptimistic(value); +const isPending = optimistic !== value; +``` + +If the values are not equal, there's a Transition in progress. + +2. **Add a `useTransition`** + +``` +const [isPending, startTransition] = useTransition(); +const [optimistic, setOptimistic] = useOptimistic(value); + +//... +startTransition(() => { + setOptimistic(state); +}) +``` + +Since `useTransition` uses `useOptimsitic` for `isPending` under the hood, this is equivalent to option 1. + +3**Add a `pending` flag in your reducer** + +```js +const [optimistic, addOptimistic] = useOptimistic( + items, + (state, newItem) => [...state, { ...newItem, isPending: true }] +); +``` diff --git a/src/pages/api/md/[...path].ts b/src/pages/api/md/[...path].ts new file mode 100644 index 00000000..5f80e4e8 --- /dev/null +++ b/src/pages/api/md/[...path].ts @@ -0,0 +1,53 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import type {NextApiRequest, NextApiResponse} from 'next'; +import fs from 'fs'; +import path from 'path'; + +const FOOTER = ` +--- + +## Sitemap + +[Overview of all docs pages](/llms.txt) +`; + +export default function handler(req: NextApiRequest, res: NextApiResponse) { + const pathSegments = req.query.path; + if (!pathSegments) { + return res.status(404).send('Not found'); + } + + const filePath = Array.isArray(pathSegments) + ? pathSegments.join('/') + : pathSegments; + + // Block /index.md URLs - use /foo.md instead of /foo/index.md + if (filePath.endsWith('/index') || filePath === 'index') { + return res.status(404).send('Not found'); + } + + // Try exact path first, then with /index + const candidates = [ + path.join(process.cwd(), 'src/content', filePath + '.md'), + path.join(process.cwd(), 'src/content', filePath, 'index.md'), + ]; + + for (const fullPath of candidates) { + try { + const content = fs.readFileSync(fullPath, 'utf8'); + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.setHeader('Cache-Control', 'public, max-age=3600'); + return res.status(200).send(content + FOOTER); + } catch { + // Try next candidate + } + } + + res.status(404).send('Not found'); +} diff --git a/src/pages/llms.txt.tsx b/src/pages/llms.txt.tsx new file mode 100644 index 00000000..23fda9dd --- /dev/null +++ b/src/pages/llms.txt.tsx @@ -0,0 +1,269 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import type {GetServerSideProps} from 'next'; +import {siteConfig} from '../siteConfig'; +import sidebarLearn from '../sidebarLearn.json'; +import sidebarReference from '../sidebarReference.json'; + +interface RouteItem { + title?: string; + path?: string; + routes?: RouteItem[]; + hasSectionHeader?: boolean; + sectionHeader?: string; +} + +interface Sidebar { + title: string; + routes: RouteItem[]; +} + +interface Page { + title: string; + url: string; +} + +interface SubGroup { + heading: string; + pages: Page[]; +} + +interface Section { + heading: string | null; + pages: Page[]; + subGroups: SubGroup[]; +} + +// Clean up section header names (remove version placeholders) +function cleanSectionHeader(header: string): string { + return header + .replace(/@\{\{version\}\}/g, '') + .replace(/-/g, ' ') + .split(' ') + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' ') + .trim(); +} + +// Extract routes for sidebars that use hasSectionHeader to define major sections +// (like the API Reference sidebar) +function extractSectionedRoutes( + routes: RouteItem[], + baseUrl: string +): Section[] { + const sections: Section[] = []; + let currentSection: Section | null = null; + + for (const route of routes) { + // Skip external links + if (route.path?.startsWith('http')) { + continue; + } + + // Start a new section when we hit a section header + if (route.hasSectionHeader && route.sectionHeader) { + if (currentSection) { + sections.push(currentSection); + } + currentSection = { + heading: cleanSectionHeader(route.sectionHeader), + pages: [], + subGroups: [], + }; + continue; + } + + // If no section started yet, skip + if (!currentSection) { + continue; + } + + // Route with children - create a sub-group + if (route.title && route.routes && route.routes.length > 0) { + const subGroup: SubGroup = { + heading: route.title, + pages: [], + }; + + // Include parent page if it has a path + if (route.path) { + subGroup.pages.push({ + title: route.title, + url: `${baseUrl}${route.path}.md`, + }); + } + + // Add child pages + for (const child of route.routes) { + if (child.title && child.path && !child.path.startsWith('http')) { + subGroup.pages.push({ + title: child.title, + url: `${baseUrl}${child.path}.md`, + }); + } + } + + if (subGroup.pages.length > 0) { + currentSection.subGroups.push(subGroup); + } + } + // Single page without children + else if (route.title && route.path) { + currentSection.pages.push({ + title: route.title, + url: `${baseUrl}${route.path}.md`, + }); + } + } + + // Don't forget the last section + if (currentSection) { + sections.push(currentSection); + } + + return sections; +} + +// Extract routes for sidebars that use routes with children as the primary grouping +// (like the Learn sidebar) +function extractGroupedRoutes( + routes: RouteItem[], + baseUrl: string +): SubGroup[] { + const groups: SubGroup[] = []; + + for (const route of routes) { + // Skip section headers + if (route.hasSectionHeader) { + continue; + } + + // Skip external links + if (route.path?.startsWith('http')) { + continue; + } + + // Route with children - create a group + if (route.title && route.routes && route.routes.length > 0) { + const pages: Page[] = []; + + // Include parent page if it has a path + if (route.path) { + pages.push({ + title: route.title, + url: `${baseUrl}${route.path}.md`, + }); + } + + // Add child pages + for (const child of route.routes) { + if (child.title && child.path && !child.path.startsWith('http')) { + pages.push({ + title: child.title, + url: `${baseUrl}${child.path}.md`, + }); + } + } + + if (pages.length > 0) { + groups.push({ + heading: route.title, + pages, + }); + } + } + // Single page without children - group under its own heading + else if (route.title && route.path) { + groups.push({ + heading: route.title, + pages: [ + { + title: route.title, + url: `${baseUrl}${route.path}.md`, + }, + ], + }); + } + } + + return groups; +} + +// Check if sidebar uses section headers as primary grouping +function usesSectionHeaders(routes: RouteItem[]): boolean { + return routes.some((r) => r.hasSectionHeader && r.sectionHeader); +} + +export const getServerSideProps: GetServerSideProps = async ({res}) => { + const subdomain = + siteConfig.languageCode === 'en' ? '' : siteConfig.languageCode + '.'; + const baseUrl = 'https://' + subdomain + 'react.dev'; + + const lines = [ + '# React Documentation', + '', + '> The library for web and native user interfaces.', + ]; + + const sidebars: Sidebar[] = [ + sidebarLearn as Sidebar, + sidebarReference as Sidebar, + ]; + + for (const sidebar of sidebars) { + lines.push(''); + lines.push(`## ${sidebar.title}`); + + if (usesSectionHeaders(sidebar.routes)) { + // API Reference style: section headers define major groups + const sections = extractSectionedRoutes(sidebar.routes, baseUrl); + for (const section of sections) { + if (section.heading) { + lines.push(''); + lines.push(`### ${section.heading}`); + } + + // Output pages directly under section + for (const page of section.pages) { + lines.push(`- [${page.title}](${page.url})`); + } + + // Output sub-groups with #### headings + for (const subGroup of section.subGroups) { + lines.push(''); + lines.push(`#### ${subGroup.heading}`); + for (const page of subGroup.pages) { + lines.push(`- [${page.title}](${page.url})`); + } + } + } + } else { + // Learn style: routes with children define groups + const groups = extractGroupedRoutes(sidebar.routes, baseUrl); + for (const group of groups) { + lines.push(''); + lines.push(`### ${group.heading}`); + for (const page of group.pages) { + lines.push(`- [${page.title}](${page.url})`); + } + } + } + } + + const content = lines.join('\n'); + + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.write(content); + res.end(); + + return {props: {}}; +}; + +export default function LlmsTxt() { + return null; +} diff --git a/src/styles/index.css b/src/styles/index.css index 6b2915be..7bdf4c76 100644 --- a/src/styles/index.css +++ b/src/styles/index.css @@ -741,13 +741,6 @@ ol.mdx-illustration-block { } } -.exit { - opacity: 0; - transition: opacity 500ms ease-out; - transition-delay: 1s; - pointer-events: none; -} - .uwu-visible { display: none; } diff --git a/yarn.lock b/yarn.lock index 7d1dd6d2..6f560474 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1225,10 +1225,10 @@ unist-util-visit "^4.0.0" vfile "^5.0.0" -"@next/env@15.1.11": - version "15.1.11" - resolved "https://registry.yarnpkg.com/@next/env/-/env-15.1.11.tgz#599a126f7ce56decc39cea46668cb60d96b66bc6" - integrity sha512-yp++FVldfLglEG5LoS2rXhGypPyoSOyY0kxZQJ2vnlYJeP8o318t5DrDu5Tqzr03qAhDWllAID/kOCsXNLcwKw== +"@next/env@15.1.12": + version "15.1.12" + resolved "https://registry.yarnpkg.com/@next/env/-/env-15.1.12.tgz#0821510fa71871f1970cd216963d25a5970fe58a" + integrity sha512-EWKXZKsd9ZNn+gLqOtfwH2PQyWuWFmpLldjStw7mZgWgKu56vaqNkAGQrys2g5ER4CNXEDz3Khj2tD1pnsT9Uw== "@next/eslint-plugin-next@12.0.3": version "12.0.3" @@ -5797,12 +5797,12 @@ next-tick@^1.1.0: resolved "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz" integrity sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ== -next@15.1.11: - version "15.1.11" - resolved "https://registry.yarnpkg.com/next/-/next-15.1.11.tgz#8a70a236e02d8dd62fb0569bedfd5e4290e7af55" - integrity sha512-UiVJaOGhKST58AadwbFUZThlNBmYhKqaCs8bVtm4plTxsgKq0mJ0zTsp7t7j/rzsbAEj9WcAMdZCztjByi4EoQ== +next@15.1.12: + version "15.1.12" + resolved "https://registry.yarnpkg.com/next/-/next-15.1.12.tgz#6d308fe6cb295faed724481b57f77b8abf4f5468" + integrity sha512-fClyhVCGTATGYBnETgKAi7YU5+bSwzM5rqNsY3Dg5wBoBMwE0NSvWA3fzwYj0ijl+LMeiV8P2QAnUFpeqDfTgw== dependencies: - "@next/env" "15.1.11" + "@next/env" "15.1.12" "@swc/counter" "0.1.3" "@swc/helpers" "0.5.15" busboy "1.6.0"