diff --git a/.claude/agents/docs-reviewer.md b/.claude/agents/docs-reviewer.md new file mode 100644 index 000000000..af0a856e4 --- /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 000000000..4648ad90d --- /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 000000000..4b75f27a1 --- /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 000000000..0904a98c0 --- /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 000000000..124e5f048 --- /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 000000000..ef28225f8 --- /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 000000000..57dc9ef74 --- /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 000000000..e63c00fca --- /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 000000000..5ebcdee37 --- /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 000000000..61a6a0e05 --- /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 4738cb697..3c83df826 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ scripts plugins next.config.js +.claude/ diff --git a/.github/ISSUE_TEMPLATE/3-framework.yml b/.github/ISSUE_TEMPLATE/3-framework.yml index a47295e1e..87f03a660 100644 --- a/.github/ISSUE_TEMPLATE/3-framework.yml +++ b/.github/ISSUE_TEMPLATE/3-framework.yml @@ -8,11 +8,11 @@ body: value: | ## Apply to be included as a recommended React framework - _This form is for framework authors to apply to be included as a recommended [React framework](https://react.dev/learn/start-a-new-react-project). If you are not a framework author, please contact the authors before submitting._ + _This form is for framework authors to apply to be included as a recommended [React framework](https://react.dev/learn/creating-a-react-app). If you are not a framework author, please contact the authors before submitting._ Our goal when recommending a framework is to start developers with a React project that solves common problems like code splitting, data fetching, routing, and HTML generation without any extra work later. We believe this will allow users to get started quickly with React, and scale their app to production. - While we understand that many frameworks may want to be featured, this page is not a place to advertise every possible React framework or all frameworks that you can add React to. There are many great frameworks that offer support for React that are not listed in our guides. The frameworks we recommend have invested significantly in the React ecosystem, and collaborated with the React team to be compatible with our [full-stack React architecture vision](https://react.dev/learn/start-a-new-react-project#which-features-make-up-the-react-teams-full-stack-architecture-vision). + While we understand that many frameworks may want to be featured, this page is not a place to advertise every possible React framework or all frameworks that you can add React to. There are many great frameworks that offer support for React that are not listed in our guides. The frameworks we recommend have invested significantly in the React ecosystem, and collaborated with the React team to be compatible with our [full-stack React architecture vision](https://react.dev/learn/creating-a-react-app#which-features-make-up-the-react-teams-full-stack-architecture-vision). To be included, frameworks must meet the following criteria: diff --git a/.gitignore b/.gitignore index 99f4615e5..ff88094de 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 000000000..3a081e6d5 --- /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 5a5755307..f8ec196e1 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) { @@ -36,6 +60,14 @@ const nextConfig = { // Don't bundle the shim unnecessarily. config.resolve.alias['use-sync-external-store/shim'] = 'react'; + // ESLint depends on the CommonJS version of esquery, + // but Webpack loads the ESM version by default. This + // alias ensures the correct version is used. + // + // More info: + // https://github.com/reactjs/react.dev/pull/8115 + config.resolve.alias['esquery'] = 'esquery/dist/esquery.min.js'; + const {IgnorePlugin, NormalModuleReplacementPlugin} = require('webpack'); config.plugins.push( new NormalModuleReplacementPlugin( diff --git a/package.json b/package.json index 4376cc18d..10ec29d01 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,11 @@ "classnames": "^2.2.6", "debounce": "^1.2.1", "github-slugger": "^1.3.0", +<<<<<<< HEAD "next": "15.4.8", +======= + "next": "15.1.12", +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 "next-remote-watch": "^1.0.0", "parse-numeric-range": "^1.2.0", "react": "^19.0.0", @@ -63,7 +67,7 @@ "asyncro": "^3.0.0", "autoprefixer": "^10.4.2", "babel-eslint": "10.x", - "babel-plugin-react-compiler": "^19.1.0-rc.3", + "babel-plugin-react-compiler": "^1.0.0", "chalk": "4.1.2", "eslint": "7.x", "eslint-config-next": "12.0.3", diff --git a/plugins/remark-smartypants.js b/plugins/remark-smartypants.js index f56f14b61..c819624ba 100644 --- a/plugins/remark-smartypants.js +++ b/plugins/remark-smartypants.js @@ -14,12 +14,24 @@ const visit = require('unist-util-visit'); const retext = require('retext'); const smartypants = require('retext-smartypants'); -function check(parent) { +function check(node, parent) { + if (node.data?.skipSmartyPants) return false; if (parent.tagName === 'script') return false; if (parent.tagName === 'style') return false; return true; } +function markSkip(node) { + if (!node) return; + node.data ??= {}; + node.data.skipSmartyPants = true; + if (Array.isArray(node.children)) { + for (const child of node.children) { + markSkip(child); + } + } +} + module.exports = function (options) { const processor = retext().use(smartypants, { ...options, @@ -43,8 +55,14 @@ module.exports = function (options) { let startIndex = 0; const textOrInlineCodeNodes = []; + visit(tree, 'mdxJsxFlowElement', (node) => { + if (['TerminalBlock'].includes(node.name)) { + markSkip(node); // Mark all children to skip smarty pants + } + }); + visit(tree, ['text', 'inlineCode'], (node, _, parent) => { - if (check(parent)) { + if (check(node, parent)) { if (node.type === 'text') allText += node.value; // for the case when inlineCode contains just one part of quote: `foo'bar` else allText += 'A'.repeat(node.value.length); diff --git a/public/images/blog/react-foundation/react_foundation_logo.png b/public/images/blog/react-foundation/react_foundation_logo.png new file mode 100644 index 000000000..51c19598f Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_logo.png differ diff --git a/public/images/blog/react-foundation/react_foundation_logo.webp b/public/images/blog/react-foundation/react_foundation_logo.webp new file mode 100644 index 000000000..89efa6027 Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_logo.webp differ diff --git a/public/images/blog/react-foundation/react_foundation_logo_dark.png b/public/images/blog/react-foundation/react_foundation_logo_dark.png new file mode 100644 index 000000000..4aedaf464 Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_logo_dark.png differ diff --git a/public/images/blog/react-foundation/react_foundation_logo_dark.webp b/public/images/blog/react-foundation/react_foundation_logo_dark.webp new file mode 100644 index 000000000..09b48b70d Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_logo_dark.webp differ diff --git a/public/images/blog/react-foundation/react_foundation_member_logos.png b/public/images/blog/react-foundation/react_foundation_member_logos.png new file mode 100644 index 000000000..e83659693 Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_member_logos.png differ diff --git a/public/images/blog/react-foundation/react_foundation_member_logos.webp b/public/images/blog/react-foundation/react_foundation_member_logos.webp new file mode 100644 index 000000000..babb3d57c Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_member_logos.webp differ diff --git a/public/images/blog/react-foundation/react_foundation_member_logos_dark.png b/public/images/blog/react-foundation/react_foundation_member_logos_dark.png new file mode 100644 index 000000000..116e40337 Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_member_logos_dark.png differ diff --git a/public/images/blog/react-foundation/react_foundation_member_logos_dark.webp b/public/images/blog/react-foundation/react_foundation_member_logos_dark.webp new file mode 100644 index 000000000..5fcf38ca9 Binary files /dev/null and b/public/images/blog/react-foundation/react_foundation_member_logos_dark.webp differ diff --git a/public/images/docs/diagrams/19_2_batching_after.dark.png b/public/images/docs/diagrams/19_2_batching_after.dark.png new file mode 100644 index 000000000..29ff14093 Binary files /dev/null and b/public/images/docs/diagrams/19_2_batching_after.dark.png differ diff --git a/public/images/docs/diagrams/19_2_batching_after.png b/public/images/docs/diagrams/19_2_batching_after.png new file mode 100644 index 000000000..0ae652f79 Binary files /dev/null and b/public/images/docs/diagrams/19_2_batching_after.png differ diff --git a/public/images/docs/diagrams/19_2_batching_before.dark.png b/public/images/docs/diagrams/19_2_batching_before.dark.png new file mode 100644 index 000000000..758afceb1 Binary files /dev/null and b/public/images/docs/diagrams/19_2_batching_before.dark.png differ diff --git a/public/images/docs/diagrams/19_2_batching_before.png b/public/images/docs/diagrams/19_2_batching_before.png new file mode 100644 index 000000000..7e260135f Binary files /dev/null and b/public/images/docs/diagrams/19_2_batching_before.png differ diff --git a/public/images/docs/performance-tracks/changed-props.dark.png b/public/images/docs/performance-tracks/changed-props.dark.png new file mode 100644 index 000000000..6709a7ea8 Binary files /dev/null and b/public/images/docs/performance-tracks/changed-props.dark.png differ diff --git a/public/images/docs/performance-tracks/changed-props.png b/public/images/docs/performance-tracks/changed-props.png new file mode 100644 index 000000000..33efe9289 Binary files /dev/null and b/public/images/docs/performance-tracks/changed-props.png differ diff --git a/public/images/docs/performance-tracks/components-effects.dark.png b/public/images/docs/performance-tracks/components-effects.dark.png new file mode 100644 index 000000000..57e3a30b0 Binary files /dev/null and b/public/images/docs/performance-tracks/components-effects.dark.png differ diff --git a/public/images/docs/performance-tracks/components-effects.png b/public/images/docs/performance-tracks/components-effects.png new file mode 100644 index 000000000..ff315b99d Binary files /dev/null and b/public/images/docs/performance-tracks/components-effects.png differ diff --git a/public/images/docs/performance-tracks/components-render.dark.png b/public/images/docs/performance-tracks/components-render.dark.png new file mode 100644 index 000000000..c0608b153 Binary files /dev/null and b/public/images/docs/performance-tracks/components-render.dark.png differ diff --git a/public/images/docs/performance-tracks/components-render.png b/public/images/docs/performance-tracks/components-render.png new file mode 100644 index 000000000..436737767 Binary files /dev/null and b/public/images/docs/performance-tracks/components-render.png differ diff --git a/public/images/docs/performance-tracks/overview.dark.png b/public/images/docs/performance-tracks/overview.dark.png new file mode 100644 index 000000000..07513fe90 Binary files /dev/null and b/public/images/docs/performance-tracks/overview.dark.png differ diff --git a/public/images/docs/performance-tracks/overview.png b/public/images/docs/performance-tracks/overview.png new file mode 100644 index 000000000..835a247cf Binary files /dev/null and b/public/images/docs/performance-tracks/overview.png differ diff --git a/public/images/docs/performance-tracks/scheduler-cascading-update.dark.png b/public/images/docs/performance-tracks/scheduler-cascading-update.dark.png new file mode 100644 index 000000000..beb4512d2 Binary files /dev/null and b/public/images/docs/performance-tracks/scheduler-cascading-update.dark.png differ diff --git a/public/images/docs/performance-tracks/scheduler-cascading-update.png b/public/images/docs/performance-tracks/scheduler-cascading-update.png new file mode 100644 index 000000000..8631c4896 Binary files /dev/null and b/public/images/docs/performance-tracks/scheduler-cascading-update.png differ diff --git a/public/images/docs/performance-tracks/scheduler-update.dark.png b/public/images/docs/performance-tracks/scheduler-update.dark.png new file mode 100644 index 000000000..df252663a Binary files /dev/null and b/public/images/docs/performance-tracks/scheduler-update.dark.png differ diff --git a/public/images/docs/performance-tracks/scheduler-update.png b/public/images/docs/performance-tracks/scheduler-update.png new file mode 100644 index 000000000..79a361d2a Binary files /dev/null and b/public/images/docs/performance-tracks/scheduler-update.png differ diff --git a/public/images/docs/performance-tracks/scheduler.dark.png b/public/images/docs/performance-tracks/scheduler.dark.png new file mode 100644 index 000000000..7e48020f8 Binary files /dev/null and b/public/images/docs/performance-tracks/scheduler.dark.png differ diff --git a/public/images/docs/performance-tracks/scheduler.png b/public/images/docs/performance-tracks/scheduler.png new file mode 100644 index 000000000..1cd07a144 Binary files /dev/null and b/public/images/docs/performance-tracks/scheduler.png differ diff --git a/public/images/docs/performance-tracks/server-overview.dark.png b/public/images/docs/performance-tracks/server-overview.dark.png new file mode 100644 index 000000000..221fb1204 Binary files /dev/null and b/public/images/docs/performance-tracks/server-overview.dark.png differ diff --git a/public/images/docs/performance-tracks/server-overview.png b/public/images/docs/performance-tracks/server-overview.png new file mode 100644 index 000000000..85c7eed27 Binary files /dev/null and b/public/images/docs/performance-tracks/server-overview.png differ diff --git a/src/components/Layout/Feedback.tsx b/src/components/Layout/Feedback.tsx deleted file mode 100644 index fe9272517..000000000 --- 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/HomeContent.js b/src/components/Layout/HomeContent.js index 3cf7d5c2c..f9b785db4 100644 --- a/src/components/Layout/HomeContent.js +++ b/src/components/Layout/HomeContent.js @@ -253,7 +253,7 @@ export function HomeContent() { doesn’t prescribe how to do routing and data fetching. To build an entire app with React, we recommend a full-stack React framework like <Link href="https://nextjs.org">Next.js</Link> or{' '} - <Link href="https://remix.run">Remix</Link>. + <Link href="https://reactrouter.com">React Router</Link>. </Para> </Center> <FullBleed> @@ -270,7 +270,7 @@ export function HomeContent() { <CTA color="gray" icon="framework" - href="/learn/start-a-new-react-project"> + href="/learn/creating-a-react-app"> Get started with a framework </CTA> </div> diff --git a/src/components/Layout/Page.tsx b/src/components/Layout/Page.tsx index 89c25f46f..aa39fe5fc 100644 --- a/src/components/Layout/Page.tsx +++ b/src/components/Layout/Page.tsx @@ -15,7 +15,7 @@ import {useRouter} from 'next/router'; import {SidebarNav} from './SidebarNav'; import {Footer} from './Footer'; import {Toc} from './Toc'; -import SocialBanner from '../SocialBanner'; +// import SocialBanner from '../SocialBanner'; import {DocsPageFooter} from 'components/DocsFooter'; import {Seo} from 'components/Seo'; import PageHeading from 'components/PageHeading'; @@ -142,7 +142,7 @@ export function Page({ /> </Head> )} - <SocialBanner /> + {/* <SocialBanner /> */} <TopNav section={section} routeTree={routeTree} diff --git a/src/components/Layout/Sidebar/SidebarLink.tsx b/src/components/Layout/Sidebar/SidebarLink.tsx index 5c01fefc3..9650e95fa 100644 --- a/src/components/Layout/Sidebar/SidebarLink.tsx +++ b/src/components/Layout/Sidebar/SidebarLink.tsx @@ -24,7 +24,7 @@ interface SidebarLinkProps { selected?: boolean; title: string; level: number; - version?: 'canary' | 'major' | 'experimental'; + version?: 'canary' | 'major' | 'experimental' | 'rc'; icon?: React.ReactNode; isExpanded?: boolean; hideArrow?: boolean; @@ -102,6 +102,12 @@ export function SidebarLink({ className="ms-1 text-gray-30 dark:text-gray-60 inline-block w-3.5 h-3.5 align-[-3px]" /> )} + {version === 'rc' && ( + <IconCanary + title=" - This feature is available in the latest RC version" + className="ms-1 text-gray-30 dark:text-gray-60 inline-block w-3.5 h-3.5 align-[-3px]" + /> + )} </div> {isExpanded != null && !hideArrow && ( diff --git a/src/components/Layout/SidebarNav/SidebarNav.tsx b/src/components/Layout/SidebarNav/SidebarNav.tsx index 77beb4d72..678d483c1 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 148098933..efc90ed2c 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/components/MDX/ExpandableCallout.tsx b/src/components/MDX/ExpandableCallout.tsx index ba93d3e27..5b7491e11 100644 --- a/src/components/MDX/ExpandableCallout.tsx +++ b/src/components/MDX/ExpandableCallout.tsx @@ -24,6 +24,7 @@ type CalloutVariants = | 'wip' | 'canary' | 'experimental' + | 'rc' | 'major' | 'rsc'; @@ -50,6 +51,15 @@ const variantMap = { overlayGradient: 'linear-gradient(rgba(245, 249, 248, 0), rgba(245, 249, 248, 1)', }, + rc: { + title: 'RC', + Icon: IconCanary, + containerClasses: + 'bg-gray-5 dark:bg-gray-60 dark:bg-opacity-20 text-primary dark:text-primary-dark text-lg', + textColor: 'text-gray-60 dark:text-gray-30', + overlayGradient: + 'linear-gradient(rgba(245, 249, 248, 0), rgba(245, 249, 248, 1)', + }, canary: { title: 'Canary', Icon: IconCanary, diff --git a/src/components/MDX/MDXComponents.tsx b/src/components/MDX/MDXComponents.tsx index 7a258370c..a32dad271 100644 --- a/src/components/MDX/MDXComponents.tsx +++ b/src/components/MDX/MDXComponents.tsx @@ -106,6 +106,10 @@ const Canary = ({children}: {children: React.ReactNode}) => ( <ExpandableCallout type="canary">{children}</ExpandableCallout> ); +const RC = ({children}: {children: React.ReactNode}) => ( + <ExpandableCallout type="rc">{children}</ExpandableCallout> +); + const Experimental = ({children}: {children: React.ReactNode}) => ( <ExpandableCallout type="experimental">{children}</ExpandableCallout> ); @@ -533,6 +537,7 @@ export const MDXComponents = { Math, MathI, Note, + RC, Canary, Experimental, ExperimentalBadge, diff --git a/src/components/MDX/Sandpack/runESLint.tsx b/src/components/MDX/Sandpack/runESLint.tsx index a0b835461..667b22d7e 100644 --- a/src/components/MDX/Sandpack/runESLint.tsx +++ b/src/components/MDX/Sandpack/runESLint.tsx @@ -21,13 +21,6 @@ const getCodeMirrorPosition = ( const linter = new Linter(); -// HACK! Eslint requires 'esquery' using `require`, but there's no commonjs interop. -// because of this it tries to run `esquery.parse()`, while there's only `esquery.default.parse()`. -// This hack places the functions in the right place. -const esquery = require('esquery'); -esquery.parse = esquery.default?.parse; -esquery.matches = esquery.default?.matches; - const reactRules = require('eslint-plugin-react-hooks').rules; linter.defineRules({ 'react-hooks/rules-of-hooks': reactRules['rules-of-hooks'], diff --git a/src/components/MDX/Sandpack/template.ts b/src/components/MDX/Sandpack/template.ts index 358c8616e..fa8c9e486 100644 --- a/src/components/MDX/Sandpack/template.ts +++ b/src/components/MDX/Sandpack/template.ts @@ -35,8 +35,8 @@ root.render( eject: 'react-scripts eject', }, dependencies: { - react: '^19.1.0', - 'react-dom': '^19.1.0', + react: '^19.2.1', + 'react-dom': '^19.2.1', 'react-scripts': '^5.0.0', }, }, diff --git a/src/components/MDX/SandpackWithHTMLOutput.tsx b/src/components/MDX/SandpackWithHTMLOutput.tsx index c5149deb9..51d06beaf 100644 --- a/src/components/MDX/SandpackWithHTMLOutput.tsx +++ b/src/components/MDX/SandpackWithHTMLOutput.tsx @@ -56,8 +56,8 @@ export default function formatHTML(markup) { const packageJSON = ` { "dependencies": { - "react": "18.3.0-canary-6db7f4209-20231021", - "react-dom": "18.3.0-canary-6db7f4209-20231021", + "react": "^19.2.1", + "react-dom": "^19.2.1", "react-scripts": "^5.0.0", "html-format": "^1.1.2" }, diff --git a/src/components/MDX/TerminalBlock.tsx b/src/components/MDX/TerminalBlock.tsx index bdcd8e466..0fd0160d6 100644 --- a/src/components/MDX/TerminalBlock.tsx +++ b/src/components/MDX/TerminalBlock.tsx @@ -79,13 +79,15 @@ function TerminalBlock({level = 'info', children}: TerminalBlockProps) { </div> </div> </div> - <div + <pre className="px-8 pt-4 pb-6 text-primary-dark dark:text-primary-dark font-mono text-code whitespace-pre overflow-x-auto" translate="no" dir="ltr"> - <LevelText type={level} /> - {message} - </div> + <code> + <LevelText type={level} /> + {message} + </code> + </pre> </div> ); } diff --git a/src/components/PageHeading.tsx b/src/components/PageHeading.tsx index 760542750..ee92f5e55 100644 --- a/src/components/PageHeading.tsx +++ b/src/components/PageHeading.tsx @@ -19,7 +19,7 @@ import {IconExperimental} from './Icon/IconExperimental'; interface PageHeadingProps { title: string; - version?: 'experimental' | 'canary'; + version?: 'experimental' | 'canary' | 'rc'; experimental?: boolean; status?: string; description?: string; @@ -46,6 +46,12 @@ function PageHeading({ className="ms-4 mt-1 text-gray-50 dark:text-gray-40 inline-block w-6 h-6 align-[-1px]" /> )} + {version === 'rc' && ( + <IconCanary + title=" - This feature is available in the latest RC version" + className="ms-4 mt-1 text-gray-50 dark:text-gray-40 inline-block w-6 h-6 align-[-1px]" + /> + )} {version === 'experimental' && ( <IconExperimental title=" - This feature is available in the latest Experimental version of React" diff --git a/src/content/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023.md b/src/content/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023.md index 1bc78149d..df1fd085d 100644 --- a/src/content/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023.md +++ b/src/content/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023.md @@ -31,7 +31,7 @@ The biggest change is that we introduced [`async` / `await`](https://github.com/ Now that we have data fetching pretty well sorted, we're exploring the other direction: sending data from the client to the server, so that you can execute database mutations and implement forms. We're doing this by letting you pass Server Action functions across the server/client boundary, which the client can then call, providing seamless RPC. Server Actions also give you progressively enhanced forms before JavaScript loads. -React Server Components has shipped in [Next.js App Router](/learn/start-a-new-react-project#nextjs-app-router). This showcases a deep integration of a router that really buys into RSC as a primitive, but it's not the only way to build a RSC-compatible router and framework. There's a clear separation for features provided by the RSC spec and implementation. React Server Components is meant as a spec for components that work across compatible React frameworks. +React Server Components has shipped in [Next.js App Router](/learn/creating-a-react-app#nextjs-app-router). This showcases a deep integration of a router that really buys into RSC as a primitive, but it's not the only way to build a RSC-compatible router and framework. There's a clear separation for features provided by the RSC spec and implementation. React Server Components is meant as a spec for components that work across compatible React frameworks. We generally recommend using an existing framework, but if you need to build your own custom framework, it is possible. Building your own RSC-compatible framework is not as easy as we'd like it to be, mainly due to the deep bundler integration needed. The current generation of bundlers are great for use on the client, but they weren't designed with first-class support for splitting a single module graph between the server and the client. This is why we're now partnering directly with bundler developers to get the primitives for RSC built-in. @@ -92,7 +92,7 @@ Since our last update, we've tested an experimental version of prerendering inte ## Transition Tracing {/*transition-tracing*/} -The Transition Tracing API lets you detect when [React Transitions](/reference/react/useTransition) become slower and investigate why they may be slow. Following our last update, we have completed the initial design of the API and published an [RFC](https://github.com/reactjs/rfcs/pull/238). The basic capabilities have also been implemented. The project is currently on hold. We welcome feedback on the RFC and look forward to resuming its development to provide a better performance measurement tool for React. This will be particularly useful with routers built on top of React Transitions, like the [Next.js App Router](/learn/start-a-new-react-project#nextjs-app-router). +The Transition Tracing API lets you detect when [React Transitions](/reference/react/useTransition) become slower and investigate why they may be slow. Following our last update, we have completed the initial design of the API and published an [RFC](https://github.com/reactjs/rfcs/pull/238). The basic capabilities have also been implemented. The project is currently on hold. We welcome feedback on the RFC and look forward to resuming its development to provide a better performance measurement tool for React. This will be particularly useful with routers built on top of React Transitions, like the [Next.js App Router](/learn/creating-a-react-app#nextjs-app-router). * * * In addition to this update, our team has made recent guest appearances on community podcasts and livestreams to speak more on our work and answer questions. diff --git a/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md b/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md index 9ec330e6b..c3ab47fad 100644 --- a/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md +++ b/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md @@ -15,14 +15,6 @@ In React Labs posts, we write about projects in active research and development. </Intro> -<Note> - -React Conf 2024 is scheduled for May 15–16 in Henderson, Nevada! If you’re interested in attending React Conf in person, you can [sign up for the ticket lottery](https://forms.reform.app/bLaLeE/react-conf-2024-ticket-lottery/1aRQLK) until February 28th. - -For more info on tickets, free streaming, sponsoring, and more, see [the React Conf website](https://conf.react.dev). - -</Note> - --- ## React Compiler {/*react-compiler*/} diff --git a/src/content/blog/2024/05/22/react-conf-2024-recap.md b/src/content/blog/2024/05/22/react-conf-2024-recap.md index 7cb7d42ee..e22464010 100644 --- a/src/content/blog/2024/05/22/react-conf-2024-recap.md +++ b/src/content/blog/2024/05/22/react-conf-2024-recap.md @@ -112,7 +112,7 @@ Thank you [Ricky Hanlon](https://www.youtube.com/watch?v=FxTZL2U-uKg&t=1263s) fo Thank you [Callstack](https://www.callstack.com/) for building the conference website; and to [Kadi Kraman](https://twitter.com/kadikraman) and the [Expo](https://expo.dev/) team for building the conference mobile app. -Thank you to all the sponsors who made the event possible: [Remix](https://remix.run/), [Amazon](https://developer.amazon.com/apps-and-games?cmp=US_2024_05_3P_React-Conf-2024&ch=prtnr&chlast=prtnr&pub=ref&publast=ref&type=org&typelast=org), [MUI](https://mui.com/), [Sentry](https://sentry.io/for/react/?utm_source=sponsored-conf&utm_medium=sponsored-event&utm_campaign=frontend-fy25q2-evergreen&utm_content=logo-reactconf2024-learnmore), [Abbott](https://www.jobs.abbott/software), [Expo](https://expo.dev/), [RedwoodJS](https://redwoodjs.com/), and [Vercel](https://vercel.com). +Thank you to all the sponsors who made the event possible: [Remix](https://remix.run/), [Amazon](https://developer.amazon.com/apps-and-games?cmp=US_2024_05_3P_React-Conf-2024&ch=prtnr&chlast=prtnr&pub=ref&publast=ref&type=org&typelast=org), [MUI](https://mui.com/), [Sentry](https://sentry.io/for/react/?utm_source=sponsored-conf&utm_medium=sponsored-event&utm_campaign=frontend-fy25q2-evergreen&utm_content=logo-reactconf2024-learnmore), [Abbott](https://www.jobs.abbott/software), [Expo](https://expo.dev/), [RedwoodJS](https://rwsdk.com/), and [Vercel](https://vercel.com). Thank you to the AV Team for the visuals, stage, and sound; and to the Westin Hotel for hosting us. diff --git a/src/content/blog/2024/10/21/react-compiler-beta-release.md b/src/content/blog/2024/10/21/react-compiler-beta-release.md index cd49b6eb2..750c0f3b8 100644 --- a/src/content/blog/2024/10/21/react-compiler-beta-release.md +++ b/src/content/blog/2024/10/21/react-compiler-beta-release.md @@ -12,9 +12,9 @@ October 21, 2024 by [Lauren Tan](https://twitter.com/potetotes). <Note> -### React Compiler is now in RC! {/*react-compiler-is-now-in-rc*/} +### React Compiler is now stable! {/*react-compiler-is-now-in-rc*/} -Please see the [RC blog post](/blog/2025/04/21/react-compiler-rc) for details. +Please see the [stable release blog post](/blog/2025/10/07/react-compiler-1) for details. </Note> diff --git a/src/content/blog/2024/12/05/react-19.md b/src/content/blog/2024/12/05/react-19.md index 65bf42757..4e9aad8e8 100644 --- a/src/content/blog/2024/12/05/react-19.md +++ b/src/content/blog/2024/12/05/react-19.md @@ -355,7 +355,7 @@ For more information, see [React DOM Static APIs](/reference/react-dom/static). Server Components are a new option that allows rendering components ahead of time, before bundling, in an environment separate from your client application or SSR server. This separate environment is the "server" in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server. -React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a `react-server` [export condition](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md#react-server-conditional-exports) for use in frameworks that support the [Full-stack React Architecture](/learn/start-a-new-react-project#which-features-make-up-the-react-teams-full-stack-architecture-vision). +React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a `react-server` [export condition](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md#react-server-conditional-exports) for use in frameworks that support the [Full-stack React Architecture](/learn/creating-a-react-app#which-features-make-up-the-react-teams-full-stack-architecture-vision). <Note> diff --git a/src/content/blog/2025/02/14/sunsetting-create-react-app.md b/src/content/blog/2025/02/14/sunsetting-create-react-app.md index 9ced6231c..6f3e95d81 100644 --- a/src/content/blog/2025/02/14/sunsetting-create-react-app.md +++ b/src/content/blog/2025/02/14/sunsetting-create-react-app.md @@ -177,7 +177,7 @@ export default function Dashboard() { } ``` -Fetching in an effect means the user has to wait longer to see the content, even though the data could have been fetched earlier. To solve this, you can use a data fetching library like [React Query](https://react-query.tanstack.com/), [SWR](https://swr.vercel.app/), [Apollo](https://www.apollographql.com/docs/react), or [Relay](https://relay.dev/) which provide options to prefetch data so the request is started before the component renders. +Fetching in an effect means the user has to wait longer to see the content, even though the data could have been fetched earlier. To solve this, you can use a data fetching library like [TanStack Query](https://tanstack.com/query/), [SWR](https://swr.vercel.app/), [Apollo](https://www.apollographql.com/docs/react), or [Relay](https://relay.dev/) which provide options to prefetch data so the request is started before the component renders. These libraries work best when integrated with your routing "loader" pattern to specify data dependencies at the route level, which allows the router to optimize your data fetches: diff --git a/src/content/blog/2025/04/21/react-compiler-rc.md b/src/content/blog/2025/04/21/react-compiler-rc.md deleted file mode 100644 index 2ebbf3bae..000000000 --- a/src/content/blog/2025/04/21/react-compiler-rc.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: "React Compiler RC" -author: Lauren Tan and Mofei Zhang -date: 2025/04/21 -description: We are releasing the compiler's first Release Candidate (RC) today. - ---- - -April 21, 2025 by [Lauren Tan](https://x.com/potetotes) and [Mofei Zhang](https://x.com/zmofei). - ---- - -<Intro> - -The React team is excited to share new updates: - -</Intro> - -1. We're publishing React Compiler RC today, in preparation of the compiler's stable release. -2. We're merging `eslint-plugin-react-compiler` into `eslint-plugin-react-hooks`. -3. We've added support for swc and are working with oxc to support Babel-free builds. - ---- - -[React Compiler](https://react.dev/learn/react-compiler) is a build-time tool that optimizes your React app through automatic memoization. Last year, we published React Compiler’s [first beta](https://react.dev/blog/2024/10/21/react-compiler-beta-release) and received lots of great feedback and contributions. We’re excited about the wins we’ve seen from folks adopting the compiler (see case studies from [Sanity Studio](https://github.com/reactwg/react-compiler/discussions/33) and [Wakelet](https://github.com/reactwg/react-compiler/discussions/52)) and are working towards a stable release. - -We are releasing the compiler's first Release Candidate (RC) today. The RC is intended to be a stable and near-final version of the compiler, and safe to try out in production. - -## Use React Compiler RC today {/*use-react-compiler-rc-today*/} -To install the RC: - -npm -<TerminalBlock> -{`npm install --save-dev --save-exact babel-plugin-react-compiler@rc`} -</TerminalBlock> - -pnpm -<TerminalBlock> -{`pnpm add --save-dev --save-exact babel-plugin-react-compiler@rc`} -</TerminalBlock> - -yarn -<TerminalBlock> -{`yarn add --dev --exact babel-plugin-react-compiler@rc`} -</TerminalBlock> - -As part of the RC, we've been making React Compiler easier to add to your projects and added optimizations to how the compiler generates memoization. React Complier now supports optional chains and array indices as dependencies. We're exploring how to infer even more dependencies like equality checks and string interpolation. These improvements ultimately result in fewer re-renders and more responsive UIs. - -We have also heard from the community that the ref-in-render validation sometimes has false positives. Since as a general philosophy we want you to be able to fully trust in the compiler's error messages and hints, we are turning it off by default for now. We will keep working to improve this validation, and we will re-enable it in a follow up release. - -You can find more details on using the Compiler in [our docs](https://react.dev/learn/react-compiler). - -## Feedback {/*feedback*/} -During the RC period, we encourage all React users to try the compiler and provide feedback in the React repo. Please [open an issue](https://github.com/facebook/react/issues) if you encounter any bugs or unexpected behavior. If you have a general question or suggestion, please post them in the [React Compiler Working Group](https://github.com/reactwg/react-compiler/discussions). - -## Backwards Compatibility {/*backwards-compatibility*/} -As noted in the Beta announcement, React Compiler is compatible with React 17 and up. If you are not yet on React 19, you can use React Compiler by specifying a minimum target in your compiler config, and adding `react-compiler-runtime` as a dependency. You can find docs on this [here](https://react.dev/learn/react-compiler#using-react-compiler-with-react-17-or-18). - -## Migrating from eslint-plugin-react-compiler to eslint-plugin-react-hooks {/*migrating-from-eslint-plugin-react-compiler-to-eslint-plugin-react-hooks*/} -If you have already installed eslint-plugin-react-compiler, you can now remove it and use `eslint-plugin-react-hooks@rc`. Many thanks to [@michaelfaith](https://bsky.app/profile/michael.faith) for contributing to this improvement! - -To install: - -npm -<TerminalBlock> -{`npm install --save-dev eslint-plugin-react-hooks@rc`} -</TerminalBlock> - -pnpm -<TerminalBlock> -{`pnpm add --save-dev eslint-plugin-react-hooks@rc`} -</TerminalBlock> - -yarn -<TerminalBlock> -{`yarn add --dev eslint-plugin-react-hooks@rc`} -</TerminalBlock> - -```js -// eslint.config.js -import * as reactHooks from 'eslint-plugin-react-hooks'; - -export default [ - // Flat Config (eslint 9+) - reactHooks.configs.recommended, - - // Legacy Config - reactHooks.configs['recommended-latest'] -]; -``` - -To enable the React Compiler rule, add `'react-hooks/react-compiler': 'error'` to your ESLint configuration. - -The linter does not require the compiler to be installed, so there's no risk in upgrading eslint-plugin-react-hooks. We recommend everyone upgrade today. - -## swc support (experimental) {/*swc-support-experimental*/} -React Compiler can be installed across [several build tools](/learn/react-compiler#installation) such as Babel, Vite, and Rsbuild. - -In addition to those tools, we have been collaborating with Kang Dongyoon ([@kdy1dev](https://x.com/kdy1dev)) from the [swc](https://swc.rs/) team on adding additional support for React Compiler as an swc plugin. While this work isn't done, Next.js build performance should now be considerably faster when the [React Compiler is enabled in your Next.js app](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler). - -We recommend using Next.js [15.3.1](https://github.com/vercel/next.js/releases/tag/v15.3.1) or greater to get the best build performance. - -Vite users can continue to use [vite-plugin-react](https://github.com/vitejs/vite-plugin-react) to enable the compiler, by adding it as a [Babel plugin](https://react.dev/learn/react-compiler#usage-with-vite). We are also working with the [oxc](https://oxc.rs/) team to [add support for the compiler](https://github.com/oxc-project/oxc/issues/10048). Once [rolldown](https://github.com/rolldown/rolldown) is officially released and supported in Vite and oxc support is added for React Compiler, we'll update the docs with information on how to migrate. - -## Upgrading React Compiler {/*upgrading-react-compiler*/} -React Compiler works best when the auto-memoization applied is strictly for performance. Future versions of the compiler may change how memoization is applied, for example it could become more granular and precise. - -However, because product code may sometimes break the [rules of React](https://react.dev/reference/rules) in ways that aren't always statically detectable in JavaScript, changing memoization can occasionally have unexpected results. For example, a previously memoized value might be used as a dependency for a useEffect somewhere in the component tree. Changing how or whether this value is memoized can cause over or under-firing of that useEffect. While we encourage [useEffect only for synchronization](https://react.dev/learn/synchronizing-with-effects), your codebase may have useEffects that cover other use-cases such as effects that needs to only run in response to specific values changing. - -In other words, changing memoization may under rare circumstances cause unexpected behavior. For this reason, we recommend following the Rules of React and employing continuous end-to-end testing of your app so you can upgrade the compiler with confidence and identify any rules of React violations that might cause issues. - -If you don't have good test coverage, we recommend pinning the compiler to an exact version (eg `19.1.0`) rather than a SemVer range (eg `^19.1.0`). You can do this by passing the `--save-exact` (npm/pnpm) or `--exact` flags (yarn) when upgrading the compiler. You should then do any upgrades of the compiler manually, taking care to check that your app still works as expected. - -## Roadmap to Stable {/*roadmap-to-stable*/} -*This is not a final roadmap, and is subject to change.* - -After a period of final feedback from the community on the RC, we plan on a Stable Release for the compiler. - -* βœ… Experimental: Released at React Conf 2024, primarily for feedback from application developers. -* βœ… Public Beta: Available today, for feedback from library authors. -* βœ… Release Candidate (RC): React Compiler works for the majority of rule-following apps and libraries without issue. -* General Availability: After final feedback period from the community. - -Post-Stable, we plan to add more compiler optimizations and improvements. This includes both continual improvements to automatic memoization, and new optimizations altogether, with minimal to no change of product code. Each upgrade will continue to improve performance and add better handling of diverse JavaScript and React patterns. - ---- - -Thanks to [Joe Savona](https://x.com/en_JS), [Jason Bonta](https://x.com/someextent), [Jimmy Lai](https://x.com/feedthejim), and [Kang Dongyoon](https://x.com/kdy1dev) (@kdy1dev) for reviewing and editing this post. diff --git a/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md b/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md index c7f740091..9b6095f8b 100644 --- a/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md +++ b/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md @@ -16,16 +16,6 @@ In React Labs posts, we write about projects in active research and development. </Intro> -<Note> - -React Conf 2025 is scheduled for October 7–8 in Henderson, Nevada! - -We're looking for speakers to help us create talks about the features covered in this post. If you're interested in speaking at ReactConf, [please apply here](https://forms.reform.app/react-conf/call-for-speakers/) (no talk proposal required). - -For more info on tickets, free streaming, sponsoring, and more, see [the React Conf website](https://conf.react.dev). - -</Note> - Today, we're excited to release documentation for two new experimental features that are ready for testing: - [View Transitions](#view-transitions) @@ -42,6 +32,14 @@ We're also sharing updates on new features currently in development: # New Experimental Features {/*new-experimental-features*/} +<Note> + +`<Activity />` has shipped in `react@19.2`. + +`<ViewTransition />` and `addTransitionType` are now available in `react@canary`. + +</Note> + View Transitions and Activity are now ready for testing in `react@experimental`. These features have been tested in production and are stable, but the final API may still change as we incorporate feedback. You can try them by upgrading React packages to the most recent experimental version: @@ -68,7 +66,7 @@ To opt-in to animating an element, wrap it in the new `<ViewTransition>` compone </ViewTransition> ``` -This new component lets you declaratively define "what" to animate when an animation is activated. +This new component lets you declaratively define "what" to animate when an animation is activated. You can define "when" to animate by using one of these three triggers for a View Transition: @@ -101,9 +99,9 @@ By default, these animations use the [default CSS animations for View Transition When the DOM updates due to an animation trigger—like `startTransition`, `useDeferredValue`, or a `Suspense` fallback switching to content—React will use [declarative heuristics](/reference/react/ViewTransition#viewtransition) to automatically determine which `<ViewTransition>` components to activate for the animation. The browser will then run the animation that's defined in CSS. -If you're familiar with the browser's View Transition API and want to know how React supports it, check out [How does `<ViewTransition>` Work](/reference/react/ViewTransition#how-does-viewtransition-work) in the docs. +If you're familiar with the browser's View Transition API and want to know how React supports it, check out [How does `<ViewTransition>` Work](/reference/react/ViewTransition#how-does-viewtransition-work) in the docs. -In this post, let's take a look at a few examples of how to use View Transitions. +In this post, let's take a look at a few examples of how to use View Transitions. We'll start with this app, which doesn't animate any of the following interactions: - Click a video to view the details. @@ -1247,8 +1245,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -1296,16 +1294,17 @@ function navigate(url) { When the `url` changes, the `<ViewTransition>` and new route are rendered. Since the `<ViewTransition>` was updated inside of `startTransition`, the `<ViewTransition>` is activated for an animation. -By default, View Transitions include the browser default cross-fade animation. Adding this to our example, we now have a cross-fade whenever we navigate between pages: +By default, View Transitions include the browser default cross-fade animation. Adding this to our example, we now have a cross-fade whenever we navigate between pages: <Sandpack> ```js src/App.js active -import {unstable_ViewTransition as ViewTransition} from 'react'; import Details from './Details'; import Home from './Home'; import {useRouter} from './router'; +import {ViewTransition} from 'react'; import Details from './Details'; +import Home from './Home'; import {useRouter} from './router'; export default function App() { const {url} = useRouter(); - + // Use ViewTransition to animate between pages. // No additional CSS needed by default. return ( @@ -1564,11 +1563,11 @@ export function IconSearch(props) { ``` ```js src/Layout.js -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); - + return ( <div className="page"> <div className="top"> @@ -1772,22 +1771,22 @@ import {useState, createContext,use,useTransition,useLayoutEffect,useEffect} fro export function Router({ children }) { const [isPending, startTransition] = useTransition(); - + function navigate(url) { // Update router state in transition. startTransition(() => { go(url); }); } - - - - + + + + const [routerState, setRouterState] = useState({ pendingNav: () => {}, url: document.location.pathname, }); - + function go(url) { setRouterState({ @@ -1797,7 +1796,7 @@ export function Router({ children }) { }, }); } - + function navigateBack(url) { startTransition(() => { @@ -2443,8 +2442,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -2458,7 +2457,7 @@ root.render( </Sandpack> -Since our router already updates the route using `startTransition`, this one line change to add `<ViewTransition>` activates with the default cross-fade animation. +Since our router already updates the route using `startTransition`, this one line change to add `<ViewTransition>` activates with the default cross-fade animation. If you're curious how this works, see the docs for [How does `<ViewTransition>` work?](/reference/react/ViewTransition#how-does-viewtransition-work) @@ -2466,7 +2465,7 @@ If you're curious how this works, see the docs for [How does `<ViewTransition>` #### Opting out of `<ViewTransition>` animations {/*opting-out-of-viewtransition-animations*/} -In this example, we're wrapping the root of the app in `<ViewTransition>` for simplicity, but this means that all transitions in the app will be animated, which can lead to unexpected animations. +In this example, we're wrapping the root of the app in `<ViewTransition>` for simplicity, but this means that all transitions in the app will be animated, which can lead to unexpected animations. To fix, we're wrapping route children with `"none"` so each page can control its own animation: @@ -2477,7 +2476,7 @@ To fix, we're wrapping route children with `"none"` so each page can control its </ViewTransition> ``` -In practice, navigations should be done via "enter" and "exit" props, or by using Transition Types. +In practice, navigations should be done via "enter" and "exit" props, or by using Transition Types. </Note> @@ -2512,7 +2511,7 @@ Now, the cross fade is slower: <Sandpack> ```js src/App.js active -import { unstable_ViewTransition as ViewTransition } from "react"; +import { ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; @@ -2778,7 +2777,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); @@ -3671,8 +3670,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -3705,7 +3704,7 @@ Now the video thumbnail animates between the two pages: <Sandpack> ```js src/App.js -import { unstable_ViewTransition as ViewTransition } from "react"; +import { ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; @@ -3972,7 +3971,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); @@ -4029,7 +4028,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js active -import { useState, unstable_ViewTransition as ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react"; export function Thumbnail({ video, children }) { // Add a name to animate with a shared element transition. @@ -4880,8 +4879,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -4962,7 +4961,7 @@ Now we can animate the header along with thumbnail based on navigation type: <Sandpack> ```js src/App.js hidden -import { unstable_ViewTransition as ViewTransition } from "react"; +import { ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; @@ -5227,7 +5226,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js active -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); @@ -5291,7 +5290,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js hidden -import { useState, unstable_ViewTransition as ViewTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; @@ -5442,11 +5441,11 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); - + function navigate(url) { startTransition(() => { // Transition type for the cause "nav forward" @@ -5473,7 +5472,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -6196,8 +6195,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -6213,7 +6212,7 @@ root.render( ### Animating Suspense Boundaries {/*animating-suspense-boundaries*/} -Suspense will also activate View Transitions. +Suspense will also activate View Transitions. To animate the fallback to content, we can wrap `Suspense` with `<ViewTranstion>`: @@ -6230,7 +6229,7 @@ By adding this, the fallback will cross-fade into the content. Click a video and <Sandpack> ```js src/App.js hidden -import { unstable_ViewTransition as ViewTransition } from "react"; +import { ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; @@ -6248,7 +6247,7 @@ export default function App() { ``` ```js src/Details.js active -import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; +import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; function VideoDetails({ id }) { // Cross-fade the fallback to content. @@ -6498,7 +6497,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { @@ -6563,7 +6562,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js hidden -import { useState, unstable_ViewTransition as ViewTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; @@ -6714,7 +6713,7 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js hidden -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); @@ -6742,7 +6741,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -7494,8 +7493,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -7528,7 +7527,7 @@ We can also provide custom animations using an `exit` on the fallback, and `ente Here's how we'll define `slide-down` and `slide-up` with CSS: ```css {1, 6} -::view-transition-old(.slide-down) { +::view-transition-old(.slide-down) { /* Slide the fallback down */ animation: ...; } @@ -7544,7 +7543,7 @@ Now, the Suspense content replaces the fallback with a sliding animation: <Sandpack> ```js src/App.js hidden -import { unstable_ViewTransition as ViewTransition } from "react"; +import { ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; @@ -7562,7 +7561,7 @@ export default function App() { ``` ```js src/Details.js active -import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; +import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; function VideoDetails({ id }) { return ( @@ -7819,7 +7818,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { @@ -7884,7 +7883,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js hidden -import { useState, unstable_ViewTransition as ViewTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; @@ -8035,7 +8034,7 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js hidden -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); @@ -8063,7 +8062,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -8815,8 +8814,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -8858,7 +8857,7 @@ Now the items animate as you type in the search bar: <Sandpack> ```js src/App.js hidden -import { unstable_ViewTransition as ViewTransition } from "react"; +import { ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; @@ -8876,7 +8875,7 @@ export default function App() { ``` ```js src/Details.js hidden -import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; +import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; @@ -8951,17 +8950,17 @@ function VideoInfo({ id }) { ``` ```js src/Home.js -import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; +import { useId, useState, use, useDeferredValue, ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; function SearchList({searchText, videos}) { - // Activate with useDeferredValue ("when") + // Activate with useDeferredValue ("when") const deferredSearchText = useDeferredValue(searchText); const filteredVideos = filterVideos(videos, deferredSearchText); return ( <div className="video-list"> <div className="videos"> {filteredVideos.map((video) => ( - // Animate each item in list ("what") + // Animate each item in list ("what") <ViewTransition key={video.id}> <Video video={video} /> </ViewTransition> @@ -8978,7 +8977,7 @@ export default function Home() { const videos = use(fetchVideos()); const count = videos.length; const [searchText, setSearchText] = useState(''); - + return ( <Layout heading={<div className="fit">{count} Videos</div>}> <SearchInput value={searchText} onChange={setSearchText} /> @@ -9146,7 +9145,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { @@ -9211,7 +9210,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js hidden -import { useState, unstable_ViewTransition as ViewTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; @@ -9362,7 +9361,7 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js hidden -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); @@ -9390,7 +9389,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -10156,8 +10155,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -10182,7 +10181,7 @@ Let's remove the slow fade, and take a look at the final result: <Sandpack> ```js src/App.js -import {unstable_ViewTransition as ViewTransition} from 'react'; import Details from './Details'; import Home from './Home'; import {useRouter} from './router'; +import {ViewTransition} from 'react'; import Details from './Details'; import Home from './Home'; import {useRouter} from './router'; export default function App() { const {url} = useRouter(); @@ -10197,7 +10196,7 @@ export default function App() { ``` ```js src/Details.js -import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; +import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; function VideoDetails({id}) { // Animate from Suspense fallback to content @@ -10267,17 +10266,17 @@ function VideoInfo({ id }) { ``` ```js src/Home.js -import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; +import { useId, useState, use, useDeferredValue, ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; function SearchList({searchText, videos}) { - // Activate with useDeferredValue ("when") + // Activate with useDeferredValue ("when") const deferredSearchText = useDeferredValue(searchText); const filteredVideos = filterVideos(videos, deferredSearchText); return ( <div className="video-list"> <div className="videos"> {filteredVideos.map((video) => ( - // Animate each item in list ("what") + // Animate each item in list ("what") <ViewTransition key={video.id}> <Video video={video} /> </ViewTransition> @@ -10294,7 +10293,7 @@ export default function Home() { const videos = use(fetchVideos()); const count = videos.length; const [searchText, setSearchText] = useState(''); - + return ( <Layout heading={<div className="fit">{count} Videos</div>}> <SearchInput value={searchText} onChange={setSearchText} /> @@ -10462,7 +10461,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); @@ -10526,7 +10525,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js -import { useState, unstable_ViewTransition as ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react"; export function Thumbnail({ video, children }) { // Add a name to animate with a shared element transition. @@ -10674,7 +10673,7 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); @@ -10694,7 +10693,7 @@ export function Router({ children }) { } const [routerState, setRouterState] = useState({pendingNav: () => {}, url: document.location.pathname}); - + function go(url) { setRouterState({ url, @@ -10703,7 +10702,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -11442,8 +11441,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -11508,7 +11507,7 @@ When a user navigates away from a page, it's common to stop rendering the old pa ```js {6,7} function App() { const { url } = useRouter(); - + return ( <> {url === '/' && <Home />} @@ -11525,7 +11524,7 @@ Activity allows you to keep the state around as the user changes pages, so when ```js {6-8} function App() { const { url } = useRouter(); - + return ( <> <Activity mode={url === '/' ? 'visible' : 'hidden'}> @@ -11544,11 +11543,11 @@ Try searching for a video, selecting it, and clicking "back": <Sandpack> ```js src/App.js -import { unstable_ViewTransition as ViewTransition, unstable_Activity as Activity } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; +import { Activity, ViewTransition } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; export default function App() { const { url } = useRouter(); - + return ( // View Transitions know about Activity <ViewTransition> @@ -11563,7 +11562,7 @@ export default function App() { ``` ```js src/Details.js hidden -import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; +import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; @@ -11638,10 +11637,10 @@ function VideoInfo({ id }) { ``` ```js src/Home.js hidden -import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; +import { useId, useState, use, useDeferredValue, ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; function SearchList({searchText, videos}) { - // Activate with useDeferredValue ("when") + // Activate with useDeferredValue ("when") const deferredSearchText = useDeferredValue(searchText); const filteredVideos = filterVideos(videos, deferredSearchText); return ( @@ -11651,7 +11650,7 @@ function SearchList({searchText, videos}) { )} <div className="videos"> {filteredVideos.map((video) => ( - // Animate each item in list ("what") + // Animate each item in list ("what") <ViewTransition key={video.id}> <Video video={video} /> </ViewTransition> @@ -11665,7 +11664,7 @@ export default function Home() { const videos = use(fetchVideos()); const count = videos.length; const [searchText, setSearchText] = useState(''); - + return ( <Layout heading={<div className="fit">{count} Videos</div>}> <SearchInput value={searchText} onChange={setSearchText} /> @@ -11833,7 +11832,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); @@ -11897,7 +11896,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js hidden -import { useState, unstable_ViewTransition as ViewTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; @@ -12048,7 +12047,7 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js hidden -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); @@ -12076,7 +12075,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -12841,8 +12840,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -12881,13 +12880,13 @@ With this update, if the content on the next page has time to pre-render, it wil <Sandpack> ```js src/App.js -import { unstable_ViewTransition as ViewTransition, unstable_Activity as Activity, use } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; import {fetchVideos} from './data' +import { Activity, ViewTransition, use } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; import {fetchVideos} from './data'; export default function App() { const { url } = useRouter(); const videoId = url.split("/").pop(); const videos = use(fetchVideos()); - + return ( <ViewTransition> {/* Render videos in Activity to pre-render them */} @@ -12905,7 +12904,7 @@ export default function App() { ``` ```js src/Details.js -import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; +import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; function VideoDetails({id}) { // Animate from Suspense fallback to content. @@ -12976,10 +12975,10 @@ function VideoInfo({ id }) { ``` ```js src/Home.js hidden -import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; +import { useId, useState, use, useDeferredValue, ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; function SearchList({searchText, videos}) { - // Activate with useDeferredValue ("when") + // Activate with useDeferredValue ("when") const deferredSearchText = useDeferredValue(searchText); const filteredVideos = filterVideos(videos, deferredSearchText); return ( @@ -12989,7 +12988,7 @@ function SearchList({searchText, videos}) { )} <div className="videos"> {filteredVideos.map((video) => ( - // Animate each item in list ("what") + // Animate each item in list ("what") <ViewTransition key={video.id}> <Video video={video} /> </ViewTransition> @@ -13003,7 +13002,7 @@ export default function Home() { const videos = use(fetchVideos()); const count = videos.length; const [searchText, setSearchText] = useState(''); - + return ( <Layout heading={<div className="fit">{count} Videos</div>}> <SearchInput value={searchText} onChange={setSearchText} /> @@ -13171,7 +13170,7 @@ export function IconSearch(props) { ``` ```js src/Layout.js hidden -import {unstable_ViewTransition as ViewTransition} from 'react'; import { useIsNavPending } from "./router"; +import {ViewTransition} from 'react'; import { useIsNavPending } from "./router"; export default function Page({ heading, children }) { const isPending = useIsNavPending(); @@ -13235,7 +13234,7 @@ export default function LikeButton({video}) { ``` ```js src/Videos.js hidden -import { useState, unstable_ViewTransition as ViewTransition } from "react"; +import { useState, ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; @@ -13386,7 +13385,7 @@ export function fetchVideoDetails(id) { ``` ```js src/router.js hidden -import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, unstable_addTransitionType as addTransitionType} from "react"; +import {useState, createContext, use, useTransition, useLayoutEffect, useEffect, addTransitionType} from "react"; export function Router({ children }) { const [isPending, startTransition] = useTransition(); @@ -13414,7 +13413,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -14179,8 +14178,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -14220,13 +14219,13 @@ These are areas we're still exploring, and we'll share more as we make progress. # Features in development {/*features-in-development*/} -We're also developing features to help solve the common problems below. +We're also developing features to help solve the common problems below. -As we iterate on possible solutions, you may see some potential APIs we're testing being shared based on the PRs we are landing. Please keep in mind that as we try different ideas, we often change or remove different solutions after trying them out. +As we iterate on possible solutions, you may see some potential APIs we're testing being shared based on the PRs we are landing. Please keep in mind that as we try different ideas, we often change or remove different solutions after trying them out. -When the solutions we're working on are shared too early, it can create churn and confusion in the community. To balance being transparent and limiting confusion, we're sharing the problems we're currently developing solutions for, without sharing a particular solution we have in mind. +When the solutions we're working on are shared too early, it can create churn and confusion in the community. To balance being transparent and limiting confusion, we're sharing the problems we're currently developing solutions for, without sharing a particular solution we have in mind. -As these features progress, we'll announce them on the blog with docs included so you can try them out. +As these features progress, we'll announce them on the blog with docs included so you can try them out. ## React Performance Tracks {/*react-performance-tracks*/} @@ -14259,7 +14258,7 @@ When we released hooks, we had three motivations: - **Think in terms of function, not lifecycles**: hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods. - **Support ahead-of-time compilation**: hooks were designed to support ahead-of-time compilation with less pitfalls causing unintentional de-optimizations caused by lifecycle methods, and limitations of classes. -Since their release, hooks have been successful at *sharing code between components*. Hooks are now the favored way to share logic between components, and there are less use cases for render props and higher order components. Hooks have also been successful at supporting features like Fast Refresh that were not possible with class components. +Since their release, hooks have been successful at *sharing code between components*. Hooks are now the favored way to share logic between components, and there are less use cases for render props and higher order components. Hooks have also been successful at supporting features like Fast Refresh that were not possible with class components. ### Effects can be hard {/*effects-can-be-hard*/} @@ -14300,18 +14299,18 @@ useEffect(() => { return () => { connection.disconnect(); }; -}); // compiler inserted dependencies. +}); // compiler inserted dependencies. ``` -With this code, the React Compiler can infer the dependencies for you and insert them automatically so you don't need to see or write them. With features like [the IDE extension](#compiler-ide-extension) and [`useEffectEvent`](/reference/react/experimental_useEffectEvent), we can provide a CodeLens to show you what the Compiler inserted for times you need to debug, or to optimize by removing a dependency. This helps reinforce the correct mental model for writing Effects, which can run at any time to synchronize your component or hook's state with something else. +With this code, the React Compiler can infer the dependencies for you and insert them automatically so you don't need to see or write them. With features like [the IDE extension](#compiler-ide-extension) and [`useEffectEvent`](/reference/react/useEffectEvent), we can provide a CodeLens to show you what the Compiler inserted for times you need to debug, or to optimize by removing a dependency. This helps reinforce the correct mental model for writing Effects, which can run at any time to synchronize your component or hook's state with something else. -Our hope is that automatically inserting dependencies is not only easier to write, but that it also makes them easier to understand by forcing you to think in terms of what the Effect does, and not in component lifecycles. +Our hope is that automatically inserting dependencies is not only easier to write, but that it also makes them easier to understand by forcing you to think in terms of what the Effect does, and not in component lifecycles. --- ## Compiler IDE Extension {/*compiler-ide-extension*/} -Earlier this week [we shared](/blog/2025/04/21/react-compiler-rc) the React Compiler release candidate, and we're working towards shipping the first SemVer stable version of the compiler in the coming months. +Later in 2025 [we shared](/blog/2025/10/07/react-compiler-1) the first stable release of React Compiler, and we're continuing to invest in shipping more improvements. We've also begun exploring ways to use the React Compiler to provide information that can improve understanding and debugging your code. One idea we've started exploring is a new experimental LSP-based React IDE extension powered by React Compiler, similar to the extension used in [Lauren Tan's React Conf talk](https://conf2024.react.dev/talks/5). @@ -14333,7 +14332,7 @@ Fragment refs are still being researched. We'll share more when we're closer to ## Gesture Animations {/*gesture-animations*/} -We're also researching ways to enhance View Transitions to support gesture animations such as swiping to open a menu, or scroll through a photo carousel. +We're also researching ways to enhance View Transitions to support gesture animations such as swiping to open a menu, or scroll through a photo carousel. Gestures present new challenges for a few reasons: @@ -14357,9 +14356,9 @@ Now that React 19 has shipped, we're revisiting this problem space to create a p const value = use(store); ``` -Our goal is to allow external state to be read during render without tearing, and to work seamlessly with all of the concurrent features React offers. +Our goal is to allow external state to be read during render without tearing, and to work seamlessly with all of the concurrent features React offers. -This research is still early. We'll share more, and what the new APIs will look like, when we're further along. +This research is still early. We'll share more, and what the new APIs will look like, when we're further along. --- diff --git a/src/content/blog/2025/10/01/react-19-2.md b/src/content/blog/2025/10/01/react-19-2.md new file mode 100644 index 000000000..51c30f70a --- /dev/null +++ b/src/content/blog/2025/10/01/react-19-2.md @@ -0,0 +1,339 @@ +--- +title: "React 19.2" +author: The React Team +date: 2025/10/01 +description: React 19.2 adds new features like Activity, React Performance Tracks, useEffectEvent, and more. +--- + +October 1, 2025 by [The React Team](/community/team) + +--- + +<Intro> + +React 19.2 is now available on npm! + +</Intro> + +This is our third release in the last year, following React 19 in December and React 19.1 in June. In this post, we'll give an overview of the new features in React 19.2, and highlight some notable changes. + +<InlineToc /> + +--- + +## New React Features {/*new-react-features*/} + +### `<Activity />` {/*activity*/} + +`<Activity>` lets you break your app into "activities" that can be controlled and prioritized. + +You can use Activity as an alternative to conditionally rendering parts of your app: + +```js +// Before +{isVisible && <Page />} + +// After +<Activity mode={isVisible ? 'visible' : 'hidden'}> + <Page /> +</Activity> +``` + +In React 19.2, Activity supports two modes: `visible` and `hidden`. + +- `hidden`: hides the children, unmounts effects, and defers all updates until React has nothing left to work on. +- `visible`: shows the children, mounts effects, and allows updates to be processed normally. + +This means you can pre-render and keep rendering hidden parts of the app without impacting the performance of anything visible on screen. + +You can use Activity to render hidden parts of the app that a user is likely to navigate to next, or to save the state of parts the user navigates away from. This helps make navigations quicker by loading data, css, and images in the background, and allows back navigations to maintain state such as input fields. + +In the future, we plan to add more modes to Activity for different use cases. + +For examples on how to use Activity, check out the [Activity docs](/reference/react/Activity). + +--- + +### `useEffectEvent` {/*use-effect-event*/} + +One common pattern with `useEffect` is to notify the app code about some kind of "events" from an external system. For example, when a chat room gets connected, you might want to display a notification: + +```js {5,11} +function ChatRoom({ roomId, theme }) { + useEffect(() => { + const connection = createConnection(serverUrl, roomId); + connection.on('connected', () => { + showNotification('Connected!', theme); + }); + connection.connect(); + return () => { + connection.disconnect() + }; + }, [roomId, theme]); + // ... +``` + +The problem with the code above is that a change to any values used inside such an "event" will cause the surrounding Effect to re-run. For example, changing the `theme` will cause the chat room to reconnect. This makes sense for values related to the Effect logic itself, like `roomId`, but it doesn't make sense for `theme`. + +To solve this, most users just disable the lint rule and exclude the dependency. But that can lead to bugs since the linter can no longer help you keep the dependencies up to date if you need to update the Effect later. + +With `useEffectEvent`, you can split the "event" part of this logic out of the Effect that emits it: + +```js {2,3,4,9} +function ChatRoom({ roomId, theme }) { + const onConnected = useEffectEvent(() => { + showNotification('Connected!', theme); + }); + + useEffect(() => { + const connection = createConnection(serverUrl, roomId); + connection.on('connected', () => { + onConnected(); + }); + connection.connect(); + return () => connection.disconnect(); + }, [roomId]); // βœ… All dependencies declared (Effect Events aren't dependencies) + // ... +``` + +Similar to DOM events, Effect Events always β€œsee” the latest props and state. + +**Effect Events should _not_ be declared in the dependency array**. You'll need to upgrade to `eslint-plugin-react-hooks@latest` so that the linter doesn't try to insert them as dependencies. Note that Effect Events can only be declared in the same component or Hook as "their" Effect. These restrictions are verified by the linter. + +<Note> + +#### When to use `useEffectEvent` {/*when-to-use-useeffectevent*/} + +You should use `useEffectEvent` for functions that are conceptually "events" that happen to be fired from an Effect instead of a user event (that's what makes it an "Effect Event"). You don't need to wrap everything in `useEffectEvent`, or to use it just to silence the lint error, as this can lead to bugs. + +For a deep dive on how to think about Event Effects, see: [Separating Events from Effects](/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects). + +</Note> + +--- + +### `cacheSignal` {/*cache-signal*/} + +<RSC> + +`cacheSignal` is only for use with [React Server Components](/reference/rsc/server-components). + +</RSC> + +`cacheSignal` allows you to know when the [`cache()`](/reference/react/cache) lifetime is over: + +``` +import {cache, cacheSignal} from 'react'; +const dedupedFetch = cache(fetch); + +async function Component() { + await dedupedFetch(url, { signal: cacheSignal() }); +} +``` + +This allows you to clean up or abort work when the result will no longer be used in the cache, such as: + +- React has successfully completed rendering +- The render was aborted +- The render has failed + +For more info, see the [`cacheSignal` docs](/reference/react/cacheSignal). + +--- + +### Performance Tracks {/*performance-tracks*/} + +React 19.2 adds a new set of [custom tracks](https://developer.chrome.com/docs/devtools/performance/extension) to Chrome DevTools performance profiles to provide more information about the performance of your React app: + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <picture > + <source srcset="/images/blog/react-labs-april-2025/perf_tracks.png" /> + <img className="w-full light-image" src="/images/blog/react-labs-april-2025/perf_tracks.webp" /> + </picture> + <picture > + <source srcset="/images/blog/react-labs-april-2025/perf_tracks_dark.png" /> + <img className="w-full dark-image" src="/images/blog/react-labs-april-2025/perf_tracks_dark.webp" /> + </picture> +</div> + +The [React Performance Tracks docs](/reference/dev-tools/react-performance-tracks) explain everything included in the tracks, but here is a high-level overview. + +#### Scheduler βš› {/*scheduler-*/} + +The Scheduler track shows what React is working on for different priorities such as "blocking" for user interactions, or "transition" for updates inside startTransition. Inside each track, you will see the type of work being performed such as the event that scheduled an update, and when the render for that update happened. + +We also show information such as when an update is blocked waiting for a different priority, or when React is waiting for paint before continuing. The Scheduler track helps you understand how React splits your code into different priorities, and the order it completed the work. + +See the [Scheduler track](/reference/dev-tools/react-performance-tracks#scheduler) docs to see everything included. + +#### Components βš› {/*components-*/} + +The Components track shows the tree of components that React is working on either to render or run effects. Inside you'll see labels such as "Mount" for when children mount or effects are mounted, or "Blocked" for when rendering is blocked due to yielding to work outside React. + +The Components track helps you understand when components are rendered or run effects, and the time it takes to complete that work to help identify performance problems. + +See the [Components track docs](/reference/dev-tools/react-performance-tracks#components) for see everything included. + +--- + +## New React DOM Features {/*new-react-dom-features*/} + +### Partial Pre-rendering {/*partial-pre-rendering*/} + +In 19.2 we're adding a new capability to pre-render part of the app ahead of time, and resume rendering it later. + +This feature is called "Partial Pre-rendering", and allows you to pre-render the static parts of your app and serve it from a CDN, and then resume rendering the shell to fill it in with dynamic content later. + +To pre-render an app to resume later, first call `prerender` with an `AbortController`: + +``` +const {prelude, postponed} = await prerender(<App />, { + signal: controller.signal, +}); + +// Save the postponed state for later +await savePostponedState(postponed); + +// Send prelude to client or CDN. +``` + +Then, you can return the `prelude` shell to the client, and later call `resume` to "resume" to a SSR stream: + +``` +const postponed = await getPostponedState(request); +const resumeStream = await resume(<App />, postponed); + +// Send stream to client. +``` + +Or you can call `resumeAndPrerender` to resume to get static HTML for SSG: + +``` +const postponedState = await getPostponedState(request); +const { prelude } = await resumeAndPrerender(<App />, postponedState); + +// Send complete HTML prelude to CDN. +``` + +For more info, see the docs for the new APIs: +- `react-dom/server` + - [`resume`](/reference/react-dom/server/resume): for Web Streams. + - [`resumeToPipeableStream`](/reference/react-dom/server/resumeToPipeableStream) for Node Streams. +- `react-dom/static` + - [`resumeAndPrerender`](/reference/react-dom/static/resumeAndPrerender) for Web Streams. + - [`resumeAndPrerenderToNodeStream`](/reference/react-dom/static/resumeAndPrerenderToNodeStream) for Node Streams. + +Additionally, the prerender apis now return a `postpone` state to pass to the `resume` apis. + +--- + +## Notable Changes {/*notable-changes*/} + +### Batching Suspense Boundaries for SSR {/*batching-suspense-boundaries-for-ssr*/} + +We fixed a behavioral bug where Suspense boundaries would reveal differently depending on if they were rendered on the client or when streaming from server-side rendering. + +Starting in 19.2, React will batch reveals of server-rendered Suspense boundaries for a short time, to allow more content to be revealed together and align with the client-rendered behavior. + +<Diagram name="19_2_batching_before" height={162} width={1270} alt="Diagram with three sections, with an arrow transitioning each section in between. The first section contains a page rectangle showing a glimmer loading state with faded bars. The second panel shows the top half of the page revealed and highlighted in blue. The third panel shows the entire the page revealed and highlighted in blue."> + +Previously, during streaming server-side rendering, suspense content would immediately replace fallbacks. + +</Diagram> + +<Diagram name="19_2_batching_after" height={162} width={1270} alt="Diagram with three sections, with an arrow transitioning each section in between. The first section contains a page rectangle showing a glimmer loading state with faded bars. The second panel shows the same page. The third panel shows the entire the page revealed and highlighted in blue."> + +In React 19.2, suspense boundaries are batched for a small amount of time, to allow revealing more content together. + +</Diagram> + +This fix also prepares apps for supporting `<ViewTransition>` for Suspense during SSR. By revealing more content together, animations can run in larger batches of content, and avoid chaining animations of content that stream in close together. + +<Note> + +React uses heuristics to ensure throttling does not impact core web vitals and search ranking. + +For example, if the total page load time is approaching 2.5s (which is the time considered "good" for [LCP](https://web.dev/articles/lcp)), React will stop batching and reveal content immediately so that the throttling is not the reason to miss the metric. + +</Note> + +--- + +### SSR: Web Streams support for Node {/*ssr-web-streams-support-for-node*/} + +React 19.2 adds support for Web Streams for streaming SSR in Node.js: +- [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) is now available for Node.js +- [`prerender`](/reference/react-dom/static/prerender) is now available for Node.js + +As well as the new `resume` APIs: +- [`resume`](/reference/react-dom/server/resume) is available for Node.js. +- [`resumeAndPrerender`](/reference/react-dom/static/resumeAndPrerender) is available for Node.js. + + +<Pitfall> + +#### Prefer Node Streams for server-side rendering in Node.js {/*prefer-node-streams-for-server-side-rendering-in-nodejs*/} + +In Node.js environments, we still highly recommend using the Node Streams APIs: + +- [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) +- [`resumeToPipeableStream`](/reference/react-dom/server/resumeToPipeableStream) +- [`prerenderToNodeStream`](/reference/react-dom/static/prerenderToNodeStream) +- [`resumeAndPrerenderToNodeStream`](/reference/react-dom/static/resumeAndPrerenderToNodeStream) + +This is because Node Streams are much faster than Web Streams in Node, and Web Streams do not support compression by default, leading to users accidentally missing the benefits of streaming. + +</Pitfall> + +--- + +### `eslint-plugin-react-hooks` v6 {/*eslint-plugin-react-hooks*/} + +We also published `eslint-plugin-react-hooks@latest` with flat config by default in the `recommended` preset, and opt-in for new React Compiler powered rules. + +To continue using the legacy config, you can change to `recommended-legacy`: + +```diff +- extends: ['plugin:react-hooks/recommended'] ++ extends: ['plugin:react-hooks/recommended-legacy'] +``` + +For a full list of compiler enabled rules, [check out the linter docs](/reference/eslint-plugin-react-hooks#recommended). + +Check out the `eslint-plugin-react-hooks` [changelog for a full list of changes](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/CHANGELOG.md#610). + +--- + +### Update the default `useId` prefix {/*update-the-default-useid-prefix*/} + +In 19.2, we're updating the default `useId` prefix from `:r:` (19.0.0) or `Β«rΒ»` (19.1.0) to `_r_`. + +The original intent of using a special character that was not valid for CSS selectors was that it would be unlikely to collide with IDs written by users. However, to support View Transitions, we need to ensure that IDs generated by `useId` are valid for `view-transition-name` and XML 1.0 names. + +--- + +## Changelog {/*changelog*/} + +Other notable changes +- `react-dom`: Allow nonce to be used on hoistable styles [#32461](https://github.com/facebook/react/pull/32461) +- `react-dom`: Warn for using a React owned node as a Container if it also has text content [#32774](https://github.com/facebook/react/pull/32774) + +Notable bug fixes +- `react`: Stringify context as "SomeContext" instead of "SomeContext.Provider" [#33507](https://github.com/facebook/react/pull/33507) +- `react`: Fix infinite useDeferredValue loop in popstate event [#32821](https://github.com/facebook/react/pull/32821) +- `react`: Fix a bug when an initial value was passed to useDeferredValue [#34376](https://github.com/facebook/react/pull/34376) +- `react`: Fix a crash when submitting forms with Client Actions [#33055](https://github.com/facebook/react/pull/33055) +- `react`: Hide/unhide the content of dehydrated suspense boundaries if they resuspend [#32900](https://github.com/facebook/react/pull/32900) +- `react`: Avoid stack overflow on wide trees during Hot Reload [#34145](https://github.com/facebook/react/pull/34145) +- `react`: Improve component stacks in various places [#33629](https://github.com/facebook/react/pull/33629), [#33724](https://github.com/facebook/react/pull/33724), [#32735](https://github.com/facebook/react/pull/32735), [#33723](https://github.com/facebook/react/pull/33723) +- `react`: Fix a bug with React.use inside React.lazy-ed Component [#33941](https://github.com/facebook/react/pull/33941) +- `react-dom`: Stop warning when ARIA 1.3 attributes are used [#34264](https://github.com/facebook/react/pull/34264) +- `react-dom`: Fix a bug with deeply nested Suspense inside Suspense fallbacks [#33467](https://github.com/facebook/react/pull/33467) +- `react-dom`: Avoid hanging when suspending after aborting while rendering [#34192](https://github.com/facebook/react/pull/34192) + +For a full list of changes, please see the [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md). + + +--- + +_Thanks to [Ricky Hanlon](https://bsky.app/profile/ricky.fm) for [writing this post](https://www.youtube.com/shorts/T9X3YkgZRG0), [Dan Abramov](https://bsky.app/profile/danabra.mov), [Matt Carroll](https://twitter.com/mattcarrollcode), [Jack Pope](https://jackpope.me), and [Joe Savona](https://x.com/en_JS) for reviewing this post._ diff --git a/src/content/blog/2025/10/07/introducing-the-react-foundation.md b/src/content/blog/2025/10/07/introducing-the-react-foundation.md new file mode 100644 index 000000000..a9b922dbc --- /dev/null +++ b/src/content/blog/2025/10/07/introducing-the-react-foundation.md @@ -0,0 +1,67 @@ +--- +title: "Introducing the React Foundation" +author: Seth Webster, Matt Carroll, Joe Savona +date: 2025/10/07 +description: Today, we're announcing our plans to create the React Foundation a new technical governance structure +--- + +October 7, 2025 by [Seth Webster](https://x.com/sethwebster), [Matt Carroll](https://x.com/mattcarrollcode), [Joe Savona](https://x.com/en_JS), [Sophie Alpert](https://x.com/sophiebits) + +--- + + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem', marginLeft: '7rem', marginRight: '7rem' }}> + <picture > + <source srcset="/images/blog/react-foundation/react_foundation_logo.png" /> + <img className="w-full light-image" src="/images/blog/react-foundation/react_foundation_logo.webp" /> + </picture> + <picture > + <source srcset="/images/blog/react-foundation/react_foundation_logo_dark.png" /> + <img className="w-full dark-image" src="/images/blog/react-foundation/react_foundation_logo_dark.webp" /> + </picture> +</div> + +<Intro> + +Today, we're announcing our plans to create the React Foundation and a new technical governance structure. + +</Intro> + +--- + +We open sourced React over a decade ago to help developers build great user experiences. From its earliest days, React has received substantial contributions from contributors outside of Meta. Over time, the number of contributors and the scope of their contributions has grown significantly. What started out as a tool developed for Meta has expanded into a project that spans multiple companies with regular contributions from across the ecosystem. React has outgrown the confines of any one company. + +To better serve the React community, we are announcing our plans to move React and React Native from Meta to a new React Foundation. As a part of this change, we will also be implementing a new independent technical governance structure. We believe these changes will enable us to give React ecosystem projects more resources. + +## The React Foundation {/*the-react-foundation*/} + +We will make the React Foundation the new home for React, React Native, and some supporting projects like JSX. The React Foundation’s mission will be to support the React community and ecosystem. Once implemented, the React Foundation will + +* Maintain React’s infrastructure like GitHub, CI, and trademarks +* Organize React Conf +* Create initiatives to support the React ecosystem like financial support of ecosystem projects, issuing grants, and creating programs + +The React Foundation will be governed by a board of directors, with Seth Webster serving as the executive director. This board will direct funds and resources to support React’s development, community, and ecosystem. We believe that this is the best structure to ensure that the React Foundation is vendor-neutral and reflects the best interests of the community. + +The founding corporate members of the React Foundation will be Amazon, Callstack, Expo, Meta, Microsoft, Software Mansion, and Vercel. These companies have had a major impact on the React and React Native ecosystems and we are grateful for their support. We are excited to welcome even more members in the future. + +<div style={{display: 'flex', justifyContent: 'center', margin: '2rem'}}> + <picture > + <source srcset="/images/blog/react-foundation/react_foundation_member_logos.png" /> + <img className="w-full light-image" src="/images/blog/react-foundation/react_foundation_member_logos.webp" /> + </picture> + <picture > + <source srcset="/images/blog/react-foundation/react_foundation_member_logos_dark.png" /> + <img className="w-full dark-image" src="/images/blog/react-foundation/react_foundation_member_logos_dark.webp" /> + </picture> +</div> + +## React’s technical governance {/*reacts-technical-governance*/} + +We believe that React's technical direction should be set by the people who contribute to and maintain React. As React moves to a foundation, it is important that no single company or organization is overrepresented. To achieve this, we plan to define a new technical governance structure for React that is independent from the React Foundation. + +As a part of creating React’s new technical governance structure we will reach out to the community for feedback. Once finalized, we will share details in a future post. + +## Thank you {/*thank-you*/} + +React's incredible growth is thanks to the thousands of people, companies, and projects that have shaped React. The creation of the React Foundation is a testament to the strength and vibrancy of the React community. Together, the React Foundation and React’s new technical governance will ensure that React’s future is secure for years to come. diff --git a/src/content/blog/2025/10/07/react-compiler-1.md b/src/content/blog/2025/10/07/react-compiler-1.md new file mode 100644 index 000000000..080f3586e --- /dev/null +++ b/src/content/blog/2025/10/07/react-compiler-1.md @@ -0,0 +1,194 @@ +--- +title: "React Compiler v1.0" +author: Lauren Tan, Joe Savona, and Mofei Zhang +date: 2025/10/07 +description: We are releasing the compiler's first stable release today. + +--- + +Oct 7, 2025 by [Lauren Tan](https://x.com/potetotes), [Joe Savona](https://x.com/en_JS), and [Mofei Zhang](https://x.com/zmofei). + +--- + +<Intro> + +The React team is excited to share new updates: + +</Intro> + +1. React Compiler 1.0 is available today. +2. Compiler-powered lint rules ship in `eslint-plugin-react-hooks`'s `recommended` and `recommended-latest` preset. +3. We've published an incremental adoption guide, and partnered with Expo, Vite, and Next.js so new apps can start with the compiler enabled. + +--- + +We are releasing the compiler's first stable release today. React Compiler works on both React and React Native, and automatically optimizes components and hooks without requiring rewrites. The compiler has been battle tested on major apps at Meta and is fully production-ready. + +[React Compiler](/learn/react-compiler) is a build-time tool that optimizes your React app through automatic memoization. Last year, we published React Compiler's [first beta](/blog/2024/10/21/react-compiler-beta-release) and received lots of great feedback and contributions. We're excited about the wins we've seen from folks adopting the compiler (see case studies from [Sanity Studio](https://github.com/reactwg/react-compiler/discussions/33) and [Wakelet](https://github.com/reactwg/react-compiler/discussions/52)) and are excited to bring the compiler to more users in the React community. + +This release is the culmination of a huge and complex engineering effort spanning almost a decade. The React team's first exploration into compilers started with [Prepack](https://github.com/facebookarchive/prepack) in 2017. While this project was eventually shut down, there were many learnings that informed the team on the design of Hooks, which were designed with a future compiler in mind. In 2021, [Xuan Huang](https://x.com/Huxpro) demoed the [first iteration](https://www.youtube.com/watch?v=lGEMwh32soc) of a new take on React Compiler. + +Although this first version of the new React Compiler was eventually rewritten, the first prototype gave us increased confidence that this was a tractable problem, and the learnings that an alternative compiler architecture could precisely give us the memoization characteristics we wanted. [Joe Savona](https://x.com/en_JS), [Sathya Gunasekaran](https://x.com/_gsathya), [Mofei Zhang](https://x.com/zmofei), and [Lauren Tan](https://x.com/potetotes) worked through our first rewrite, moving the compiler's architecture into a Control Flow Graph (CFG) based High-Level Intermediate Representation (HIR). This paved the way for much more precise analysis and even type inference within React Compiler. Since then, many significant portions of the compiler have been rewritten, with each rewrite informed by our learnings from the previous attempt. And we have received significant help and contributions from many members of the [React team](/community/team) along the way. + +This stable release is our first of many. The compiler will continue to evolve and improve, and we expect to see it become a new foundation and era for the next decade and more of React. + +You can jump straight to the [quickstart](/learn/react-compiler), or read on for the highlights from React Conf 2025. + +<DeepDive> + +#### How does React Compiler work? {/*how-does-react-compiler-work*/} + +React Compiler is an optimizing compiler that optimizes components and hooks through automatic memoization. While it is implemented as a Babel plugin currently, the compiler is largely decoupled from Babel and lowers the Abstract Syntax Tree (AST) provided by Babel into its own novel HIR, and through multiple compiler passes, carefully understands data-flow and mutability of your React code. This allows the compiler to granularly memoize values used in rendering, including the ability to memoize conditionally, which is not possible through manual memoization. + +```js {8} +import { use } from 'react'; + +export default function ThemeProvider(props) { + if (!props.children) { + return null; + } + // The compiler can still memoize code after a conditional return + const theme = mergeTheme(props.theme, use(ThemeContext)); + return ( + <ThemeContext value={theme}> + {props.children} + </ThemeContext> + ); +} +``` +_See this example in the [React Compiler Playground](https://playground.react.dev/#N4Igzg9grgTgxgUxALhASwLYAcIwC4AEwBUYCBAvgQGYwQYEDkMCAhnHowNwA6AdvwQAPHPgIATBNVZQANoWpQ+HNBD4EAKgAsEGBAAU6ANzSSYACix0sYAJRF+BAmmoFzAQisQbAOjha0WXEWPntgRycCFjxYdT45WV51Sgi4NTBCPB09AgBeAj0YAHMEbV0ES2swHyzygBoSMnMyvQBhNTxhPFtbJKdo2LcIpwAeFoR2vk6hQiNWWSgEXOBavQoAPmHI4C9ff0DghD4KLZGAenHJ6bxN5N7+ChA6kDS+ajQilHRsXEyATyw5GI+gWRTQfAA8lg8Ko+GBKDQ6AxGAAjVgohCyAC0WFB4KxLHYeCxaWwgQQMDO4jQGW4-H45nCyTOZ1JWECrBhagAshBJMgCDwQPNZEKHgQwJyae8EPCQVAwZDobC7FwnuAtBAAO4ASSmFL48zAKGksjIFCAA)_ + +In addition to automatic memoization, React Compiler also has validation passes that run on your React code. These passes encode the [Rules of React](/reference/rules), and uses the compiler's understanding of data-flow and mutability to provide diagnostics where the Rules of React are broken. These diagnostics often expose latent bugs hiding in React code, and are primarily surfaced through `eslint-plugin-react-hooks`. + +To learn more about how the compiler optimizes your code, visit the [Playground](https://playground.react.dev). + +</DeepDive> + +## Use React Compiler Today {/*use-react-compiler-today*/} +To install the compiler: + +npm +<TerminalBlock> +npm install --save-dev --save-exact babel-plugin-react-compiler@latest +</TerminalBlock> + +pnpm +<TerminalBlock> +pnpm add --save-dev --save-exact babel-plugin-react-compiler@latest +</TerminalBlock> + +yarn +<TerminalBlock> +yarn add --dev --exact babel-plugin-react-compiler@latest +</TerminalBlock> + +As part of the stable release, we've been making React Compiler easier to add to your projects and added optimizations to how the compiler generates memoization. React Compiler now supports optional chains and array indices as dependencies. These improvements ultimately result in fewer re-renders and more responsive UIs, while letting you keep writing idiomatic declarative code. + +You can find more details on using the Compiler in [our docs](/learn/react-compiler). + +## What we're seeing in production {/*react-compiler-at-meta*/} +[The compiler has already shipped in apps like Meta Quest Store](https://youtu.be/lyEKhv8-3n0?t=3002). We've seen initial loads and cross-page navigations improve by up to 12%, while certain interactions are more than 2.5Γ— faster. Memory usage stays neutral even with these wins. Although your mileage may vary, we recommend experimenting with the compiler in your app to see similar performance gains. + +## Backwards Compatibility {/*backwards-compatibility*/} +As noted in the Beta announcement, React Compiler is compatible with React 17 and up. If you are not yet on React 19, you can use React Compiler by specifying a minimum target in your compiler config, and adding `react-compiler-runtime` as a dependency. You can find docs on this [here](/reference/react-compiler/target#targeting-react-17-or-18). + +## Enforce the Rules of React with compiler-powered linting {/*migrating-from-eslint-plugin-react-compiler-to-eslint-plugin-react-hooks*/} +React Compiler includes an ESLint rule that helps identify code that breaks the [Rules of React](/reference/rules). The linter does not require the compiler to be installed, so there's no risk in upgrading eslint-plugin-react-hooks. We recommend everyone upgrade today. + +If you have already installed `eslint-plugin-react-compiler`, you can now remove it and use `eslint-plugin-react-hooks@latest`. Many thanks to [@michaelfaith](https://bsky.app/profile/michael.faith) for contributing to this improvement! + +To install: + +npm +<TerminalBlock> +npm install --save-dev eslint-plugin-react-hooks@latest +</TerminalBlock> + +pnpm +<TerminalBlock> +pnpm add --save-dev eslint-plugin-react-hooks@latest +</TerminalBlock> + +yarn +<TerminalBlock> +yarn add --dev eslint-plugin-react-hooks@latest +</TerminalBlock> + +```js {6} +// eslint.config.js (Flat Config) +import reactHooks from 'eslint-plugin-react-hooks'; +import { defineConfig } from 'eslint/config'; + +export default defineConfig([ + reactHooks.configs.flat.recommended, +]); +``` + +```js {3} +// eslintrc.json (Legacy Config) +{ + "extends": ["plugin:react-hooks/recommended"], + // ... +} +``` + +To enable React Compiler rules, we recommend using the `recommended` preset. You can also check out the [README](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md) for more instructions. Here are a few examples we featured at React Conf: + +- Catching `setState` patterns that cause render loops with [`set-state-in-render`](/reference/eslint-plugin-react-hooks/lints/set-state-in-render). +- Flagging expensive work inside effects via [`set-state-in-effect`](/reference/eslint-plugin-react-hooks/lints/set-state-in-effect). +- Preventing unsafe ref access during render with [`refs`](/reference/eslint-plugin-react-hooks/lints/refs). + +## What should I do about useMemo, useCallback, and React.memo? {/*what-should-i-do-about-usememo-usecallback-and-reactmemo*/} +By default, React Compiler will memoize your code based on its analysis and heuristics. In most cases, this memoization will be as precise, or moreso, than what you may have written β€” and as noted above, the compiler can memoize even in cases where `useMemo`/`useCallback` cannot be used, such as after an early return. + +However, in some cases developers may need more control over memoization. The `useMemo` and `useCallback` hooks can continue to be used with React Compiler as an escape hatch to provide control over which values are memoized. A common use-case for this is if a memoized value is used as an effect dependency, in order to ensure that an effect does not fire repeatedly even when its dependencies do not meaningfully change. + +For new code, we recommend relying on the compiler for memoization and using `useMemo`/`useCallback` where needed to achieve precise control. + +For existing code, we recommend either leaving existing memoization in place (removing it can change compilation output) or carefully testing before removing the memoization. + +## New apps should use React Compiler {/*new-apps-should-use-react-compiler*/} +We have partnered with the Expo, Vite, and Next.js teams to add the compiler to the new app experience. + +[Expo SDK 54](https://docs.expo.dev/guides/react-compiler/) and up has the compiler enabled by default, so new apps will automatically be able to take advantage of the compiler from the start. + +<TerminalBlock> +npx create-expo-app@latest +</TerminalBlock> + +[Vite](https://vite.dev/guide/) and [Next.js](https://nextjs.org/docs/app/api-reference/cli/create-next-app) users can choose the compiler enabled templates in `create-vite` and `create-next-app`. + +<TerminalBlock> +npm create vite@latest +</TerminalBlock> + +<br /> + +<TerminalBlock> +npx create-next-app@latest +</TerminalBlock> + +## Adopt React Compiler incrementally {/*adopt-react-compiler-incrementally*/} +If you're maintaining an existing application, you can roll out the compiler at your own pace. We published a step-by-step [incremental adoption guide](/learn/react-compiler/incremental-adoption) that covers gating strategies, compatibility checks, and rollout tooling so you can enable the compiler with confidence. + +## swc support (experimental) {/*swc-support-experimental*/} +React Compiler can be installed across [several build tools](/learn/react-compiler#installation) such as Babel, Vite, and Rsbuild. + +In addition to those tools, we have been collaborating with Kang Dongyoon ([@kdy1dev](https://x.com/kdy1dev)) from the [swc](https://swc.rs/) team on adding additional support for React Compiler as an swc plugin. While this work isn't done, Next.js build performance should now be considerably faster when the [React Compiler is enabled in your Next.js app](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler). + +We recommend using Next.js [15.3.1](https://github.com/vercel/next.js/releases/tag/v15.3.1) or greater to get the best build performance. + +Vite users can continue to use [vite-plugin-react](https://github.com/vitejs/vite-plugin-react) to enable the compiler, by adding it as a [Babel plugin](/learn/react-compiler/installation#vite). We are also working with the [oxc](https://oxc.rs/) team to [add support for the compiler](https://github.com/oxc-project/oxc/issues/10048). Once [rolldown](https://github.com/rolldown/rolldown) is officially released and supported in Vite and oxc support is added for React Compiler, we'll update the docs with information on how to migrate. + +## Upgrading React Compiler {/*upgrading-react-compiler*/} +React Compiler works best when the auto-memoization applied is strictly for performance. Future versions of the compiler may change how memoization is applied, for example it could become more granular and precise. + +However, because product code may sometimes break the [rules of React](/reference/rules) in ways that aren't always statically detectable in JavaScript, changing memoization can occasionally have unexpected results. For example, a previously memoized value might be used as a dependency for a `useEffect` somewhere in the component tree. Changing how or whether this value is memoized can cause over or under-firing of that `useEffect`. While we encourage [useEffect only for synchronization](/learn/synchronizing-with-effects), your codebase may have `useEffect`s that cover other use cases, such as effects that needs to only run in response to specific values changing. + +In other words, changing memoization may under rare circumstances cause unexpected behavior. For this reason, we recommend following the Rules of React and employing continuous end-to-end testing of your app so you can upgrade the compiler with confidence and identify any rules of React violations that might cause issues. + +If you don't have good test coverage, we recommend pinning the compiler to an exact version (eg `1.0.0`) rather than a SemVer range (eg `^1.0.0`). You can do this by passing the `--save-exact` (npm/pnpm) or `--exact` flags (yarn) when upgrading the compiler. You should then do any upgrades of the compiler manually, taking care to check that your app still works as expected. + +--- + +Thanks to [Jason Bonta](https://x.com/someextent), [Jimmy Lai](https://x.com/feedthejim), [Kang Dongyoon](https://x.com/kdy1dev) (@kdy1dev), and [Dan Abramov](https://bsky.app/profile/danabra.mov) for reviewing and editing this post. diff --git a/src/content/blog/2025/10/16/react-conf-2025-recap.md b/src/content/blog/2025/10/16/react-conf-2025-recap.md new file mode 100644 index 000000000..8476b02aa --- /dev/null +++ b/src/content/blog/2025/10/16/react-conf-2025-recap.md @@ -0,0 +1,133 @@ +--- +title: "React Conf 2025 Recap" +author: Matt Carroll and Ricky Hanlon +date: 2025/10/16 +description: Last week we hosted React Conf 2025, in this post, we summarize the talks and announcements from the event... +--- + +Oct 16, 2025 by [Matt Carroll](https://x.com/mattcarrollcode) and [Ricky Hanlon](https://bsky.app/profile/ricky.fm) + +--- + +<Intro> + +Last week we hosted React Conf 2025 where we announced the [React Foundation](/blog/2025/10/07/introducing-the-react-foundation) and showcased new features coming to React and React Native. + +</Intro> + +--- + +React Conf 2025 was held on October 7-8, 2025, in Henderson, Nevada. + +The entire [day 1](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=1067s) and [day 2](https://www.youtube.com/watch?v=p9OcztRyDl0&t=2299s) streams are available online, and you can view photos from the event [here](https://conf.react.dev/photos). + +In this post, we'll summarize the talks and announcements from the event. + + +## Day 1 Keynote {/*day-1-keynote*/} + +_Watch the full day 1 stream [here.](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=1067s)_ + +In the day 1 keynote, Joe Savona shared the updates from the team and community since the last React Conf and highlights from React 19.0 and 19.1. + +Mofei Zhang highlighted the new features in React 19.2 including: +* [`<Activity />`](https://react.dev/reference/react/Activity) β€” a new component to manage visibility. +* [`useEffectEvent`](https://react.dev/reference/react/useEffectEvent) to fire events from Effects. +* [Performance Tracks](https://react.dev/reference/dev-tools/react-performance-tracks) β€” a new profiling tool in DevTools. +* [Partial Pre-Rendering](https://react.dev/blog/2025/10/01/react-19-2#partial-pre-rendering) to pre-render part of an app ahead of time, and resume rendering it later. + +Jack Pope announced new features in Canary including: + +* [`<ViewTransition />`](https://react.dev/reference/react/ViewTransition) β€” a new component to animate page transitions. +* [Fragment Refs](https://react.dev/reference/react/Fragment#fragmentinstance) β€” a new way to interact with the DOM nodes wrapped by a Fragment. + +Lauren Tan announced [React Compiler v1.0](https://react.dev/blog/2025/10/07/react-compiler-1) and recommended all apps use React Compiler for benefits like: +* [Automatic memoization](/learn/react-compiler/introduction#what-does-react-compiler-do) that understands React code. +* [New lint rules](/learn/react-compiler/installation#eslint-integration) powered by React Compiler to teach best practices. +* [Default support](/learn/react-compiler/installation#basic-setup) for new apps in Vite, Next.js, and Expo. +* [Migration guides](/learn/react-compiler/incremental-adoption) for existing apps migrating to React Compiler. + +Finally, Seth Webster announced the [React Foundation](/blog/2025/10/07/introducing-the-react-foundation) to steward React's open source development and community. + +Watch day 1 here: + +<YouTubeIframe src="https://www.youtube.com/embed/zyVRg2QR6LA?si=z-8t_xCc12HwGJH_&t=1067s" /> + +## Day 2 Keynote {/*day-2-keynote*/} + +_Watch the full day 2 stream [here.](https://www.youtube.com/watch?v=p9OcztRyDl0&t=2299s)_ + +Jorge Cohen and Nicola Corti kicked off day 2 highlighting React Native’s incredible growth with 4M weekly downloads (100% growth YoY), and some notable app migrations from Shopify, Zalando, and HelloFresh, award-winning apps like RISE, RUNNA, and Partyful, and AI apps from Mistral, Replit, and v0. + +Riccardo Cipolleschi shared two major announcements for React Native: +- [React Native 0.82 will be New Architecture only](https://reactnative.dev/blog/2025/10/08/react-native-0.82#new-architecture-only) +- [Experimental Hermes V1 support](https://reactnative.dev/blog/2025/10/08/react-native-0.82#experimental-hermes-v1) + +Ruben Norte and Alex Hunt finished out the keynote by announcing: +- [New web-aligned DOM APIs](https://reactnative.dev/blog/2025/10/08/react-native-0.82#dom-node-apis) for improved compatibility with React on the web. +- [New Performance APIs](https://reactnative.dev/blog/2025/10/08/react-native-0.82#web-performance-apis-canary) with a new network panel and desktop app. + +Watch day 2 here: + +<YouTubeIframe src="https://www.youtube.com/embed/p9OcztRyDl0?si=qPTHftsUE07cjZpS&t=2299s" /> + + +## React team talks {/*react-team-talks*/} + +Throughout the conference, there were talks from the React team including: +* [Async React Part I](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=10907s) and [Part II](https://www.youtube.com/watch?v=p9OcztRyDl0&t=29073s) [(Ricky Hanlon)](https://x.com/rickhanlonii) showed what's possible using the last 10 years of innovation. +* [Exploring React Performance](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=20274s) [(Joe Savona)](https://x.com/en_js) showed the results of our React performance research. +* [Reimagining Lists in React Native](https://www.youtube.com/watch?v=p9OcztRyDl0&t=10382s) [(Luna Wei)](https://x.com/lunaleaps) introduced Virtual View, a new primitive for lists that manages visibility with mode-based rendering (hidden/pre-render/visible). +* [Profiling with React Performance tracks](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=8276s) [(Ruslan Lesiutin)](https://x.com/ruslanlesiutin) showed how to use the new React Performance Tracks to debug performance issues and build great apps. +* [React Strict DOM](https://www.youtube.com/watch?v=p9OcztRyDl0&t=9026s) [(Nicolas Gallagher)](https://nicolasgallagher.com/) talked about Meta's approach to using web code on native. +* [View Transitions and Activity](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=4870s) [(Chance Strickland)](https://x.com/chancethedev) β€” Chance worked with the React team to showcase how to use `<Activity />` and `<ViewTransition />` to build fast, native-feeling animations. +* [In case you missed the memo](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=9525s) [(Cody Olsen)](https://bsky.app/profile/codey.bsky.social) - Cody worked with the React team to adopt the Compiler at Sanity Studio, and shared how it went. +## React framework talks {/*react-framework-talks*/} + +The second half of day 2 had a series of talks from React Framework teams including: + +* [React Native, Amplified](https://www.youtube.com/watch?v=p9OcztRyDl0&t=5737s) by [Giovanni Laquidara](https://x.com/giolaq) and [Eric Fahsl](https://x.com/efahsl). +* [React Everywhere: Bringing React Into Native Apps](https://www.youtube.com/watch?v=p9OcztRyDl0&t=18213s) by [Mike Grabowski](https://x.com/grabbou). +* [How Parcel Bundles React Server Components](https://www.youtube.com/watch?v=p9OcztRyDl0&t=19538s) by [Devon Govett](https://x.com/devonovett). +* [Designing Page Transitions](https://www.youtube.com/watch?v=p9OcztRyDl0&t=20640s) by [Delba de Oliveira](https://x.com/delba_oliveira). +* [Build Fast, Deploy Faster β€” Expo in 2025](https://www.youtube.com/watch?v=p9OcztRyDl0&t=21350s) by [Evan Bacon](https://x.com/baconbrix). +* [The React Router's take on RSC](https://www.youtube.com/watch?v=p9OcztRyDl0&t=22367s) by [Kent C. Dodds](https://x.com/kentcdodds). +* [RedwoodSDK: Web Standards Meet Full-Stack React](https://www.youtube.com/watch?v=p9OcztRyDl0&t=24992s) by [Peter Pistorius](https://x.com/appfactory) and [Aurora Scharff](https://x.com/aurorascharff). +* [TanStack Start](https://www.youtube.com/watch?v=p9OcztRyDl0&t=26065s) by [Tanner Linsley](https://x.com/tannerlinsley). + +## Q&A {/*q-and-a*/} +There were three Q&A panels during the conference: + +* [React Team at Meta Q&A](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=26304s) hosted by [Shruti Kapoor](https://x.com/shrutikapoor08) +* [React Frameworks Q&A](https://www.youtube.com/watch?v=p9OcztRyDl0&t=26812s) hosted by [Jack Herrington](https://x.com/jherr) +* [React and AI Panel](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=18741s) hosted by [Lee Robinson](https://x.com/leerob) + +## And more... {/*and-more*/} + +We also heard talks from the community including: +* [Building an MCP Server](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=24204s) by [James Swinton](https://x.com/JamesSwintonDev) ([AG Grid](https://www.ag-grid.com/?utm_source=react-conf&utm_medium=react-conf-homepage&utm_campaign=react-conf-sponsorship-2025)) +* [Modern Emails using React](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=25521s) by [Zeno Rocha](https://x.com/zenorocha) ([Resend](https://resend.com/)) +* [Why React Native Apps Make All the Money](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=24917s) by [Perttu LΓ€hteenlahti](https://x.com/plahteenlahti) ([RevenueCat](https://www.revenuecat.com/)) +* [The invisible craft of great UX](https://www.youtube.com/watch?v=zyVRg2QR6LA&t=23400s) by [MichaΕ‚ Dudak](https://x.com/michaldudak) ([MUI](https://mui.com/)) + +## Thanks {/*thanks*/} + +Thank you to all the staff, speakers, and participants, who made React Conf 2025 possible. There are too many to list, but we want to thank a few in particular. + +Thank you to [Matt Carroll](https://x.com/mattcarrollcode) for planning the entire event and building the conference website. + +Thank you to [Michael Chan](https://x.com/chantastic) for MCing React Conf with incredible dedication and energy, delivering thoughtful speaker intros, fun jokes, and genuine enthusiasm throughout the event. Thank you to [Jorge Cohen](https://x.com/JorgeWritesCode) for hosting the livestream, interviewing each speaker, and bringing the in-person React Conf experience online. + +Thank you to [Mateusz Kornacki](https://x.com/mat_kornacki), [Mike Grabowski](https://x.com/grabbou), [Kris Lis](https://www.linkedin.com/in/krzysztoflisakakris/) and the team at [Callstack](https://www.callstack.com/) for co-organizing React Conf and providing design, engineering, and marketing support. Thank you to the [ZeroSlope team](https://zeroslopeevents.com/contact-us/): Sunny Leggett, Tracey Harrison, Tara Larish, Whitney Pogue, and Brianne Smythia for helping to organize the event. + +Thank you to [Jorge Cabiedes Acosta](https://github.com/jorge-cab), [Gijs Weterings](https://x.com/gweterings), [Tim Yung](https://x.com/yungsters), and [Jason Bonta](https://x.com/someextent) for bringing questions from the Discord to the livestream. Thank you to [Lynn Yu](https://github.com/lynnshaoyu) for leading the moderation of the Discord. Thank you to [Seth Webster](https://x.com/sethwebster) for welcoming us each day; and to [Christopher Chedeau](https://x.com/vjeux), [Kevin Gozali](https://x.com/fkgozali), and [Pieter De Baets](https://x.com/Javache) for joining us with a special message during the after-party. + +Thank you to [Kadi Kraman](https://x.com/kadikraman), [Beto](https://x.com/betomoedano) and [Nicolas Solerieu](https://www.linkedin.com/in/nicolas-solerieu/) for building the conference mobile app. Thank you [Wojtek Szafraniec](https://x.com/wojteg1337) for help with the conference website. Thank you to [Mustache](https://www.mustachepower.com/) & [Cornerstone](https://cornerstoneav.com/) for the visuals, stage, and sound; and to the Westin Hotel for hosting us. + +Thank you to all the sponsors who made the event possible: [Amazon](https://www.developer.amazon.com), [MUI](https://mui.com/), [Vercel](https://vercel.com/), [Expo](https://expo.dev/), [RedwoodSDK](https://rwsdk.com), [Ag Grid](https://www.ag-grid.com), [RevenueCat](https://www.revenuecat.com/), [Resend](https://resend.com), [Mux](https://www.mux.com/), [Old Mission](https://www.oldmissioncapital.com/), [Arcjet](https://arcjet.com), [Infinite Red](https://infinite.red/), and [RenderATL](https://renderatl.com). + +Thank you to all the speakers who shared their knowledge and experience with the community. + +Finally, thank you to everyone who attended in person and online to show what makes React, React. React is more than a library, it is a community, and it was inspiring to see everyone come together to share and learn together. + +See you next time! 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 new file mode 100644 index 000000000..310a84116 --- /dev/null +++ b/src/content/blog/2025/12/03/critical-security-vulnerability-in-react-server-components.md @@ -0,0 +1,208 @@ +--- +title: "Critical Security Vulnerability in React Server Components" +author: The React Team +date: 2025/12/03 +description: There is an unauthenticated remote code execution vulnerability in React Server Components. A fix has been published in versions 19.0.1, 19.1.2, and 19.2.1. We recommend upgrading immediately. + +--- + +December 3, 2025 by [The React Team](/community/team) + +--- + +<Intro> + +There is an unauthenticated remote code execution vulnerability in React Server Components. + +We recommend upgrading immediately. + +</Intro> + +--- + +On November 29th, Lachlan Davidson reported a security vulnerability in React that allows unauthenticated remote code execution by exploiting a flaw in how React decodes payloads sent to React Server Function endpoints. + +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 vulnerability was disclosed as [CVE-2025-55182](https://www.cve.org/CVERecord?id=CVE-2025-55182) and is rated CVSS 10.0. + +The vulnerability is present in versions 19.0, 19.1.0, 19.1.1, and 19.2.0 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) + +## Immediate Action Required {/*immediate-action-required*/} + +A fix was introduced in versions [19.0.1](https://github.com/facebook/react/releases/tag/v19.0.1), [19.1.2](https://github.com/facebook/react/releases/tag/v19.1.2), and [19.2.1](https://github.com/facebook/react/releases/tag/v19.2.1). If you are using any of the above packages please upgrade to any of the fixed versions immediately. + +If your app’s React code does not use a server, your app is not affected by this vulnerability. If your app does not use a framework, bundler, or bundler plugin that supports React Server Components, your app is not affected by this vulnerability. + +### Affected frameworks and bundlers {/*affected-frameworks-and-bundlers*/} + +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), [@vitejs/plugin-rsc](https://www.npmjs.com/package/@vitejs/plugin-rsc), and [rwsdk](https://www.npmjs.com/package/rwsdk). + +See the [update instructions below](#update-instructions) for how to upgrade to these patches. + +### Hosting Provider Mitigations {/*hosting-provider-mitigations*/} + +We have worked with a number of hosting providers to apply temporary mitigations. + +You should not depend on these to secure your app, and still update immediately. + +### Vulnerability overview {/*vulnerability-overview*/} + +[React Server Functions](https://react.dev/reference/rsc/server-functions) allow a client to call a function on a server. React provides integration points and tools that frameworks and bundlers use to help React code run on both the client and the server. React translates requests on the client into HTTP requests which are forwarded to a server. On the server, React translates the HTTP request into a function call and returns the needed data to the client. + +An unauthenticated attacker could craft a malicious HTTP request to any Server Function endpoint that, when deserialized by React, achieves remote code execution on the server. Further details of the vulnerability will be provided after the rollout of the fix is complete. + +## Update Instructions {/*update-instructions*/} + +<Note> + +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) 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) +- **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*/} + +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.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: + +```bash +npm install next@14 +``` + +See the [Next.js blog](https://nextjs.org/blog/security-update-2025-12-11) for the latest update instructions and the [previous changelog](https://nextjs.org/blog/CVE-2025-66478) for more info. + +### React Router {/*update-react-router*/} + +If you are using React Router's unstable RSC APIs, you should upgrade the following package.json dependencies if they exist: + +```bash +npm install react@latest +npm install react-dom@latest +npm install react-server-dom-parcel@latest +npm install react-server-dom-webpack@latest +npm install @vitejs/plugin-rsc@latest +``` + +### Expo {/*expo*/} + +To learn more about mitigating, read the article on [expo.dev/changelog](https://expo.dev/changelog/mitigating-critical-security-vulnerability-in-react-server-components). + +### Redwood SDK {/*update-redwood-sdk*/} + +Ensure you are on rwsdk>=1.0.0-alpha.0 + +For the latest beta version: + +```bash +npm install rwsdk@latest +``` + +Upgrade to the latest `react-server-dom-webpack`: + +```bash +npm install react@latest react-dom@latest react-server-dom-webpack@latest +``` + +See [Redwood docs](https://docs.rwsdk.com/migrating/) for more migration instructions. + +### Waku {/*update-waku*/} + +Upgrade to the latest `react-server-dom-webpack`: + +```bash +npm install react@latest react-dom@latest react-server-dom-webpack@latest waku@latest +``` + +See [Waku announcement](https://github.com/wakujs/waku/discussions/1823) for more migration instructions. + +### `@vitejs/plugin-rsc` {/*vitejs-plugin-rsc*/} + +Upgrade to the latest RSC plugin: + +```bash +npm install react@latest react-dom@latest @vitejs/plugin-rsc@latest +``` + +### `react-server-dom-parcel` {/*update-react-server-dom-parcel*/} + +Update to the latest version: + + ```bash + npm install react@latest react-dom@latest react-server-dom-parcel@latest + ``` + +### `react-server-dom-turbopack` {/*update-react-server-dom-turbopack*/} + +Update to the latest version: + + ```bash + npm install react@latest react-dom@latest react-server-dom-turbopack@latest + ``` + +### `react-server-dom-webpack` {/*update-react-server-dom-webpack*/} + +Update to the latest version: + + ```bash +npm install react@latest react-dom@latest react-server-dom-webpack@latest + ``` + + +### React Native {/*react-native*/} + +For React Native users not using a monorepo or `react-dom`, your `react` version should be pinned in your `package.json`, and there are no additional steps needed. + +If you are using React Native in a monorepo, you should update _only_ the impacted packages if they are installed: + +- `react-server-dom-webpack` +- `react-server-dom-parcel` +- `react-server-dom-turbopack` + +This is required to mitigate the security advisory, but you do not need to update `react` and `react-dom` so this will not cause the version mismatch error in React Native. + +See [this issue](https://github.com/facebook/react-native/issues/54772#issuecomment-3617929832) for more information. + + +## Timeline {/*timeline*/} + +* **November 29th**: Lachlan Davidson reported the security vulnerability via [Meta Bug Bounty](https://bugbounty.meta.com/). +* **November 30th**: Meta security researchers confirmed and began working with the React team on a fix. +* **December 1st**: A fix was created and the React team began working with affected hosting providers and open source projects to validate the fix, implement mitigations and roll out the fix +* **December 3rd**: The fix was published to npm and the publicly disclosed as CVE-2025-55182. + +## Attribution {/*attribution*/} + +Thank you to [Lachlan Davidson](https://github.com/lachlan2k) for discovering, reporting, and working to help fix this vulnerability. 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 new file mode 100644 index 000000000..6845e2f2f --- /dev/null +++ b/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md @@ -0,0 +1,202 @@ +--- +title: "Denial of Service and Source Code Exposure in React Server Components" +author: The React Team +date: 2025/12/11 +description: Security researchers have found and disclosed two additional vulnerabilities in React Server Components while attempting to exploit the patches in last week’s critical vulnerability. High vulnerability Denial of Service (CVE-2025-55184), and medium vulnerability Source Code Exposure (CVE-2025-55183) + + +--- + +December 11, 2025 by [The React Team](/community/team) + +_Updated January 26, 2026._ + +--- + +<Intro> + +Security researchers have found and disclosed two additional vulnerabilities in React Server Components while attempting to exploit the patches in last week’s critical vulnerability. + +**These new vulnerabilities do not allow for Remote Code Execution.** The patch for React2Shell remains effective at mitigating the Remote Code Execution exploit. + +</Intro> + +--- + +The new vulnerabilities are disclosed as: + +- **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. + +<Note> + +#### The patches published earlier are vulnerable. {/*the-patches-published-earlier-are-vulnerable*/} + +If you already updated for the previous vulnerabilities, 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. + +## Immediate Action Required {/*immediate-action-required*/} + +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 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.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. + +<Note> + +#### It’s common for critical CVEs to uncover follow‑up vulnerabilities. {/*its-common-for-critical-cves-to-uncover-followup-vulnerabilities*/} + +When a critical vulnerability is disclosed, researchers scrutinize adjacent code paths looking for variant exploit techniques to test whether the initial mitigation can be bypassed. + +This pattern shows up across the industry, not just in JavaScript. For example, after [Log4Shell](https://nvd.nist.gov/vuln/detail/cve-2021-44228), additional CVEs ([1](https://nvd.nist.gov/vuln/detail/cve-2021-45046), [2](https://nvd.nist.gov/vuln/detail/cve-2021-45105)) were reported as the community probed the original fix. + +Additional disclosures can be frustrating, but they are generally a sign of a healthy response cycle. + +</Note> + +### Affected frameworks and bundlers {/*affected-frameworks-and-bundlers*/} + +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](/blog/2025/12/03/critical-security-vulnerability-in-react-server-components#update-instructions) for upgrade steps. + +### Hosting Provider Mitigations {/*hosting-provider-mitigations*/} + +As before, we have worked with a number of hosting providers to apply temporary mitigations. + +You should not depend on these to secure your app, and still update immediately. + +### React Native {/*react-native*/} + +For React Native users not using a monorepo or `react-dom`, your `react` version should be pinned in your `package.json`, and there are no additional steps needed. + +If you are using React Native in a monorepo, you should update _only_ the impacted packages if they are installed: + +- `react-server-dom-webpack` +- `react-server-dom-parcel` +- `react-server-dom-turbopack` + +This is required to mitigate the security advisories, but you do not need to update `react` and `react-dom` so this will not cause the version mismatch error in React Native. + +See [this issue](https://github.com/facebook/react-native/issues/54772#issuecomment-3617929832) for more information. + +--- + +## 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 discovered additional DoS vulnerabilities still exist in React Server Components. + +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 January 26th mitigate these DoS vulnerabilities. + +<Note> + +#### 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 previous versions vulnerable. Versions 19.0.4, 19.1.5, 19.2.4 are safe. + +----- + +_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) +**Base Score**: 5.3 (Medium) + +A security researcher has discovered that a malicious HTTP request sent to a vulnerable Server Function may unsafely return the source code of any Server Function. Exploitation requires the existence of a Server Function which explicitly or implicitly exposes a stringified argument: + +```javascript +'use server'; + +export async function serverFunction(name) { + const conn = db.createConnection('SECRET KEY'); + const user = await conn.createUser(name); // implicitly stringified, leaked in db + + return { + id: user.id, + message: `Hello, ${name}!` // explicitly stringified, leaked in reply + }} +``` + +An attacker may be able to leak the following: + +```txt +0:{"a":"$@1","f":"","b":"Wy43RxUKdxmr5iuBzJ1pN"} +1:{"id":"tva1sfodwq","message":"Hello, async function(a){console.log(\"serverFunction\");let b=i.createConnection(\"SECRET KEY\");return{id:(await b.createUser(a)).id,message:`Hello, ${a}!`}}!"} +``` + +The patches published today prevent stringifying the Server Function source code. + +<Note> + +#### Only secrets in source code may be exposed. {/*only-secrets-in-source-code-may-be-exposed*/} + +Secrets hardcoded in source code may be exposed, but runtime secrets such as `process.env.SECRET` are not affected. + +The scope of the exposed code is limited to the code inside the Server Function, which may include other functions depending on the amount of inlining your bundler provides. + +Always verify against production bundles. + +</Note> + +--- + +## Timeline {/*timeline*/} +* **December 3rd**: Leak reported to Vercel and [Meta Bug Bounty](https://bugbounty.meta.com/) by [Andrew MacPherson](https://github.com/AndrewMohawk). +* **December 4th**: Initial DoS reported to [Meta Bug Bounty](https://bugbounty.meta.com/) by [RyotaK](https://ryotak.net). +* **December 6th**: Both issues confirmed by the React team, and the team began investigating. +* **December 7th**: Initial fixes created and the React team began verifying and planning new patch. +* **December 8th**: Affected hosting providers and open source projects notified. +* **December 10th**: Hosting provider mitigations in place and patches verified. +* **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 [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/blog/index.md b/src/content/blog/index.md index a7a897634..30c4a3ffe 100644 --- a/src/content/blog/index.md +++ b/src/content/blog/index.md @@ -12,15 +12,45 @@ You can also follow the [@react.dev](https://bsky.app/profile/react.dev) account <div className="sm:-mx-5 flex flex-col gap-5 mt-12"> -<BlogCard title="React Labs: View Transitions, Activity, and more" date="April 23, 2025" url="/blog/2025/04/23/react-labs-view-transitions-activity-and-more"> +<BlogCard title="Denial of Service and Source Code Exposure in React Server Components" date="December 11, 2025" url="/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components"> -In React Labs posts, we write about projects in active research and development. In this post, we're sharing two new experimental features that are ready to try today, and sharing other areas we're working on now ... +Security researchers have found and disclosed two additional vulnerabilities in React Server Components while attempting to exploit the patches in last week’s critical vulnerability... + +</BlogCard> + +<BlogCard title="Critical Security Vulnerability in React Server Components" date="December 3, 2025" url="/blog/2025/12/03/critical-security-vulnerability-in-react-server-components"> + +There is an unauthenticated remote code execution vulnerability in React Server Components. A fix has been published in versions 19.0.1, 19.1.2, and 19.2.1. We recommend upgrading immediately. + +</BlogCard> + +<BlogCard title="React Conf 2025 Recap" date="October 16, 2025" url="/blog/2025/10/16/react-conf-2025-recap"> + +Last week we hosted React Conf 2025. In this post, we summarize the talks and announcements from the event... + +</BlogCard> + +<BlogCard title="React Compiler v1.0" date="October 7, 2025" url="/blog/2025/10/07/react-compiler-1"> + +We're releasing the compiler's first stable release today, plus linting and tooling improvements to make adoption easier. + +</BlogCard> + +<BlogCard title="Introducing the React Foundation" date="October 7, 2025" url="/blog/2025/10/07/introducing-the-react-foundation"> + +Today, we're announcing our plans to create the React Foundation and a new technical governance structure ... </BlogCard> -<BlogCard title="React Compiler RC" date="April 21, 2025" url="/blog/2025/04/21/react-compiler-rc"> +<BlogCard title="React 19.2" date="October 1, 2025" url="/blog/2025/10/01/react-19-2"> -We are releasing the compiler's first Release Candidate (RC) today. +React 19.2 adds new features like Activity, React Performance Tracks, useEffectEvent, and more. In this post ... + +</BlogCard> + +<BlogCard title="React Labs: View Transitions, Activity, and more" date="April 23, 2025" url="/blog/2025/04/23/react-labs-view-transitions-activity-and-more"> + +In React Labs posts, we write about projects in active research and development. In this post, we're sharing two new experimental features that are ready to try today, and sharing other areas we're working on now ... </BlogCard> diff --git a/src/content/community/conferences.md b/src/content/community/conferences.md index fdacf4bcf..b4110225a 100644 --- a/src/content/community/conferences.md +++ b/src/content/community/conferences.md @@ -35,12 +35,6 @@ October 31 - November 01, 2025. In-person in Goa, India (hybrid event) + Oct 15 [Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Youtube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w) - -### CityJS New Delhi 2025 {/*cityjs-newdelhi*/} -November 6-7, 2025. In-person in New Delhi, India - -[Website](https://india.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) - ### React Summit US 2025 {/*react-summit-us-2025*/} November 18 - 21, 2025. In-person in New York, USA + remote (hybrid event) @@ -51,12 +45,29 @@ November 28 & December 1, 2025. In-person in London, UK + online (hybrid event) [Website](https://reactadvanced.com/) - [Twitter](https://x.com/reactadvanced) +### CityJS Singapore 2026 {/*cityjs-singapore-2026*/} +February 4-6, 2026. In-person in Singapore + +[Website](https://india.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) + +### CityJS New Delhi 2026 {/*cityjs-newdelhi-2026*/} +February 12-13, 2026. In-person in New Delhi, India + +[Website](https://india.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) + + ### React Paris 2026 {/*react-paris-2026*/} March 26 - 27, 2026. In-person in Paris, France (hybrid event) [Website](https://react.paris/) - [Twitter](https://x.com/BeJS_) +### CityJS London 2026 {/*cityjs-london-2026*/} +April 14-17, 2026. In-person in London + +[Website](https://india.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) + + ## Past Conferences {/*past-conferences*/} diff --git a/src/content/errors/index.md b/src/content/errors/index.md index 25746d25d..d4fc3927a 100644 --- a/src/content/errors/index.md +++ b/src/content/errors/index.md @@ -7,4 +7,4 @@ In the minified production build of React, we avoid sending down full error mess We highly recommend using the development build locally when debugging your app since it tracks additional debug info and provides helpful warnings about potential problems in your apps, but if you encounter an exception while using the production build, the error message will include just a link to the docs for the error. -For an example, see: [https://react.dev/errors/149](/errors/421). +For an example, see: [https://react.dev/errors/149](/errors/149). diff --git a/src/content/learn/add-react-to-an-existing-project.md b/src/content/learn/add-react-to-an-existing-project.md index 5d3d44005..f98bece42 100644 --- a/src/content/learn/add-react-to-an-existing-project.md +++ b/src/content/learn/add-react-to-an-existing-project.md @@ -20,7 +20,7 @@ Let's say you have an existing web app at `example.com` built with another serve Here's how we recommend to set it up: -1. **Build the React part of your app** using one of the [React-based frameworks](/learn/start-a-new-react-project). +1. **Build the React part of your app** using one of the [React-based frameworks](/learn/creating-a-react-app). 2. **Specify `/some-app` as the *base path*** in your framework's configuration (here's how: [Next.js](https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath), [Gatsby](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/path-prefix/)). 3. **Configure your server or a proxy** so that all requests under `/some-app/` are handled by your React app. @@ -149,7 +149,7 @@ root.render(<NavigationBar />); Notice how the original HTML content from `index.html` is preserved, but your own `NavigationBar` React component now appears inside the `<nav id="navigation">` from your HTML. Read the [`createRoot` usage documentation](/reference/react-dom/client/createRoot#rendering-a-page-partially-built-with-react) to learn more about rendering React components inside an existing HTML page. -When you adopt React in an existing project, it's common to start with small interactive components (like buttons), and then gradually keep "moving upwards" until eventually your entire page is built with React. If you ever reach that point, we recommend migrating to [a React framework](/learn/start-a-new-react-project) right after to get the most out of React. +When you adopt React in an existing project, it's common to start with small interactive components (like buttons), and then gradually keep "moving upwards" until eventually your entire page is built with React. If you ever reach that point, we recommend migrating to [a React framework](/learn/creating-a-react-app) right after to get the most out of React. ## Using React Native in an existing native mobile app {/*using-react-native-in-an-existing-native-mobile-app*/} diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md index 185b693b1..8a2142cf9 100644 --- a/src/content/learn/build-a-react-app-from-scratch.md +++ b/src/content/learn/build-a-react-app-from-scratch.md @@ -34,7 +34,7 @@ The first step is to install a build tool like `vite`, `parcel`, or `rsbuild`. T [Vite](https://vite.dev/) is a build tool that aims to provide a faster and leaner development experience for modern web projects. <TerminalBlock> -{`npm create vite@latest my-app -- --template react`} +npm create vite@latest my-app -- --template react-ts </TerminalBlock> Vite is opinionated and comes with sensible defaults out of the box. Vite has a rich ecosystem of plugins to support fast refresh, JSX, Babel/SWC, and other common features. See Vite's [React plugin](https://vite.dev/plugins/#vitejs-plugin-react) or [React SWC plugin](https://vite.dev/plugins/#vitejs-plugin-react-swc) and [React SSR example project](https://vite.dev/guide/ssr.html#example-projects) to get started. @@ -46,7 +46,7 @@ Vite is already being used as a build tool in one of our [recommended frameworks [Parcel](https://parceljs.org/) combines a great out-of-the-box development experience with a scalable architecture that can take your project from just getting started to massive production applications. <TerminalBlock> -{`npm install --save-dev parcel`} +npm install --save-dev parcel </TerminalBlock> Parcel supports fast refresh, JSX, TypeScript, Flow, and styling out of the box. See [Parcel's React recipe](https://parceljs.org/recipes/react/#getting-started) to get started. @@ -56,7 +56,7 @@ Parcel supports fast refresh, JSX, TypeScript, Flow, and styling out of the box. [Rsbuild](https://rsbuild.dev/) is an Rspack-powered build tool that provides a seamless development experience for React applications. It comes with carefully tuned defaults and performance optimizations ready to use. <TerminalBlock> -{`npx create-rsbuild --template react`} +npx create-rsbuild --template react </TerminalBlock> Rsbuild includes built-in support for React features like fast refresh, JSX, TypeScript, and styling. See [Rsbuild's React guide](https://rsbuild.dev/guide/framework/react) to get started. @@ -97,7 +97,7 @@ Note that fetching data directly in components can lead to slower loading times If you're fetching data from most backends or REST-style APIs, we suggest using: -- [React Query](https://react-query.tanstack.com/) +- [TanStack Query](https://tanstack.com/query/) - [SWR](https://swr.vercel.app/) - [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) diff --git a/src/content/learn/choosing-the-state-structure.md b/src/content/learn/choosing-the-state-structure.md index 5be2b4d34..f6ed669ab 100644 --- a/src/content/learn/choosing-the-state-structure.md +++ b/src/content/learn/choosing-the-state-structure.md @@ -1716,7 +1716,7 @@ export const initialTravelPlan = { 34: { id: 34, title: 'Oceania', - childIds: [35, 36, 37, 38, 39, 40,, 41], + childIds: [35, 36, 37, 38, 39, 40, 41], }, 35: { id: 35, diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md index df512cca8..a65b59f6e 100644 --- a/src/content/learn/creating-a-react-app.md +++ b/src/content/learn/creating-a-react-app.md @@ -63,8 +63,8 @@ Expo is maintained by [Expo (the company)](https://expo.dev/about). Building app There are other up-and-coming frameworks that are working towards our full stack React vision: -- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more using tools like Nitro and Vite. -- [RedwoodJS](https://redwoodjs.com/): Redwood is a full stack React framework with lots of pre-installed packages and configuration that makes it easy to build full-stack web applications. +- [TanStack Start (Beta)](https://tanstack.com/start/): TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more using tools like Nitro and Vite. +- [RedwoodSDK](https://rwsdk.com/): Redwood is a full stack React framework with lots of pre-installed packages and configuration that makes it easy to build full-stack web applications. <DeepDive> diff --git a/src/content/learn/escape-hatches.md b/src/content/learn/escape-hatches.md index 0b2d595b2..ab5f666ad 100644 --- a/src/content/learn/escape-hatches.md +++ b/src/content/learn/escape-hatches.md @@ -312,12 +312,6 @@ Read **[Lifecycle of Reactive Events](/learn/lifecycle-of-reactive-effects)** to ## Separating events from Effects {/*separating-events-from-effects*/} -<Wip> - -This section describes an **experimental API that has not yet been released** in a stable version of React. - -</Wip> - Event handlers only re-run when you perform the same interaction again. Unlike event handlers, Effects re-synchronize if any of the values they read, like props or state, are different than during last render. Sometimes, you want a mix of both behaviors: an Effect that re-runs in response to some values but not others. All code inside Effects is *reactive.* It will run again if some reactive value it reads has changed due to a re-render. For example, this Effect will re-connect to the chat if either `roomId` or `theme` have changed: @@ -455,8 +449,8 @@ This is not ideal. You want to re-connect to the chat only if the `roomId` has c ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -471,7 +465,7 @@ This is not ideal. You want to re-connect to the chat only if the `roomId` has c ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createConnection, sendMessage } from './chat.js'; import { showNotification } from './notifications.js'; diff --git a/src/content/learn/react-compiler/installation.md b/src/content/learn/react-compiler/installation.md index a40b1f5af..6cce34c6b 100644 --- a/src/content/learn/react-compiler/installation.md +++ b/src/content/learn/react-compiler/installation.md @@ -18,28 +18,24 @@ This guide will help you install and configure React Compiler in your React appl React Compiler is designed to work best with React 19, but it also supports React 17 and 18. Learn more about [React version compatibility](/reference/react-compiler/target). -<Note> -React Compiler is currently in RC. Install it using the `@rc` tag to get the latest release candidate version. -</Note> - ## Installation {/*installation*/} Install React Compiler as a `devDependency`: <TerminalBlock> -npm install -D babel-plugin-react-compiler@rc +npm install -D babel-plugin-react-compiler@latest </TerminalBlock> Or with Yarn: <TerminalBlock> -yarn add -D babel-plugin-react-compiler@rc +yarn add -D babel-plugin-react-compiler@latest </TerminalBlock> Or with pnpm: <TerminalBlock> -pnpm install -D babel-plugin-react-compiler@rc +pnpm install -D babel-plugin-react-compiler@latest </TerminalBlock> ## Basic Setup {/*basic-setup*/} @@ -118,7 +114,7 @@ Please refer to the [Next.js docs](https://nextjs.org/docs/app/api-reference/nex Install `vite-plugin-babel`, and add the compiler's Babel plugin to it: <TerminalBlock> -{`npm install vite-plugin-babel`} +npm install vite-plugin-babel </TerminalBlock> ```js {3-4,16} @@ -173,10 +169,10 @@ React Compiler includes an ESLint rule that helps identify code that can't be op Install the ESLint plugin: <TerminalBlock> -npm install -D eslint-plugin-react-hooks@rc +npm install -D eslint-plugin-react-hooks@latest </TerminalBlock> -If you haven't already configured eslint-plugin-react-hooks, follow the [installation instructions in the readme](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#installation). The compiler rule is enabled by default in the latest RC, so no additional configuration is needed. +If you haven't already configured eslint-plugin-react-hooks, follow the [installation instructions in the readme](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#installation). The compiler rules are available in the `recommended-latest` preset. The ESLint rule will: - Identify violations of the [Rules of React](/reference/rules) @@ -246,4 +242,4 @@ Now that you have React Compiler installed, learn more about: - [Configuration options](/reference/react-compiler/configuration) to customize the compiler - [Incremental adoption strategies](/learn/react-compiler/incremental-adoption) for existing codebases - [Debugging techniques](/learn/react-compiler/debugging) for troubleshooting issues -- [Compiling Libraries guide](/reference/react-compiler/compiling-libraries) for compiling your React library \ No newline at end of file +- [Compiling Libraries guide](/reference/react-compiler/compiling-libraries) for compiling your React library diff --git a/src/content/learn/react-compiler/introduction.md b/src/content/learn/react-compiler/introduction.md index 96fa8802a..ff5d6eae4 100644 --- a/src/content/learn/react-compiler/introduction.md +++ b/src/content/learn/react-compiler/introduction.md @@ -16,10 +16,6 @@ React Compiler is a new build-time tool that automatically optimizes your React </YouWillLearn> -<Note> -React Compiler is currently in Release Candidate (RC). We now recommend everyone to try the compiler and provide feedback. The latest RC release can be found with the `@rc` tag. -</Note> - ## What does React Compiler do? {/*what-does-react-compiler-do*/} React Compiler automatically optimizes your React application at build time. React is often fast enough without optimization, but sometimes you need to manually memoize components and values to keep your app responsive. This manual memoization is tedious, easy to get wrong, and adds extra code to maintain. React Compiler does this optimization automatically for you, freeing you from this mental burden so you can focus on building features. @@ -28,7 +24,7 @@ React Compiler automatically optimizes your React application at build time. Rea Without the compiler, you need to manually memoize components and values to optimize re-renders: -```js {expectedErrors: {'react-compiler': [4]}} +```js import { useMemo, useCallback, memo } from 'react'; const ExpensiveComponent = memo(function ExpensiveComponent({ data, onClick }) { @@ -157,7 +153,7 @@ We encourage everyone to start using React Compiler. While the compiler is still ### Is it safe to use? {/*is-it-safe-to-use*/} -React Compiler is now in RC and has been tested extensively in production. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules). +React Compiler is now stable and has been tested extensively in production. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules). ## What build tools are supported? {/*what-build-tools-are-supported*/} @@ -169,9 +165,13 @@ Next.js users can enable the swc-invoked React Compiler by using [v15.3.1](https ## What should I do about useMemo, useCallback, and React.memo? {/*what-should-i-do-about-usememo-usecallback-and-reactmemo*/} -React Compiler adds automatic memoization more precisely and granularly than is possible with [`useMemo`](/reference/react/useMemo), [`useCallback`](/reference/react/useCallback), and [`React.memo`](/reference/react/memo). If you choose to keep manual memoization, React Compiler will analyze them and determine if your manual memoization matches its automatically inferred memoization. If there isn't a match, the compiler will choose to bail out of optimizing that component. +By default, React Compiler will memoize your code based on its analysis and heuristics. In most cases, this memoization will be as precise, or moreso, than what you may have written. + +However, in some cases developers may need more control over memoization. The `useMemo` and `useCallback` hooks can continue to be used with React Compiler as an escape hatch to provide control over which values are memoized. A common use-case for this is if a memoized value is used as an effect dependency, in order to ensure that an effect does not fire repeatedly even when its dependencies do not meaningfully change. + +For new code, we recommend relying on the compiler for memoization and using `useMemo`/`useCallback` where needed to achieve precise control. -This is done out of caution as a common anti-pattern with manual memoization is using it for correctness. This means your app depends on specific values being memoized to work properly. For example, in order to prevent an infinite loop, you may have memoized some values to stop a `useEffect` call from firing. This breaks the Rules of React, but since it can potentially be dangerous for the compiler to automatically remove manual memoization, the compiler will just bail out instead. You should manually remove your handwritten memoization and verify that your app still works as expected. +For existing code, we recommend either leaving existing memoization in place (removing it can change compilation output) or carefully testing before removing the memoization. ## Try React Compiler {/*try-react-compiler*/} diff --git a/src/content/learn/removing-effect-dependencies.md b/src/content/learn/removing-effect-dependencies.md index 7ab6dbc1f..61eb2e8d6 100644 --- a/src/content/learn/removing-effect-dependencies.md +++ b/src/content/learn/removing-effect-dependencies.md @@ -609,12 +609,6 @@ function ChatRoom({ roomId }) { ### Do you want to read a value without "reacting" to its changes? {/*do-you-want-to-read-a-value-without-reacting-to-its-changes*/} -<Wip> - -This section describes an **experimental API that has not yet been released** in a stable version of React. - -</Wip> - Suppose that you want to play a sound when the user receives a new message unless `isMuted` is `true`: ```js {3,10-12} @@ -1259,25 +1253,9 @@ Is there a line of code inside the Effect that should not be reactive? How can y <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect, useRef } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { FadeInAnimation } from './animation.js'; function Welcome({ duration }) { @@ -1386,26 +1364,10 @@ Your Effect needs to read the latest value of `duration`, but you don't want it <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect, useRef } from 'react'; import { FadeInAnimation } from './animation.js'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; function Welcome({ duration }) { const ref = useRef(null); @@ -1825,8 +1787,8 @@ Another of these functions only exists to pass some state to an imported API met ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -1907,7 +1869,7 @@ export default function App() { ```js src/ChatRoom.js active import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export default function ChatRoom({ roomId, createConnection, onMessage }) { useEffect(() => { @@ -2120,8 +2082,8 @@ As a result, the chat re-connects only when something meaningful (`roomId` or `i ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -2189,7 +2151,7 @@ export default function App() { ```js src/ChatRoom.js active import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createEncryptedConnection, createUnencryptedConnection, diff --git a/src/content/learn/reusing-logic-with-custom-hooks.md b/src/content/learn/reusing-logic-with-custom-hooks.md index de68dd190..47a4cf52a 100644 --- a/src/content/learn/reusing-logic-with-custom-hooks.md +++ b/src/content/learn/reusing-logic-with-custom-hooks.md @@ -837,12 +837,6 @@ Every time your `ChatRoom` component re-renders, it passes the latest `roomId` a ### Passing event handlers to custom Hooks {/*passing-event-handlers-to-custom-hooks*/} -<Wip> - -This section describes an **experimental API that has not yet been released** in a stable version of React. - -</Wip> - As you start using `useChatRoom` in more components, you might want to let components customize its behavior. For example, currently, the logic for what to do when a message arrives is hardcoded inside the Hook: ```js {9-11} @@ -985,7 +979,7 @@ export default function ChatRoom({ roomId }) { ```js src/useChatRoom.js import { useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createConnection } from './chat.js'; export function useChatRoom({ serverUrl, roomId, onReceiveMessage }) { @@ -1070,8 +1064,8 @@ export function showNotification(message, theme = 'dark') { ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -1666,7 +1660,7 @@ export default function App() { ```js src/useFadeIn.js active import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export function useFadeIn(ref, duration) { const [isRunning, setIsRunning] = useState(true); @@ -1716,22 +1710,6 @@ html, body { min-height: 300px; } } ``` -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - </Sandpack> However, you didn't *have to* do that. As with regular functions, ultimately you decide where to draw the boundaries between different parts of your code. You could also take a very different approach. Instead of keeping the logic in the Effect, you could move most of the imperative logic inside a JavaScript [class:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) @@ -2205,22 +2183,6 @@ It looks like your `useInterval` Hook accepts an event listener as an argument. <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useCounter } from './useCounter.js'; import { useInterval } from './useInterval.js'; @@ -2252,7 +2214,7 @@ export function useCounter(delay) { ```js src/useInterval.js import { useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export function useInterval(onTick, delay) { useEffect(() => { @@ -2276,22 +2238,6 @@ With this change, both intervals work as expected and don't interfere with each <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useCounter } from './useCounter.js'; @@ -2324,7 +2270,7 @@ export function useCounter(delay) { ```js src/useInterval.js active import { useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export function useInterval(callback, delay) { const onTick = useEffectEvent(callback); diff --git a/src/content/learn/separating-events-from-effects.md b/src/content/learn/separating-events-from-effects.md index fd603c395..5f6ce4ee8 100644 --- a/src/content/learn/separating-events-from-effects.md +++ b/src/content/learn/separating-events-from-effects.md @@ -400,13 +400,7 @@ You need a way to separate this non-reactive logic from the reactive Effect arou ### Declaring an Effect Event {/*declaring-an-effect-event*/} -<Wip> - -This section describes an **experimental API that has not yet been released** in a stable version of React. - -</Wip> - -Use a special Hook called [`useEffectEvent`](/reference/react/experimental_useEffectEvent) to extract this non-reactive logic out of your Effect: +Use a special Hook called [`useEffectEvent`](/reference/react/useEffectEvent) to extract this non-reactive logic out of your Effect: ```js {1,4-6} import { useEffect, useEffectEvent } from 'react'; @@ -448,8 +442,8 @@ Verify that the new behavior works as you would expect: ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -464,7 +458,7 @@ Verify that the new behavior works as you would expect: ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createConnection, sendMessage } from './chat.js'; import { showNotification } from './notifications.js'; @@ -574,16 +568,10 @@ 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*/} -<Wip> - -This section describes an **experimental API that has not yet been released** in a stable version of React. - -</Wip> - Effect Events let you fix many patterns where you might be tempted to suppress the dependency linter. For example, say you have an Effect to log the page visits: @@ -725,7 +713,7 @@ function Page({ url }) { } ``` -After `useEffectEvent` becomes a stable part of React, we recommend **never suppressing the linter**. +We recommend **never suppressing the linter**. The first downside of suppressing the rule is that React will no longer warn you when your Effect needs to "react" to a new reactive dependency you've introduced to your code. In the earlier example, you added `url` to the dependencies *because* React reminded you to do it. You will no longer get such reminders for any future edits to that Effect if you disable the linter. This leads to bugs. @@ -800,25 +788,9 @@ With `useEffectEvent`, there is no need to "lie" to the linter, and the code wor <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export default function App() { const [position, setPosition] = useState({ x: 0, y: 0 }); @@ -878,12 +850,6 @@ Read [Removing Effect Dependencies](/learn/removing-effect-dependencies) for oth ### Limitations of Effect Events {/*limitations-of-effect-events*/} -<Wip> - -This section describes an **experimental API that has not yet been released** in a stable version of React. - -</Wip> - Effect Events are very limited in how you can use them: * **Only call them from inside Effects.** @@ -973,23 +939,6 @@ To fix this code, it's enough to follow the rules. <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - - ```js {expectedErrors: {'react-compiler': [14]}} import { useState, useEffect } from 'react'; @@ -1043,22 +992,6 @@ If you remove the suppression comment, React will tell you that this Effect's co <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect } from 'react'; @@ -1121,25 +1054,9 @@ It seems like the Effect which sets up the timer "reacts" to the `increment` val <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export default function Timer() { const [count, setCount] = useState(0); @@ -1190,25 +1107,9 @@ To solve the issue, extract an `onTick` Effect Event from the Effect: <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export default function Timer() { const [count, setCount] = useState(0); @@ -1272,25 +1173,9 @@ Code inside Effect Events is not reactive. Are there cases in which you would _w <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export default function Timer() { const [count, setCount] = useState(0); @@ -1359,25 +1244,9 @@ The problem with the above example is that it extracted an Effect Event called ` <Sandpack> -```json package.json hidden -{ - "dependencies": { - "react": "experimental", - "react-dom": "experimental", - "react-scripts": "latest" - }, - "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test --env=jsdom", - "eject": "react-scripts eject" - } -} -``` - ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; export default function Timer() { const [count, setCount] = useState(0); @@ -1458,8 +1327,8 @@ Your Effect knows which room it connected to. Is there any information that you ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -1474,7 +1343,7 @@ Your Effect knows which room it connected to. Is there any information that you ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createConnection, sendMessage } from './chat.js'; import { showNotification } from './notifications.js'; @@ -1599,8 +1468,8 @@ To fix the issue, instead of reading the *latest* `roomId` inside the Effect Eve ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -1615,7 +1484,7 @@ To fix the issue, instead of reading the *latest* `roomId` inside the Effect Eve ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createConnection, sendMessage } from './chat.js'; import { showNotification } from './notifications.js'; @@ -1736,8 +1605,8 @@ To solve the additional challenge, save the notification timeout ID and clear it ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -1752,7 +1621,7 @@ To solve the additional challenge, save the notification timeout ID and clear it ```js import { useState, useEffect } from 'react'; -import { experimental_useEffectEvent as useEffectEvent } from 'react'; +import { useEffectEvent } from 'react'; import { createConnection, sendMessage } from './chat.js'; import { showNotification } from './notifications.js'; diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 7f61a255b..1eec63388 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -732,8 +732,8 @@ Writing `fetch` calls inside Effects is a [popular way to fetch data](https://ww This list of downsides is not specific to React. It applies to fetching data on mount with any library. Like with routing, data fetching is not trivial to do well, so we recommend the following approaches: -- **If you use a [framework](/learn/start-a-new-react-project#full-stack-frameworks), use its built-in data fetching mechanism.** Modern React frameworks have integrated data fetching mechanisms that are efficient and don't suffer from the above pitfalls. -- **Otherwise, consider using or building a client-side cache.** Popular open source solutions include [React Query](https://tanstack.com/query/latest), [useSWR](https://swr.vercel.app/), and [React Router 6.4+.](https://beta.reactrouter.com/en/main/start/overview) You can build your own solution too, in which case you would use Effects under the hood, but add logic for deduplicating requests, caching responses, and avoiding network waterfalls (by preloading data or hoisting data requirements to routes). +- **If you use a [framework](/learn/creating-a-react-app#full-stack-frameworks), use its built-in data fetching mechanism.** Modern React frameworks have integrated data fetching mechanisms that are efficient and don't suffer from the above pitfalls. +- **Otherwise, consider using or building a client-side cache.** Popular open source solutions include [TanStack Query](https://tanstack.com/query/latest), [useSWR](https://swr.vercel.app/), and [React Router 6.4+.](https://beta.reactrouter.com/en/main/start/overview) You can build your own solution too, in which case you would use Effects under the hood, but add logic for deduplicating requests, caching responses, and avoiding network waterfalls (by preloading data or hoisting data requirements to routes). You can continue fetching data directly in Effects if neither of these approaches suit you. diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md index 822891e60..216a381b5 100644 --- a/src/content/learn/thinking-in-react.md +++ b/src/content/learn/thinking-in-react.md @@ -37,7 +37,7 @@ Start by drawing boxes around every component and subcomponent in the mockup and Depending on your background, you can think about splitting up a design into components in different ways: -* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents. +* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns), that is, a component should ideally only be concerned with one thing. If it ends up growing, it should be decomposed into smaller subcomponents. * **CSS**--consider what you would make class selectors for. (However, components are a bit less granular.) * **Design**--consider how you would organize the design's layers. diff --git a/src/content/learn/typescript.md b/src/content/learn/typescript.md index 5ed72a1f5..2e6f7edc5 100644 --- a/src/content/learn/typescript.md +++ b/src/content/learn/typescript.md @@ -20,7 +20,7 @@ TypeScript is a popular way to add type definitions to JavaScript codebases. Out ## Installation {/*installation*/} -All [production-grade React frameworks](/learn/start-a-new-react-project#full-stack-frameworks) offer support for using TypeScript. Follow the framework specific guide for installation: +All [production-grade React frameworks](/learn/creating-a-react-app#full-stack-frameworks) offer support for using TypeScript. Follow the framework specific guide for installation: - [Next.js](https://nextjs.org/docs/app/building-your-application/configuring/typescript) - [Remix](https://remix.run/docs/en/1.19.2/guides/typescript) diff --git a/src/content/learn/understanding-your-ui-as-a-tree.md b/src/content/learn/understanding-your-ui-as-a-tree.md index 2abf7affc..afc38cd33 100644 --- a/src/content/learn/understanding-your-ui-as-a-tree.md +++ b/src/content/learn/understanding-your-ui-as-a-tree.md @@ -20,7 +20,7 @@ React, and many other UI libraries, model UI as a tree. Thinking of your app as ## Your UI as a tree {/*your-ui-as-a-tree*/} -Trees are a relationship model between items and UI is often represented using tree structures. For example, browsers use tree structures to model HTML ([DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction)) and CSS ([CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model)). Mobile platforms also use trees to represent their view hierarchy. +Trees are a relationship model between items. The UI is often represented using tree structures. For example, browsers use tree structures to model HTML ([DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction)) and CSS ([CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model)). Mobile platforms also use trees to represent their view hierarchy. <Diagram name="preserving_state_dom_tree" height={193} width={864} alt="Diagram with three sections arranged horizontally. In the first section, there are three rectangles stacked vertically, with labels 'Component A', 'Component B', and 'Component C'. Transitioning to the next pane is an arrow with the React logo on top labeled 'React'. The middle section contains a tree of components, with the root labeled 'A' and two children labeled 'B' and 'C'. The next section is again transitioned using an arrow with the React logo on top labeled 'React DOM'. The third and final section is a wireframe of a browser, containing a tree of 8 nodes, which has only a subset highlighted (indicating the subtree from the middle section)."> diff --git a/src/content/learn/you-might-not-need-an-effect.md b/src/content/learn/you-might-not-need-an-effect.md index 39a1dc740..81a0842eb 100644 --- a/src/content/learn/you-might-not-need-an-effect.md +++ b/src/content/learn/you-might-not-need-an-effect.md @@ -26,7 +26,7 @@ There are two common cases in which you don't need Effects: * **You don't need Effects to transform data for rendering.** For example, let's say you want to filter a list before displaying it. You might feel tempted to write an Effect that updates a state variable when the list changes. However, this is inefficient. When you update the state, React will first call your component functions to calculate what should be on the screen. Then React will ["commit"](/learn/render-and-commit) these changes to the DOM, updating the screen. Then React will run your Effects. If your Effect *also* immediately updates the state, this restarts the whole process from scratch! To avoid the unnecessary render passes, transform all the data at the top level of your components. That code will automatically re-run whenever your props or state change. * **You don't need Effects to handle user events.** For example, let's say you want to send an `/api/buy` POST request and show a notification when the user buys a product. In the Buy button click event handler, you know exactly what happened. By the time an Effect runs, you don't know *what* the user did (for example, which button was clicked). This is why you'll usually handle user events in the corresponding event handlers. -You *do* need Effects to [synchronize](/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events) with external systems. For example, you can write an Effect that keeps a jQuery widget synchronized with the React state. You can also fetch data with Effects: for example, you can synchronize the search results with the current search query. Keep in mind that modern [frameworks](/learn/start-a-new-react-project#full-stack-frameworks) provide more efficient built-in data fetching mechanisms than writing Effects directly in your components. +You *do* need Effects to [synchronize](/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events) with external systems. For example, you can write an Effect that keeps a jQuery widget synchronized with the React state. You can also fetch data with Effects: for example, you can synchronize the search results with the current search query. Keep in mind that modern [frameworks](/learn/creating-a-react-app#full-stack-frameworks) provide more efficient built-in data fetching mechanisms than writing Effects directly in your components. To help you gain the right intuition, let's look at some common concrete examples! @@ -437,7 +437,7 @@ function Game() { // βœ… Calculate all the next state in the event handler setCard(nextCard); if (nextCard.gold) { - if (goldCardCount <= 3) { + if (goldCardCount < 3) { setGoldCardCount(goldCardCount + 1); } else { setGoldCardCount(0); @@ -757,7 +757,7 @@ This ensures that when your Effect fetches data, all responses except the last r Handling race conditions is not the only difficulty with implementing data fetching. You might also want to think about caching responses (so that the user can click Back and see the previous screen instantly), how to fetch data on the server (so that the initial server-rendered HTML contains the fetched content instead of a spinner), and how to avoid network waterfalls (so that a child can fetch data without waiting for every parent). -**These issues apply to any UI library, not just React. Solving them is not trivial, which is why modern [frameworks](/learn/start-a-new-react-project#full-stack-frameworks) provide more efficient built-in data fetching mechanisms than fetching data in Effects.** +**These issues apply to any UI library, not just React. Solving them is not trivial, which is why modern [frameworks](/learn/creating-a-react-app#full-stack-frameworks) provide more efficient built-in data fetching mechanisms than fetching data in Effects.** If you don't use a framework (and don't want to build your own) but would like to make data fetching from Effects more ergonomic, consider extracting your fetching logic into a custom Hook like in this example: @@ -1106,7 +1106,7 @@ Remove the state variable and the Effect, and instead add a `useMemo` call to ca <Sandpack> -```js {expectedErrors: {'react-compiler': [8]}} +```js import { useState, useMemo } from 'react'; import { initialTodos, createTodo, getVisibleTodos } from './todos.js'; diff --git a/src/content/learn/your-first-component.md b/src/content/learn/your-first-component.md index 17fa01e98..1c38fa655 100644 --- a/src/content/learn/your-first-component.md +++ b/src/content/learn/your-first-component.md @@ -215,7 +215,7 @@ Your React application begins at a "root" component. Usually, it is created auto Most React apps use components all the way down. This means that you won't only use components for reusable pieces like buttons, but also for larger pieces like sidebars, lists, and ultimately, complete pages! Components are a handy way to organize UI code and markup, even if some of them are only used once. -[React-based frameworks](/learn/start-a-new-react-project) take this a step further. Instead of using an empty HTML file and letting React "take over" managing the page with JavaScript, they *also* generate the HTML automatically from your React components. This allows your app to show some content before the JavaScript code loads. +[React-based frameworks](/learn/creating-a-react-app) take this a step further. Instead of using an empty HTML file and letting React "take over" managing the page with JavaScript, they *also* generate the HTML automatically from your React components. This allows your app to show some content before the JavaScript code loads. Still, many websites only use React to [add interactivity to existing HTML pages.](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page) They have many root components instead of a single one for the entire page. You can use as muchβ€”or as littleβ€”React as you need. diff --git a/src/content/reference/dev-tools/react-performance-tracks.md b/src/content/reference/dev-tools/react-performance-tracks.md new file mode 100644 index 000000000..dc2912da2 --- /dev/null +++ b/src/content/reference/dev-tools/react-performance-tracks.md @@ -0,0 +1,159 @@ +--- +title: React Performance tracks +--- + +<Intro> + +React Performance tracks are specialized custom entries that appear on the Performance panel's timeline in your browser developer tools. + +</Intro> + +These tracks are designed to provide developers with comprehensive insights into their React application's performance by visualizing React-specific events and metrics alongside other critical data sources such as network requests, JavaScript execution, and event loop activity, all synchronized on a unified timeline within the Performance panel for a complete understanding of application behavior. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/overview.png" alt="React Performance Tracks" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/overview.dark.png" alt="React Performance Tracks" /> +</div> + +<InlineToc /> + +--- + +## Usage {/*usage*/} + +React Performance tracks are only available in development and profiling builds of React: + +- **Development**: enabled by default. +- **Profiling**: Only Scheduler tracks are enabled by default. The Components track only lists Components that are in subtrees wrapped with [`<Profiler>`](/reference/react/Profiler). If you have [React Developer Tools extension](/learn/react-developer-tools) enabled, all Components are included in the Components track even if they're not wrapped in `<Profiler>`. Server tracks are not available in profiling builds. + +If enabled, tracks should appear automatically in the traces you record with the Performance panel of browsers that provide [extensibility APIs](https://developer.chrome.com/docs/devtools/performance/extension). + +<Pitfall> + +The profiling instrumentation that powers React Performance tracks adds some additional overhead, so it is disabled in production builds by default. +Server Components and Server Requests tracks are only available in development builds. + +</Pitfall> + +### Using profiling builds {/*using-profiling-builds*/} + +In addition to production and development builds, React also includes a special profiling build. +To use profiling builds, you have to use `react-dom/profiling` instead of `react-dom/client`. +We recommend that you alias `react-dom/client` to `react-dom/profiling` at build time via bundler aliases instead of manually updating each `react-dom/client` import. +Your framework might have built-in support for enabling React's profiling build. + +--- + +## Tracks {/*tracks*/} + +### Scheduler {/*scheduler*/} + +The Scheduler is an internal React concept used for managing tasks with different priorities. This track consists of 4 subtracks, each representing work of a specific priority: + +- **Blocking** - The synchronous updates, which could've been initiated by user interactions. +- **Transition** - Non-blocking work that happens in the background, usually initiated via [`startTransition`](/reference/react/startTransition). +- **Suspense** - Work related to Suspense boundaries, such as displaying fallbacks or revealing content. +- **Idle** - The lowest priority work that is done when there are no other tasks with higher priority. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/scheduler.png" alt="Scheduler track" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/scheduler.dark.png" alt="Scheduler track" /> +</div> + +#### Renders {/*renders*/} + +Every render pass consists of multiple phases that you can see on a timeline: + +- **Update** - this is what caused a new render pass. +- **Render** - React renders the updated subtree by calling render functions of components. You can see the rendered components subtree on [Components track](#components), which follows the same color scheme. +- **Commit** - After rendering components, React will submit the changes to the DOM and run layout effects, like [`useLayoutEffect`](/reference/react/useLayoutEffect). +- **Remaining Effects** - React runs passive effects of a rendered subtree. This usually happens after the paint, and this is when React runs hooks like [`useEffect`](/reference/react/useEffect). One known exception is user interactions, like clicks, or other discrete events. In this scenario, this phase could run before the paint. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/scheduler-update.png" alt="Scheduler track: updates" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/scheduler-update.dark.png" alt="Scheduler track: updates" /> +</div> + +[Learn more about renders and commits](/learn/render-and-commit). + +#### Cascading updates {/*cascading-updates*/} + +Cascading updates is one of the patterns for performance regressions. If an update was scheduled during a render pass, React could discard completed work and start a new pass. + +In development builds, React can show you which Component scheduled a new update. This includes both general updates and cascading ones. You can see the enhanced stack trace by clicking on the "Cascading update" entry, which should also display the name of the method that scheduled an update. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/scheduler-cascading-update.png" alt="Scheduler track: cascading updates" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/scheduler-cascading-update.dark.png" alt="Scheduler track: cascading updates" /> +</div> + +[Learn more about Effects](/learn/you-might-not-need-an-effect). + +### Components {/*components*/} + +The Components track visualizes the durations of React components. They are displayed as a flamegraph, where each entry represents the duration of the corresponding component render and all its descendant children components. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/components-render.png" alt="Components track: render durations" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/components-render.dark.png" alt="Components track: render durations" /> +</div> + +Similar to render durations, effect durations are also represented as a flamegraph, but with a different color scheme that aligns with the corresponding phase on the Scheduler track. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/components-effects.png" alt="Components track: effects durations" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/components-effects.dark.png" alt="Components track: effects durations" /> +</div> + +<Note> + +Unlike renders, not all effects are shown on the Components track by default. + +To maintain performance and prevent UI clutter, React will only display those effects, which had a duration of 0.05ms or longer, or triggered an update. + +</Note> + +Additional events may be displayed during the render and effects phases: + +- <span style={{padding: '0.125rem 0.25rem', backgroundColor: '#facc15', color: '#1f1f1fff'}}>Mount</span> - A corresponding subtree of component renders or effects was mounted. +- <span style={{padding: '0.125rem 0.25rem', backgroundColor: '#facc15', color: '#1f1f1fff'}}>Unmount</span> - A corresponding subtree of component renders or effects was unmounted. +- <span style={{padding: '0.125rem 0.25rem', backgroundColor: '#facc15', color: '#1f1f1fff'}}>Reconnect</span> - Similar to Mount, but limited to cases when [`<Activity>`](/reference/react/Activity) is used. +- <span style={{padding: '0.125rem 0.25rem', backgroundColor: '#facc15', color: '#1f1f1fff'}}>Disconnect</span> - Similar to Unmount, but limited to cases when [`<Activity>`](/reference/react/Activity) is used. + +#### Changed props {/*changed-props*/} + +In development builds, when you click on a component render entry, you can inspect potential changes in props. You can use this information to identify unnecessary renders. + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/changed-props.png" alt="Components track: changed props" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/changed-props.dark.png" alt="Components track: changed props" /> +</div> + +### Server {/*server*/} + +<div style={{display: 'flex', justifyContent: 'center', marginBottom: '1rem'}}> + <img className="w-full light-image" src="/images/docs/performance-tracks/server-overview.png" alt="React Server Performance Tracks" /> + <img className="w-full dark-image" src="/images/docs/performance-tracks/server-overview.dark.png" alt="React Server Performance Tracks" /> +</div> + +#### Server Requests {/*server-requests*/} + +The Server Requests track visualized all Promises that eventually end up in a React Server Component. This includes any `async` operations like calling `fetch` or async Node.js file operations. + +React will try to combine Promises that are started from inside third-party code into a single span representing the the duration of the entire operation blocking 1st party code. +For example, a third party library method called `getUser` that calls `fetch` internally multiple times will be represented as a single span called `getUser`, instead of showing multiple `fetch` spans. + +Clicking on spans will show you a stack trace of where the Promise was created as well as a view of the value that the Promise resolved to, if available. + +Rejected Promises are displayed as red with their rejected value. + +#### Server Components {/*server-components*/} + +The Server Components tracks visualize the durations of React Server Components Promises they awaited. Timings are displayed as a flamegraph, where each entry represents the duration of the corresponding component render and all its descendant children components. + +If you await a Promise, React will display duration of that Promise. To see all I/O operations, use the Server Requests track. + +Different colors are used to indicate the duration of the component render. The darker the color, the longer the duration. + +The Server Components track group will always contain a "Primary" track. If React is able to render Server Components concurrently, it will display addititional "Parallel" tracks. +If more than 8 Server Components are rendered concurrently, React will associate them with the last "Parallel" track instead of adding more tracks. diff --git a/src/content/reference/eslint-plugin-react-hooks/index.md b/src/content/reference/eslint-plugin-react-hooks/index.md index 6494bd78f..b3a16bc37 100644 --- a/src/content/reference/eslint-plugin-react-hooks/index.md +++ b/src/content/reference/eslint-plugin-react-hooks/index.md @@ -1,5 +1,6 @@ --- title: eslint-plugin-react-hooks +version: rc --- <Intro> @@ -16,12 +17,15 @@ When the compiler reports a diagnostic, it means that the compiler was able to s What this means for linting, is that you don’t need to fix all violations immediately. Address them at your own pace to gradually increase the number of optimized components. </Note> -## Available Lints {/*available-lints*/} +## Recommended Rules {/*recommended*/} -* [`component-hook-factories`](/reference/eslint-plugin-react-hooks/lints/component-hook-factories) - Validates against higher order functions defining nested components or hooks +These rules are included in the `recommended` preset in `eslint-plugin-react-hooks`: + +* [`exhaustive-deps`](/reference/eslint-plugin-react-hooks/lints/exhaustive-deps) - Validates that dependency arrays for React hooks contain all necessary dependencies +* [`rules-of-hooks`](/reference/eslint-plugin-react-hooks/lints/rules-of-hooks) - Validates that components and hooks follow the Rules of Hooks +* [`component-hook-factories`](/reference/eslint-plugin-react-hooks/lints/component-hook-factories) - Validates higher order functions defining nested components or hooks * [`config`](/reference/eslint-plugin-react-hooks/lints/config) - Validates the compiler configuration options * [`error-boundaries`](/reference/eslint-plugin-react-hooks/lints/error-boundaries) - Validates usage of Error Boundaries instead of try/catch for child errors -* [`exhaustive-deps`](/reference/eslint-plugin-react-hooks/lints/exhaustive-deps) - Validates that dependency arrays for React hooks contain all necessary dependencies * [`gating`](/reference/eslint-plugin-react-hooks/lints/gating) - Validates configuration of gating mode * [`globals`](/reference/eslint-plugin-react-hooks/lints/globals) - Validates against assignment/mutation of globals during render * [`immutability`](/reference/eslint-plugin-react-hooks/lints/immutability) - Validates against mutating props, state, and other immutable values @@ -29,7 +33,6 @@ What this means for linting, is that you don’t need to fix all violations imme * [`preserve-manual-memoization`](/reference/eslint-plugin-react-hooks/lints/preserve-manual-memoization) - Validates that existing manual memoization is preserved by the compiler * [`purity`](/reference/eslint-plugin-react-hooks/lints/purity) - Validates that components/hooks are pure by checking known-impure functions * [`refs`](/reference/eslint-plugin-react-hooks/lints/refs) - Validates correct usage of refs, not reading/writing during render -* [`rules-of-hooks`](/reference/eslint-plugin-react-hooks/lints/rules-of-hooks) - Validates that components and hooks follow the Rules of Hooks * [`set-state-in-effect`](/reference/eslint-plugin-react-hooks/lints/set-state-in-effect) - Validates against calling setState synchronously in an effect * [`set-state-in-render`](/reference/eslint-plugin-react-hooks/lints/set-state-in-render) - Validates against setting state during render * [`static-components`](/reference/eslint-plugin-react-hooks/lints/static-components) - Validates that components are static, not recreated every render diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/exhaustive-deps.md b/src/content/reference/eslint-plugin-react-hooks/lints/exhaustive-deps.md index cd26483a1..daa7db6a8 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/exhaustive-deps.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/exhaustive-deps.md @@ -140,7 +140,21 @@ useEffect(() => { ## Options {/*options*/} -This rule accepts an options object: +You can configure custom effect hooks using shared ESLint settings (available in `eslint-plugin-react-hooks` 6.1.1 and later): + +```js +{ + "settings": { + "react-hooks": { + "additionalEffectHooks": "(useMyEffect|useCustomEffect)" + } + } +} +``` + +- `additionalEffectHooks`: Regex pattern matching custom hooks that should be checked for exhaustive dependencies. This configuration is shared across all `react-hooks` rules. + +For backward compatibility, this rule also accepts a rule-level option: ```js { @@ -152,4 +166,4 @@ This rule accepts an options object: } ``` -- `additionalHooks`: Regex for hooks that should be checked for exhaustive dependencies +- `additionalHooks`: Regex for hooks that should be checked for exhaustive dependencies. **Note:** If this rule-level option is specified, it takes precedence over the shared `settings` configuration. diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md b/src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md index 6508fc867..a364ab67f 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md @@ -132,7 +132,7 @@ useEffect(() => { <Note> -There are better ways to fetch data rather than in a useEffect. Consider using React Query, useSWR, or React Router 6.4+ for data fetching. These solutions handle deduplicating requests, caching responses, and avoiding network waterfalls. +There are better ways to fetch data rather than in a useEffect. Consider using TanStack Query, useSWR, or React Router 6.4+ for data fetching. These solutions handle deduplicating requests, caching responses, and avoiding network waterfalls. Learn more: [Fetching Data](/learn/synchronizing-with-effects#fetching-data) @@ -159,3 +159,21 @@ const [permissions, setPermissions] = useState( userType === 'admin' ? adminPerms : userPerms ); ``` + +## Options {/*options*/} + +You can configure custom effect hooks using shared ESLint settings (available in `eslint-plugin-react-hooks` 6.1.1 and later): + +```js +{ + "settings": { + "react-hooks": { + "additionalEffectHooks": "(useMyEffect|useCustomEffect)" + } + } +} +``` + +- `additionalEffectHooks`: Regex pattern matching custom hooks that should be treated as effects. This allows `useEffectEvent` and similar event functions to be called from your custom effect hooks. + +This shared configuration is used by both `rules-of-hooks` and `exhaustive-deps` rules, ensuring consistent behavior across all hook-related linting. diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-effect.md b/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-effect.md index 8c6a7cb47..64fa5c655 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-effect.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-effect.md @@ -71,7 +71,7 @@ function Component({selectedId, items}) { Examples of correct code for this rule: -```js {expectedErrors: {'react-compiler': [8]}} +```js // βœ… setState in an effect is fine if the value comes from a ref function Tooltip() { const ref = useRef(null); diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-render.md b/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-render.md index 61852990a..7517d5f92 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-render.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-render.md @@ -4,20 +4,20 @@ title: set-state-in-render <Intro> -Validates against setting state during render, which can trigger additional renders and potential infinite render loops. +Validates against unconditionally setting state during render, which can trigger additional renders and potential infinite render loops. </Intro> ## Rule Details {/*rule-details*/} -Calling `setState` during render triggers another render before the current one finishes. This creates an infinite loop that crashes your app. +Calling `setState` during render unconditionally triggers another render before the current one finishes. This creates an infinite loop that crashes your app. ## Common Violations {/*common-violations*/} ### Invalid {/*invalid*/} ```js {expectedErrors: {'react-compiler': [4]}} -// ❌ setState directly in render +// ❌ Unconditional setState directly in render function Component({value}) { const [count, setCount] = useState(0); setCount(value); // Infinite loop! @@ -50,6 +50,19 @@ function Component({user}) { const email = user?.email || ''; return <div>{name}</div>; } + +// βœ… Conditionally derive state from props and state from previous renders +function Component({ items }) { + const [isReverse, setIsReverse] = useState(false); + const [selection, setSelection] = useState(null); + + const [prevItems, setPrevItems] = useState(items); + if (items !== prevItems) { // This condition makes it valid + setPrevItems(items); + setSelection(null); + } + // ... +} ``` ## Troubleshooting {/*troubleshooting*/} @@ -93,3 +106,5 @@ function Counter({max}) { ``` Now the setter only runs in response to the click, React finishes the render normally, and `count` never crosses `max`. + +In rare cases, you may need to adjust state based on information from previous renders. For those, follow [this pattern](https://react.dev/reference/react/useState#storing-information-from-previous-renders) of setting state conditionally. diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/static-components.md b/src/content/reference/eslint-plugin-react-hooks/lints/static-components.md index 709303612..bd52f0703 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/static-components.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/static-components.md @@ -29,10 +29,10 @@ function Parent() { // ❌ Dynamic component creation function Parent({type}) { - const Component = type === 'button' + const Component = type === 'button' ? () => <button>Click</button> : () => <div>Text</div>; - + return <Component />; } ``` @@ -47,10 +47,10 @@ const ButtonComponent = () => <button>Click</button>; const TextComponent = () => <div>Text</div>; function Parent({type}) { - const Component = type === 'button' + const Component = type === 'button' ? ButtonComponent // Reference existing component : TextComponent; - + return <Component />; } ``` @@ -65,7 +65,7 @@ You might define components inside to access local state: // ❌ Wrong: Inner component to access parent state function Parent() { const [theme, setTheme] = useState('light'); - + function ThemedButton() { // Recreated every render! return ( <button className={theme}> @@ -73,7 +73,7 @@ function Parent() { </button> ); } - + return <ThemedButton />; } ``` diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md b/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md index 54bbe1579..a5a77e5f6 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md @@ -4,7 +4,7 @@ title: use-memo <Intro> -Validates usage of the `useMemo` hook without a return value. See [`useMemo` docs](/reference/react/useMemo) for more information. +Validates that the `useMemo` hook is used with a return value. See [`useMemo` docs](/reference/react/useMemo) for more information. </Intro> diff --git a/src/content/reference/react-compiler/compiling-libraries.md b/src/content/reference/react-compiler/compiling-libraries.md index f09ffcb72..ec0a7581e 100644 --- a/src/content/reference/react-compiler/compiling-libraries.md +++ b/src/content/reference/react-compiler/compiling-libraries.md @@ -21,7 +21,7 @@ As a library author, you can compile your library code before publishing to npm. Add React Compiler to your library's build process: <TerminalBlock> -npm install -D babel-plugin-react-compiler@rc +npm install -D babel-plugin-react-compiler@latest </TerminalBlock> Configure your build tool to compile your library. For example, with Babel: @@ -45,13 +45,13 @@ If your library supports React versions below 19, you'll need additional configu We recommend installing react-compiler-runtime as a direct dependency: <TerminalBlock> -npm install react-compiler-runtime@rc +npm install react-compiler-runtime@latest </TerminalBlock> ```json { "dependencies": { - "react-compiler-runtime": "^19.1.0-rc.2" + "react-compiler-runtime": "^1.0.0" }, "peerDependencies": { "react": "^17.0.0 || ^18.0.0 || ^19.0.0" diff --git a/src/content/reference/react-compiler/configuration.md b/src/content/reference/react-compiler/configuration.md index f38f1afc0..ec9b27e6f 100644 --- a/src/content/reference/react-compiler/configuration.md +++ b/src/content/reference/react-compiler/configuration.md @@ -130,7 +130,7 @@ module.exports = { Older React versions need the runtime package and target configuration: ```bash -npm install react-compiler-runtime@rc +npm install react-compiler-runtime@latest ``` ```js diff --git a/src/content/reference/react-compiler/target.md b/src/content/reference/react-compiler/target.md index 381748513..8ccc4a6b1 100644 --- a/src/content/reference/react-compiler/target.md +++ b/src/content/reference/react-compiler/target.md @@ -45,7 +45,7 @@ Configures the React version compatibility for the compiled output. - Always use string values, not numbers (e.g., `'17'` not `17`) - Don't include patch versions (e.g., use `'18'` not `'18.2.0'`) - React 19 includes built-in compiler runtime APIs -- React 17 and 18 require installing `react-compiler-runtime@rc` +- React 17 and 18 require installing `react-compiler-runtime@latest` --- @@ -75,7 +75,7 @@ For React 17 and React 18 projects, you need two steps: 1. Install the runtime package: ```bash -npm install react-compiler-runtime@rc +npm install react-compiler-runtime@latest ``` 2. Configure the target: @@ -114,7 +114,7 @@ If you see errors like "Cannot find module 'react/compiler-runtime'": 2. If using React 17 or 18, install the runtime: ```bash - npm install react-compiler-runtime@rc + npm install react-compiler-runtime@latest ``` 3. Ensure your target matches your React version: @@ -130,7 +130,7 @@ Ensure the runtime package is: 1. Installed in your project (not globally) 2. Listed in your `package.json` dependencies -3. The correct version (`@rc` tag) +3. The correct version (`@latest` tag) 4. Not in `devDependencies` (it's needed at runtime) ### Checking compiled output {/*checking-output*/} diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md index da12ee27c..7f6434b98 100644 --- a/src/content/reference/react-dom/client/createRoot.md +++ b/src/content/reference/react-dom/client/createRoot.md @@ -209,7 +209,7 @@ When your HTML is empty, the user sees a blank page until the app's JavaScript c <div id="root"></div> ``` -This can feel very slow! To solve this, you can generate the initial HTML from your components [on the server or during the build.](/reference/react-dom/server) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend [using a framework](/learn/start-a-new-react-project#full-stack-frameworks) that does this optimization out of the box. Depending on when it runs, this is called *server-side rendering (SSR)* or *static site generation (SSG).* +This can feel very slow! To solve this, you can generate the initial HTML from your components [on the server or during the build.](/reference/react-dom/server) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend [using a framework](/learn/creating-a-react-app#full-stack-frameworks) that does this optimization out of the box. Depending on when it runs, this is called *server-side rendering (SSR)* or *static site generation (SSG).* </Note> diff --git a/src/content/reference/react-dom/client/index.md b/src/content/reference/react-dom/client/index.md index a00422023..b612d7ba6 100644 --- a/src/content/reference/react-dom/client/index.md +++ b/src/content/reference/react-dom/client/index.md @@ -4,7 +4,7 @@ title: Client React DOM APIs <Intro> -The `react-dom/client` APIs let you render React components on the client (in the browser). These APIs are typically used at the top level of your app to initialize your React tree. A [framework](/learn/start-a-new-react-project#full-stack-frameworks) may call them for you. Most of your components don't need to import or use them. +The `react-dom/client` APIs let you render React components on the client (in the browser). These APIs are typically used at the top level of your app to initialize your React tree. A [framework](/learn/creating-a-react-app#full-stack-frameworks) may call them for you. Most of your components don't need to import or use them. </Intro> diff --git a/src/content/reference/react-dom/components/form.md b/src/content/reference/react-dom/components/form.md index b17b1a40b..1043b13a0 100644 --- a/src/content/reference/react-dom/components/form.md +++ b/src/content/reference/react-dom/components/form.md @@ -278,7 +278,7 @@ export default function Search() { Displaying a form submission error message before the JavaScript bundle loads for progressive enhancement requires that: -1. `<form>` be rendered by a [Server Component](/reference/rsc/use-client) +1. `<form>` be rendered by a [Client Component](/reference/rsc/use-client) 1. the function passed to the `<form>`'s `action` prop be a [Server Function](/reference/rsc/server-functions) 1. the `useActionState` Hook be used to display the error message diff --git a/src/content/reference/react-dom/createPortal.md b/src/content/reference/react-dom/createPortal.md index 4521dfa47..e806660e8 100644 --- a/src/content/reference/react-dom/createPortal.md +++ b/src/content/reference/react-dom/createPortal.md @@ -398,8 +398,7 @@ Here is a complete example you can play with: } ``` -{/* TODO(@poteto) - fixed by https://github.com/facebook/react/pull/34462. need a new release */} -```js {expectedErrors: {'react-compiler': [15]}} src/App.js +```js src/App.js import { useRef, useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { createMapWidget, addPopupToMapWidget } from './map-widget.js'; diff --git a/src/content/reference/react-dom/hooks/index.md b/src/content/reference/react-dom/hooks/index.md index 5dfb07d82..5bda2b5ad 100644 --- a/src/content/reference/react-dom/hooks/index.md +++ b/src/content/reference/react-dom/hooks/index.md @@ -4,7 +4,7 @@ title: "Built-in React DOM Hooks" <Intro> -The `react-dom` package contains Hooks that are only supported for web applications (which run in the browser DOM environment). These Hooks are not supported in non-browser environments like iOS, Android, or Windows applications. If you are looking for Hooks that are supported in web browsers *and other environments* see [the React Hooks page](/reference/react). This page lists all the Hooks in the `react-dom` package. +The `react-dom` package contains Hooks that are only supported for web applications (which run in the browser DOM environment). These Hooks are not supported in non-browser environments like iOS, Android, or Windows applications. If you are looking for Hooks that are supported in web browsers *and other environments* see [the React Hooks page](/reference/react/hooks). This page lists all the Hooks in the `react-dom` package. </Intro> diff --git a/src/content/reference/react-dom/index.md b/src/content/reference/react-dom/index.md index b79b16db6..d01bd6562 100644 --- a/src/content/reference/react-dom/index.md +++ b/src/content/reference/react-dom/index.md @@ -21,7 +21,7 @@ These APIs can be imported from your components. They are rarely used: These APIs can be used to make apps faster by pre-loading resources such as scripts, stylesheets, and fonts as soon as you know you need them, for example before navigating to another page where the resources will be used. -[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call these APIs yourself. Consult your framework's documentation for details. +[React-based frameworks](/learn/creating-a-react-app) frequently handle resource loading for you, so you might not have to call these APIs yourself. Consult your framework's documentation for details. * [`prefetchDNS`](/reference/react-dom/prefetchDNS) lets you prefetch the IP address of a DNS domain name that you expect to connect to. * [`preconnect`](/reference/react-dom/preconnect) lets you connect to a server you expect to request resources from, even if you don't know what resources you'll need yet. diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md index 117fccac8..5dcaaf933 100644 --- a/src/content/reference/react-dom/preinit.md +++ b/src/content/reference/react-dom/preinit.md @@ -4,7 +4,7 @@ title: preinit <Note> -[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. +[React-based frameworks](/learn/creating-a-react-app) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. </Note> diff --git a/src/content/reference/react-dom/preinitModule.md b/src/content/reference/react-dom/preinitModule.md index 97bb4dbc7..93a4a730f 100644 --- a/src/content/reference/react-dom/preinitModule.md +++ b/src/content/reference/react-dom/preinitModule.md @@ -4,7 +4,7 @@ title: preinitModule <Note> -[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. +[React-based frameworks](/learn/creating-a-react-app) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. </Note> diff --git a/src/content/reference/react-dom/preload.md b/src/content/reference/react-dom/preload.md index 5dcba10f7..e9d00fc60 100644 --- a/src/content/reference/react-dom/preload.md +++ b/src/content/reference/react-dom/preload.md @@ -4,7 +4,7 @@ title: preload <Note> -[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. +[React-based frameworks](/learn/creating-a-react-app) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. </Note> diff --git a/src/content/reference/react-dom/preloadModule.md b/src/content/reference/react-dom/preloadModule.md index ebc2fa6d0..944d438fc 100644 --- a/src/content/reference/react-dom/preloadModule.md +++ b/src/content/reference/react-dom/preloadModule.md @@ -4,7 +4,7 @@ title: preloadModule <Note> -[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. +[React-based frameworks](/learn/creating-a-react-app) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. </Note> diff --git a/src/content/reference/react-dom/server/index.md b/src/content/reference/react-dom/server/index.md index 72972c327..1856acd71 100644 --- a/src/content/reference/react-dom/server/index.md +++ b/src/content/reference/react-dom/server/index.md @@ -4,25 +4,33 @@ title: Server React DOM APIs <Intro> -The `react-dom/server` APIs let you server-side render React components to HTML. These APIs are only used on the server at the top level of your app to generate the initial HTML. A [framework](/learn/start-a-new-react-project#full-stack-frameworks) may call them for you. Most of your components don't need to import or use them. +The `react-dom/server` APIs let you server-side render React components to HTML. These APIs are only used on the server at the top level of your app to generate the initial HTML. A [framework](/learn/creating-a-react-app#full-stack-frameworks) may call them for you. Most of your components don't need to import or use them. </Intro> --- -## Server APIs for Node.js Streams {/*server-apis-for-nodejs-streams*/} +## Server APIs for Web Streams {/*server-apis-for-web-streams*/} -These methods are only available in the environments with [Node.js Streams:](https://nodejs.org/api/stream.html) +These methods are only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), which includes browsers, Deno, and some modern edge runtimes: -* [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) renders a React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html) +* [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) +* [`resume`](/reference/react-dom/server/renderToPipeableStream) resumes [`prerender`](/reference/react-dom/static/prerender) to a [Readable Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). + + +<Note> +Node.js also includes these methods for compatibility, but they are not recommended due to worse performance. Use the [dedicated Node.js APIs](#server-apis-for-nodejs-streams) instead. + +</Note> --- -## Server APIs for Web Streams {/*server-apis-for-web-streams*/} +## Server APIs for Node.js Streams {/*server-apis-for-nodejs-streams*/} -These methods are only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), which includes browsers, Deno, and some modern edge runtimes: +These methods are only available in the environments with [Node.js Streams:](https://nodejs.org/api/stream.html) -* [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) +* [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) renders a React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html) +* [`resumeToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) resumes [`prerenderToNodeStream`](/reference/react-dom/static/prerenderToNodeStream) to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html) --- diff --git a/src/content/reference/react-dom/server/resume.md b/src/content/reference/react-dom/server/resume.md new file mode 100644 index 000000000..17b48b2ac --- /dev/null +++ b/src/content/reference/react-dom/server/resume.md @@ -0,0 +1,236 @@ +--- +title: resume +--- + +<Intro> + +`resume` streams a pre-rendered React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) + +```js +const stream = await resume(reactNode, postponedState, options?) +``` + +</Intro> + +<InlineToc /> + +<Note> + +This API depends on [Web Streams.](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) For Node.js, use [`resumeToNodeStream`](/reference/react-dom/server/renderToPipeableStream) instead. + +</Note> + +--- + +## Reference {/*reference*/} + +### `resume(node, postponedState, options?)` {/*resume*/} + +Call `resume` to resume rendering a pre-rendered React tree as HTML into a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) + +```js +import { resume } from 'react-dom/server'; +import {getPostponedState} from './storage'; + +async function handler(request, writable) { + const postponed = await getPostponedState(request); + const resumeStream = await resume(<App />, postponed); + return resumeStream.pipeTo(writable) +} +``` + +[See more examples below.](#usage) + +#### Parameters {/*parameters*/} + +* `reactNode`: The React node you called `prerender` with. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag. +* `postponedState`: The opaque `postpone` object returned from a [prerender API](/reference/react-dom/static/index), loaded from wherever you stored it (e.g. redis, a file, or S3). +* **optional** `options`: An object with streaming options. + * **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src). + * **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client. + * **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-outside-the-shell) or [not.](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](/reference/react-dom/server/renderToReadableStream#logging-crashes-on-the-server) make sure that you still call `console.error`. + + +#### Returns {/*returns*/} + +`resume` returns a Promise: + +- If `resume` successfully produced a [shell](/reference/react-dom/server/renderToReadableStream#specifying-what-goes-into-the-shell), that Promise will resolve to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) that can be piped to a [Writable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream). +- If an error happens in the shell, the Promise will reject with that error. + +The returned stream has an additional property: + +* `allReady`: A Promise that resolves when all rendering is complete. You can `await stream.allReady` before returning a response [for crawlers and static generation.](/reference/react-dom/server/renderToReadableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation) If you do that, you won't get any progressive loading. The stream will contain the final HTML. + +#### Caveats {/*caveats*/} + +- `resume` does not accept options for `bootstrapScripts`, `bootstrapScriptContent`, or `bootstrapModules`. Instead, you need to pass these options to the `prerender` call that generates the `postponedState`. You can also inject bootstrap content into the writable stream manually. +- `resume` does not accept `identifierPrefix` since the prefix needs to be the same in both `prerender` and `resume`. +- Since `nonce` cannot be provided to prerender, you should only provide `nonce` to `resume` if you're not providing scripts to prerender. +- `resume` re-renders from the root until it finds a component that was not fully pre-rendered. Only fully prerendered Components (the Component and its children finished prerendering) are skipped entirely. + +## Usage {/*usage*/} + +### Resuming a prerender {/*resuming-a-prerender*/} + +<Sandpack> + +```js src/App.js hidden +``` + +```html public/index.html +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Document + + + + + +``` + +```js src/index.js +import { + flushReadableStreamToFrame, + getUser, + Postponed, + sleep, +} from "./demo-helpers"; +import { StrictMode, Suspense, use, useEffect } from "react"; +import { prerender } from "react-dom/static"; +import { resume } from "react-dom/server"; +import { hydrateRoot } from "react-dom/client"; + +function Header() { + return
    Me and my descendants can be prerendered
    ; +} + +const { promise: cookies, resolve: resolveCookies } = Promise.withResolvers(); + +function Main() { + const { sessionID } = use(cookies); + const user = getUser(sessionID); + + useEffect(() => { + console.log("reached interactivity!"); + }, []); + + return ( +
    + Hello, {user.name}! + +
    + ); +} + +function Shell({ children }) { + // In a real app, this is where you would put your html and body. + // We're just using tags here we can include in an existing body for demonstration purposes + return ( + + {children} + + ); +} + +function App() { + return ( + + +
    + + +
    + + + ); +} + +async function main(frame) { + // Layer 1 + const controller = new AbortController(); + const prerenderedApp = prerender(, { + signal: controller.signal, + onError(error) { + if (error instanceof Postponed) { + } else { + console.error(error); + } + }, + }); + // We're immediately aborting in a macrotask. + // Any data fetching that's not available synchronously, or in a microtask, will not have finished. + setTimeout(() => { + controller.abort(new Postponed()); + }); + + const { prelude, postponed } = await prerenderedApp; + await flushReadableStreamToFrame(prelude, frame); + + // Layer 2 + // Just waiting here for demonstration purposes. + // In a real app, the prelude and postponed state would've been serialized in Layer 1 and Layer would deserialize them. + // The prelude content could be flushed immediated as plain HTML while + // React is continuing to render from where the prerender left off. + await sleep(2000); + + // You would get the cookies from the incoming HTTP request + resolveCookies({ sessionID: "abc" }); + + const stream = await resume(, postponed); + + await flushReadableStreamToFrame(stream, frame); + + // Layer 3 + // Just waiting here for demonstration purposes. + await sleep(2000); + + hydrateRoot(frame.contentWindow.document, ); +} + +main(document.getElementById("container")); + +``` + +```js src/demo-helpers.js +export async function flushReadableStreamToFrame(readable, frame) { + const document = frame.contentWindow.document; + const decoder = new TextDecoder(); + for await (const chunk of readable) { + const partialHTML = decoder.decode(chunk); + document.write(partialHTML); + } +} + +// This doesn't need to be an error. +// You can use any other means to check if an error during prerender was +// from an intentional abort or a real error. +export class Postponed extends Error {} + +// We're just hardcoding a session here. +export function getUser(sessionID) { + return { + name: "Alice", + }; +} + +export function sleep(timeoutMS) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, timeoutMS); + }); +} +``` + + + +### Further reading {/*further-reading*/} + +Resuming behaves like `renderToReadableStream`. For more examples, check out the [usage section of `renderToReadableStream`](/reference/react-dom/server/renderToReadableStream#usage). +The [usage section of `prerender`](/reference/react-dom/static/prerender#usage) includes examples of how to use `prerender` specifically. \ No newline at end of file diff --git a/src/content/reference/react-dom/server/resumeToPipeableStream.md b/src/content/reference/react-dom/server/resumeToPipeableStream.md new file mode 100644 index 000000000..48caa3be6 --- /dev/null +++ b/src/content/reference/react-dom/server/resumeToPipeableStream.md @@ -0,0 +1,78 @@ +--- +title: resumeToPipeableStream +--- + + + +`resumeToPipeableStream` streams a pre-rendered React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html) + +```js +const {pipe, abort} = await resumeToPipeableStream(reactNode, postponedState, options?) +``` + + + + + + + +This API is specific to Node.js. Environments with [Web Streams,](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) like Deno and modern edge runtimes, should use [`resume`](/reference/react-dom/server/renderToReadableStream) instead. + + + +--- + +## Reference {/*reference*/} + +### `resumeToPipeableStream(node, postponed, options?)` {/*resume-to-pipeable-stream*/} + +Call `resume` to resume rendering a pre-rendered React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams) + +```js +import { resume } from 'react-dom/server'; +import {getPostponedState} from './storage'; + +async function handler(request, response) { + const postponed = await getPostponedState(request); + const {pipe} = resumeToPipeableStream(, postponed, { + onShellReady: () => { + pipe(response); + } + }); +} +``` + +[See more examples below.](#usage) + +#### Parameters {/*parameters*/} + +* `reactNode`: The React node you called `prerender` with. For example, a JSX element like ``. It is expected to represent the entire document, so the `App` component should render the `` tag. +* `postponedState`: The opaque `postpone` object returned from a [prerender API](/reference/react-dom/static/index), loaded from wherever you stored it (e.g. redis, a file, or S3). +* **optional** `options`: An object with streaming options. + * **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src). + * **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client. + * **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-outside-the-shell) or [not.](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](/reference/react-dom/server/renderToReadableStream#logging-crashes-on-the-server) make sure that you still call `console.error`. + * **optional** `onShellReady`: A callback that fires right after the [shell](#specifying-what-goes-into-the-shell) has finished. You can call `pipe` here to start streaming. React will [stream the additional content](#streaming-more-content-as-it-loads) after the shell along with the inline `