diff --git a/.claude/agents/docs-reviewer.md b/.claude/agents/docs-reviewer.md new file mode 100644 index 0000000000..af0a856e45 --- /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 0000000000..4648ad90df --- /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 0000000000..4b75f27a12 --- /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 0000000000..0904a98c09 --- /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 0000000000..124e5f048f --- /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 0000000000..ef28225f81 --- /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 0000000000..57dc9ef745 --- /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 0000000000..e63c00fcaa --- /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 0000000000..5ebcdee37d --- /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 0000000000..61a6a0e05c --- /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 4738cb6975..3c83df826c 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ scripts plugins next.config.js +.claude/ diff --git a/.eslintrc b/.eslintrc index f8b03f98a1..7bc6ab9333 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,18 +2,36 @@ "root": true, "extends": "next/core-web-vitals", "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint", "eslint-plugin-react-compiler"], + "plugins": ["@typescript-eslint", "eslint-plugin-react-compiler", "local-rules"], "rules": { "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": ["error", {"varsIgnorePattern": "^_"}], "react-hooks/exhaustive-deps": "error", "react/no-unknown-property": ["error", {"ignore": ["meta"]}], - "react-compiler/react-compiler": "error" + "react-compiler/react-compiler": "error", + "local-rules/lint-markdown-code-blocks": "error" }, "env": { "node": true, "commonjs": true, "browser": true, "es6": true - } + }, + "overrides": [ + { + "files": ["src/content/**/*.md"], + "parser": "./eslint-local-rules/parser", + "parserOptions": { + "sourceType": "module" + }, + "rules": { + "no-unused-vars": "off", + "@typescript-eslint/no-unused-vars": "off", + "react-hooks/exhaustive-deps": "off", + "react/no-unknown-property": "off", + "react-compiler/react-compiler": "off", + "local-rules/lint-markdown-code-blocks": "error" + } + } + ] } diff --git a/.github/ISSUE_TEMPLATE/3-framework.yml b/.github/ISSUE_TEMPLATE/3-framework.yml index a47295e1e8..87f03a660b 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 7bf71dbc5d..ff88094dee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies -/node_modules +node_modules /.pnp .pnp.js @@ -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 0000000000..3a081e6d51 --- /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/colors.js b/colors.js index 872f33cac2..2b282c820c 100644 --- a/colors.js +++ b/colors.js @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/eslint-local-rules/__tests__/fixtures/src/content/basic-error.md b/eslint-local-rules/__tests__/fixtures/src/content/basic-error.md new file mode 100644 index 0000000000..8e7670fdcd --- /dev/null +++ b/eslint-local-rules/__tests__/fixtures/src/content/basic-error.md @@ -0,0 +1,8 @@ +```jsx +import {useState} from 'react'; +function Counter() { + const [count, setCount] = useState(0); + setCount(count + 1); + return <div>{count}</div>; +} +``` diff --git a/eslint-local-rules/__tests__/fixtures/src/content/duplicate-metadata.md b/eslint-local-rules/__tests__/fixtures/src/content/duplicate-metadata.md new file mode 100644 index 0000000000..67d6b62bbd --- /dev/null +++ b/eslint-local-rules/__tests__/fixtures/src/content/duplicate-metadata.md @@ -0,0 +1,8 @@ +```jsx title="Counter" {expectedErrors: {'react-compiler': [99]}} {expectedErrors: {'react-compiler': [2]}} +import {useState} from 'react'; +function Counter() { + const [count, setCount] = useState(0); + setCount(count + 1); + return <div>{count}</div>; +} +``` diff --git a/eslint-local-rules/__tests__/fixtures/src/content/malformed-metadata.md b/eslint-local-rules/__tests__/fixtures/src/content/malformed-metadata.md new file mode 100644 index 0000000000..fd542bf03a --- /dev/null +++ b/eslint-local-rules/__tests__/fixtures/src/content/malformed-metadata.md @@ -0,0 +1,8 @@ +```jsx {expectedErrors: {'react-compiler': 'invalid'}} +import {useState} from 'react'; +function Counter() { + const [count, setCount] = useState(0); + setCount(count + 1); + return <div>{count}</div>; +} +``` diff --git a/eslint-local-rules/__tests__/fixtures/src/content/mixed-language.md b/eslint-local-rules/__tests__/fixtures/src/content/mixed-language.md new file mode 100644 index 0000000000..313b0e30fd --- /dev/null +++ b/eslint-local-rules/__tests__/fixtures/src/content/mixed-language.md @@ -0,0 +1,7 @@ +```bash +setCount() +``` + +```txt +import {useState} from 'react'; +``` diff --git a/eslint-local-rules/__tests__/fixtures/src/content/stale-expected-error.md b/eslint-local-rules/__tests__/fixtures/src/content/stale-expected-error.md new file mode 100644 index 0000000000..46e330ac0e --- /dev/null +++ b/eslint-local-rules/__tests__/fixtures/src/content/stale-expected-error.md @@ -0,0 +1,5 @@ +```jsx {expectedErrors: {'react-compiler': [3]}} +function Hello() { + return <h1>Hello</h1>; +} +``` diff --git a/eslint-local-rules/__tests__/fixtures/src/content/suppressed-error.md b/eslint-local-rules/__tests__/fixtures/src/content/suppressed-error.md new file mode 100644 index 0000000000..ecefa8495c --- /dev/null +++ b/eslint-local-rules/__tests__/fixtures/src/content/suppressed-error.md @@ -0,0 +1,8 @@ +```jsx {expectedErrors: {'react-compiler': [4]}} +import {useState} from 'react'; +function Counter() { + const [count, setCount] = useState(0); + setCount(count + 1); + return <div>{count}</div>; +} +``` diff --git a/eslint-local-rules/__tests__/lint-markdown-code-blocks.test.js b/eslint-local-rules/__tests__/lint-markdown-code-blocks.test.js new file mode 100644 index 0000000000..250e0a1e58 --- /dev/null +++ b/eslint-local-rules/__tests__/lint-markdown-code-blocks.test.js @@ -0,0 +1,131 @@ +/** + * 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. + */ + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const {ESLint} = require('eslint'); +const plugin = require('..'); + +const FIXTURES_DIR = path.join( + __dirname, + 'fixtures', + 'src', + 'content' +); +const PARSER_PATH = path.join(__dirname, '..', 'parser.js'); + +function createESLint({fix = false} = {}) { + return new ESLint({ + useEslintrc: false, + fix, + plugins: { + 'local-rules': plugin, + }, + overrideConfig: { + parser: PARSER_PATH, + plugins: ['local-rules'], + rules: { + 'local-rules/lint-markdown-code-blocks': 'error', + }, + parserOptions: { + sourceType: 'module', + }, + }, + }); +} + +function readFixture(name) { + return fs.readFileSync(path.join(FIXTURES_DIR, name), 'utf8'); +} + +async function lintFixture(name, {fix = false} = {}) { + const eslint = createESLint({fix}); + const filePath = path.join(FIXTURES_DIR, name); + const markdown = readFixture(name); + const [result] = await eslint.lintText(markdown, {filePath}); + return result; +} + +async function run() { + const basicResult = await lintFixture('basic-error.md'); + assert.strictEqual( + basicResult.messages.length, + 1, + 'expected one diagnostic' + ); + assert( + basicResult.messages[0].message.includes('Calling setState during render'), + 'expected message to mention setState during render' + ); + + const suppressedResult = await lintFixture('suppressed-error.md'); + assert.strictEqual( + suppressedResult.messages.length, + 0, + 'expected suppression metadata to silence diagnostic' + ); + + const staleResult = await lintFixture('stale-expected-error.md'); + assert.strictEqual( + staleResult.messages.length, + 1, + 'expected stale metadata error' + ); + assert.strictEqual( + staleResult.messages[0].message, + 'React Compiler expected error on line 3 was not triggered' + ); + + const duplicateResult = await lintFixture('duplicate-metadata.md'); + assert.strictEqual( + duplicateResult.messages.length, + 2, + 'expected duplicate metadata to surface compiler diagnostic and stale metadata notice' + ); + const duplicateFixed = await lintFixture('duplicate-metadata.md', { + fix: true, + }); + assert( + duplicateFixed.output.includes( + "{expectedErrors: {'react-compiler': [4]}}" + ), + 'expected duplicates to be rewritten to a single canonical block' + ); + assert( + !duplicateFixed.output.includes('[99]'), + 'expected stale line numbers to be removed from metadata' + ); + + const mixedLanguageResult = await lintFixture('mixed-language.md'); + assert.strictEqual( + mixedLanguageResult.messages.length, + 0, + 'expected non-js code fences to be ignored' + ); + + const malformedResult = await lintFixture('malformed-metadata.md'); + assert.strictEqual( + malformedResult.messages.length, + 1, + 'expected malformed metadata to fall back to compiler diagnostics' + ); + const malformedFixed = await lintFixture('malformed-metadata.md', { + fix: true, + }); + assert( + malformedFixed.output.includes( + "{expectedErrors: {'react-compiler': [4]}}" + ), + 'expected malformed metadata to be replaced with canonical form' + ); +} + +run().catch(error => { + console.error(error); + process.exitCode = 1; +}); diff --git a/eslint-local-rules/index.js b/eslint-local-rules/index.js new file mode 100644 index 0000000000..b1f747ccb4 --- /dev/null +++ b/eslint-local-rules/index.js @@ -0,0 +1,14 @@ +/** + * 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. + */ + +const lintMarkdownCodeBlocks = require('./rules/lint-markdown-code-blocks'); + +module.exports = { + rules: { + 'lint-markdown-code-blocks': lintMarkdownCodeBlocks, + }, +}; diff --git a/eslint-local-rules/package.json b/eslint-local-rules/package.json new file mode 100644 index 0000000000..9940fee200 --- /dev/null +++ b/eslint-local-rules/package.json @@ -0,0 +1,12 @@ +{ + "name": "eslint-plugin-local-rules", + "version": "0.0.0", + "main": "index.js", + "private": "true", + "scripts": { + "test": "node __tests__/lint-markdown-code-blocks.test.js" + }, + "devDependencies": { + "eslint-mdx": "^2" + } +} diff --git a/eslint-local-rules/parser.js b/eslint-local-rules/parser.js new file mode 100644 index 0000000000..043f2e520d --- /dev/null +++ b/eslint-local-rules/parser.js @@ -0,0 +1,8 @@ +/** + * 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. + */ + +module.exports = require('eslint-mdx'); diff --git a/eslint-local-rules/rules/diagnostics.js b/eslint-local-rules/rules/diagnostics.js new file mode 100644 index 0000000000..4e433164b5 --- /dev/null +++ b/eslint-local-rules/rules/diagnostics.js @@ -0,0 +1,77 @@ +/** + * 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. + */ + +function getRelativeLine(loc) { + return loc?.start?.line ?? loc?.line ?? 1; +} + +function getRelativeColumn(loc) { + return loc?.start?.column ?? loc?.column ?? 0; +} + +function getRelativeEndLine(loc, fallbackLine) { + if (loc?.end?.line != null) { + return loc.end.line; + } + if (loc?.line != null) { + return loc.line; + } + return fallbackLine; +} + +function getRelativeEndColumn(loc, fallbackColumn) { + if (loc?.end?.column != null) { + return loc.end.column; + } + if (loc?.column != null) { + return loc.column; + } + return fallbackColumn; +} + +/** + * @param {import('./markdown').MarkdownCodeBlock} block + * @param {Array<{detail: any, loc: any, message: string}>} diagnostics + * @returns {Array<{detail: any, message: string, relativeStartLine: number, markdownLoc: {start: {line: number, column: number}, end: {line: number, column: number}}}>} + */ +function normalizeDiagnostics(block, diagnostics) { + return diagnostics.map(({detail, loc, message}) => { + const relativeStartLine = Math.max(getRelativeLine(loc), 1); + const relativeStartColumn = Math.max(getRelativeColumn(loc), 0); + const relativeEndLine = Math.max( + getRelativeEndLine(loc, relativeStartLine), + relativeStartLine + ); + const relativeEndColumn = Math.max( + getRelativeEndColumn(loc, relativeStartColumn), + relativeStartColumn + ); + + const markdownStartLine = block.codeStartLine + relativeStartLine - 1; + const markdownEndLine = block.codeStartLine + relativeEndLine - 1; + + return { + detail, + message, + relativeStartLine, + markdownLoc: { + start: { + line: markdownStartLine, + column: relativeStartColumn, + }, + end: { + line: markdownEndLine, + column: relativeEndColumn, + }, + }, + }; + }); +} + +module.exports = { + normalizeDiagnostics, +}; diff --git a/eslint-local-rules/rules/lint-markdown-code-blocks.js b/eslint-local-rules/rules/lint-markdown-code-blocks.js new file mode 100644 index 0000000000..5ec327947b --- /dev/null +++ b/eslint-local-rules/rules/lint-markdown-code-blocks.js @@ -0,0 +1,178 @@ +/** + * 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. + */ + +const { + buildFenceLine, + getCompilerExpectedLines, + getSortedUniqueNumbers, + hasCompilerEntry, + metadataEquals, + metadataHasExpectedErrorsToken, + removeCompilerExpectedLines, + setCompilerExpectedLines, +} = require('./metadata'); +const {normalizeDiagnostics} = require('./diagnostics'); +const {parseMarkdownFile} = require('./markdown'); +const {runReactCompiler} = require('./react-compiler'); + +module.exports = { + meta: { + type: 'problem', + docs: { + description: 'Run React Compiler on markdown code blocks', + category: 'Possible Errors', + }, + fixable: 'code', + hasSuggestions: true, + schema: [], + }, + + create(context) { + return { + Program(node) { + const filename = context.getFilename(); + if (!filename.endsWith('.md') || !filename.includes('src/content')) { + return; + } + + const sourceCode = context.getSourceCode(); + const {blocks} = parseMarkdownFile(sourceCode.text, filename); + // For each supported code block, run the compiler and reconcile metadata. + for (const block of blocks) { + const compilerResult = runReactCompiler( + block.code, + `${filename}#codeblock` + ); + + const expectedLines = getCompilerExpectedLines(block.metadata); + const expectedLineSet = new Set(expectedLines); + const diagnostics = normalizeDiagnostics( + block, + compilerResult.diagnostics + ); + + const errorLines = new Set(); + const unexpectedDiagnostics = []; + + for (const diagnostic of diagnostics) { + const line = diagnostic.relativeStartLine; + errorLines.add(line); + if (!expectedLineSet.has(line)) { + unexpectedDiagnostics.push(diagnostic); + } + } + + const normalizedErrorLines = getSortedUniqueNumbers( + Array.from(errorLines) + ); + const missingExpectedLines = expectedLines.filter( + (line) => !errorLines.has(line) + ); + + const desiredMetadata = normalizedErrorLines.length + ? setCompilerExpectedLines(block.metadata, normalizedErrorLines) + : removeCompilerExpectedLines(block.metadata); + + // Compute canonical metadata and attach an autofix when it differs. + const metadataChanged = !metadataEquals( + block.metadata, + desiredMetadata + ); + const replacementLine = buildFenceLine(block.lang, desiredMetadata); + const replacementDiffers = block.fence.rawText !== replacementLine; + const applyReplacementFix = replacementDiffers + ? (fixer) => + fixer.replaceTextRange(block.fence.range, replacementLine) + : null; + + const hasDuplicateMetadata = + block.metadata.hadDuplicateExpectedErrors; + const hasExpectedErrorsMetadata = metadataHasExpectedErrorsToken( + block.metadata + ); + + const shouldFixUnexpected = + Boolean(applyReplacementFix) && + normalizedErrorLines.length > 0 && + (metadataChanged || + hasDuplicateMetadata || + !hasExpectedErrorsMetadata); + + let fixAlreadyAttached = false; + + for (const diagnostic of unexpectedDiagnostics) { + const reportData = { + node, + loc: diagnostic.markdownLoc, + message: diagnostic.message, + }; + + if ( + shouldFixUnexpected && + applyReplacementFix && + !fixAlreadyAttached + ) { + reportData.fix = applyReplacementFix; + reportData.suggest = [ + { + desc: 'Add expectedErrors metadata to suppress these errors', + fix: applyReplacementFix, + }, + ]; + fixAlreadyAttached = true; + } + + context.report(reportData); + } + + // Assert that expectedErrors is actually needed + if ( + Boolean(applyReplacementFix) && + missingExpectedLines.length > 0 && + hasCompilerEntry(block.metadata) + ) { + const plural = missingExpectedLines.length > 1; + const message = plural + ? `React Compiler expected errors on lines ${missingExpectedLines.join( + ', ' + )} were not triggered` + : `React Compiler expected error on line ${missingExpectedLines[0]} was not triggered`; + + const reportData = { + node, + loc: { + start: { + line: block.position.start.line, + column: 0, + }, + end: { + line: block.position.start.line, + column: block.fence.rawText.length, + }, + }, + message, + }; + + if (!fixAlreadyAttached && applyReplacementFix) { + reportData.fix = applyReplacementFix; + fixAlreadyAttached = true; + } else if (applyReplacementFix) { + reportData.suggest = [ + { + desc: 'Remove stale expectedErrors metadata', + fix: applyReplacementFix, + }, + ]; + } + + context.report(reportData); + } + } + }, + }; + }, +}; diff --git a/eslint-local-rules/rules/markdown.js b/eslint-local-rules/rules/markdown.js new file mode 100644 index 0000000000..d888d1311a --- /dev/null +++ b/eslint-local-rules/rules/markdown.js @@ -0,0 +1,124 @@ +/** + * 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. + */ + +const remark = require('remark'); +const {parseFenceMetadata} = require('./metadata'); + +/** + * @typedef {Object} MarkdownCodeBlock + * @property {string} code + * @property {number} codeStartLine + * @property {{start: {line: number, column: number}, end: {line: number, column: number}}} position + * @property {{lineIndex: number, rawText: string, metaText: string, range: [number, number]}} fence + * @property {string} filePath + * @property {string} lang + * @property {import('./metadata').FenceMetadata} metadata + */ + +const SUPPORTED_LANGUAGES = new Set([ + 'js', + 'jsx', + 'javascript', + 'ts', + 'tsx', + 'typescript', +]); + +function computeLineOffsets(lines) { + const offsets = []; + let currentOffset = 0; + + for (const line of lines) { + offsets.push(currentOffset); + currentOffset += line.length + 1; + } + + return offsets; +} + +function parseMarkdownFile(content, filePath) { + const tree = remark().parse(content); + const lines = content.split('\n'); + const lineOffsets = computeLineOffsets(lines); + const blocks = []; + + function traverse(node) { + if (!node || typeof node !== 'object') { + return; + } + + if (node.type === 'code') { + const rawLang = node.lang || ''; + const normalizedLang = rawLang.toLowerCase(); + if (!normalizedLang || !SUPPORTED_LANGUAGES.has(normalizedLang)) { + return; + } + + const fenceLineIndex = (node.position?.start?.line ?? 1) - 1; + const fenceStartOffset = node.position?.start?.offset ?? 0; + const fenceLine = lines[fenceLineIndex] ?? ''; + const fenceEndOffset = fenceStartOffset + fenceLine.length; + + let metaText = ''; + if (fenceLine) { + const prefixMatch = fenceLine.match(/^`{3,}\s*/); + const prefixLength = prefixMatch ? prefixMatch[0].length : 3; + metaText = fenceLine.slice(prefixLength + rawLang.length); + } else if (node.meta) { + metaText = ` ${node.meta}`; + } + + const metadata = parseFenceMetadata(metaText); + + blocks.push({ + lang: rawLang || normalizedLang, + metadata, + filePath, + code: node.value || '', + codeStartLine: (node.position?.start?.line ?? 1) + 1, + position: { + start: { + line: fenceLineIndex + 1, + column: (node.position?.start?.column ?? 1) - 1, + }, + end: { + line: fenceLineIndex + 1, + column: (node.position?.start?.column ?? 1) - 1 + fenceLine.length, + }, + }, + fence: { + lineIndex: fenceLineIndex, + rawText: fenceLine, + metaText, + range: [fenceStartOffset, fenceEndOffset], + }, + }); + return; + } + + if ('children' in node && Array.isArray(node.children)) { + for (const child of node.children) { + traverse(child); + } + } + } + + traverse(tree); + + return { + content, + blocks, + lines, + lineOffsets, + }; +} + +module.exports = { + SUPPORTED_LANGUAGES, + computeLineOffsets, + parseMarkdownFile, +}; diff --git a/eslint-local-rules/rules/metadata.js b/eslint-local-rules/rules/metadata.js new file mode 100644 index 0000000000..fb58a37c29 --- /dev/null +++ b/eslint-local-rules/rules/metadata.js @@ -0,0 +1,377 @@ +/** + * 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. + */ + +/** + * @typedef {{type: 'text', raw: string}} TextToken + * @typedef {{ + * type: 'expectedErrors', + * entries: Record<string, Array<number>>, + * raw?: string, + * }} ExpectedErrorsToken + * @typedef {TextToken | ExpectedErrorsToken} MetadataToken + * + * @typedef {{ + * leading: string, + * trailing: string, + * tokens: Array<MetadataToken>, + * parseError: boolean, + * hadDuplicateExpectedErrors: boolean, + * }} FenceMetadata + */ + +const EXPECTED_ERRORS_BLOCK_REGEX = /\{\s*expectedErrors\s*:/; +const REACT_COMPILER_KEY = 'react-compiler'; + +function getSortedUniqueNumbers(values) { + return Array.from(new Set(values)) + .filter((value) => typeof value === 'number' && !Number.isNaN(value)) + .sort((a, b) => a - b); +} + +function tokenizeMeta(body) { + if (!body) { + return []; + } + + const tokens = []; + let current = ''; + let depth = 0; + + for (let i = 0; i < body.length; i++) { + const char = body[i]; + if (char === '{') { + depth++; + } else if (char === '}') { + depth = Math.max(depth - 1, 0); + } + + if (char === ' ' && depth === 0) { + if (current) { + tokens.push(current); + current = ''; + } + continue; + } + + current += char; + } + + if (current) { + tokens.push(current); + } + + return tokens; +} + +function normalizeEntryValues(values) { + if (!Array.isArray(values)) { + return []; + } + return getSortedUniqueNumbers(values); +} + +function parseExpectedErrorsEntries(rawEntries) { + const normalized = rawEntries + .replace(/([{,]\s*)([a-zA-Z_$][\w$]*)\s*:/g, '$1"$2":') + .replace(/'([^']*)'/g, '"$1"'); + + const parsed = JSON.parse(normalized); + const entries = {}; + + if (parsed && typeof parsed === 'object') { + for (const [key, value] of Object.entries(parsed)) { + entries[key] = normalizeEntryValues(Array.isArray(value) ? value.flat() : value); + } + } + + return entries; +} + +function parseExpectedErrorsToken(tokenText) { + const match = tokenText.match(/^\{\s*expectedErrors\s*:\s*(\{[\s\S]*\})\s*\}$/); + if (!match) { + return null; + } + + const entriesSource = match[1]; + let parseError = false; + let entries; + + try { + entries = parseExpectedErrorsEntries(entriesSource); + } catch (error) { + parseError = true; + entries = {}; + } + + return { + token: { + type: 'expectedErrors', + entries, + raw: tokenText, + }, + parseError, + }; +} + +function parseFenceMetadata(metaText) { + if (!metaText) { + return { + leading: '', + trailing: '', + tokens: [], + parseError: false, + hadDuplicateExpectedErrors: false, + }; + } + + const leading = metaText.match(/^\s*/)?.[0] ?? ''; + const trailing = metaText.match(/\s*$/)?.[0] ?? ''; + const bodyStart = leading.length; + const bodyEnd = metaText.length - trailing.length; + const body = metaText.slice(bodyStart, bodyEnd).trim(); + + if (!body) { + return { + leading, + trailing, + tokens: [], + parseError: false, + hadDuplicateExpectedErrors: false, + }; + } + + const tokens = []; + let parseError = false; + let sawExpectedErrors = false; + let hadDuplicateExpectedErrors = false; + + for (const rawToken of tokenizeMeta(body)) { + const normalizedToken = rawToken.trim(); + if (!normalizedToken) { + continue; + } + + if (EXPECTED_ERRORS_BLOCK_REGEX.test(normalizedToken)) { + const parsed = parseExpectedErrorsToken(normalizedToken); + if (parsed) { + if (sawExpectedErrors) { + hadDuplicateExpectedErrors = true; + // Drop duplicates. We'll rebuild the canonical block on write. + continue; + } + tokens.push(parsed.token); + parseError = parseError || parsed.parseError; + sawExpectedErrors = true; + continue; + } + } + + tokens.push({type: 'text', raw: normalizedToken}); + } + + return { + leading, + trailing, + tokens, + parseError, + hadDuplicateExpectedErrors, + }; +} + +function cloneMetadata(metadata) { + return { + leading: metadata.leading, + trailing: metadata.trailing, + parseError: metadata.parseError, + hadDuplicateExpectedErrors: metadata.hadDuplicateExpectedErrors, + tokens: metadata.tokens.map((token) => { + if (token.type === 'expectedErrors') { + const clonedEntries = {}; + for (const [key, value] of Object.entries(token.entries)) { + clonedEntries[key] = [...value]; + } + return {type: 'expectedErrors', entries: clonedEntries}; + } + return {type: 'text', raw: token.raw}; + }), + }; +} + +function findExpectedErrorsToken(metadata) { + return metadata.tokens.find((token) => token.type === 'expectedErrors') || null; +} + +function getCompilerExpectedLines(metadata) { + const token = findExpectedErrorsToken(metadata); + if (!token) { + return []; + } + return getSortedUniqueNumbers(token.entries[REACT_COMPILER_KEY] || []); +} + +function hasCompilerEntry(metadata) { + const token = findExpectedErrorsToken(metadata); + return Boolean(token && token.entries[REACT_COMPILER_KEY]?.length); +} + +function metadataHasExpectedErrorsToken(metadata) { + return Boolean(findExpectedErrorsToken(metadata)); +} + +function stringifyExpectedErrorsToken(token) { + const entries = token.entries || {}; + const keys = Object.keys(entries).filter((key) => entries[key].length > 0); + if (keys.length === 0) { + return ''; + } + + keys.sort(); + + const segments = keys.map((key) => { + const values = entries[key]; + return `'${key}': [${values.join(', ')}]`; + }); + + return `{expectedErrors: {${segments.join(', ')}}}`; +} + +function stringifyFenceMetadata(metadata) { + if (!metadata.tokens.length) { + return ''; + } + + const parts = metadata.tokens + .map((token) => { + if (token.type === 'expectedErrors') { + return stringifyExpectedErrorsToken(token); + } + return token.raw; + }) + .filter(Boolean); + + if (!parts.length) { + return ''; + } + + const leading = metadata.leading || ' '; + const trailing = metadata.trailing ? metadata.trailing.trimEnd() : ''; + const body = parts.join(' '); + return `${leading}${body}${trailing}`; +} + +function buildFenceLine(lang, metadata) { + const meta = stringifyFenceMetadata(metadata); + return meta ? `\`\`\`${lang}${meta}` : `\`\`\`${lang}`; +} + +function metadataEquals(a, b) { + if (a.leading !== b.leading || a.trailing !== b.trailing) { + return false; + } + + if (a.tokens.length !== b.tokens.length) { + return false; + } + + for (let i = 0; i < a.tokens.length; i++) { + const left = a.tokens[i]; + const right = b.tokens[i]; + if (left.type !== right.type) { + return false; + } + if (left.type === 'text') { + if (left.raw !== right.raw) { + return false; + } + } else { + const leftKeys = Object.keys(left.entries).sort(); + const rightKeys = Object.keys(right.entries).sort(); + if (leftKeys.length !== rightKeys.length) { + return false; + } + for (let j = 0; j < leftKeys.length; j++) { + if (leftKeys[j] !== rightKeys[j]) { + return false; + } + const lValues = getSortedUniqueNumbers(left.entries[leftKeys[j]]); + const rValues = getSortedUniqueNumbers(right.entries[rightKeys[j]]); + if (lValues.length !== rValues.length) { + return false; + } + for (let k = 0; k < lValues.length; k++) { + if (lValues[k] !== rValues[k]) { + return false; + } + } + } + } + } + + return true; +} + +function normalizeMetadata(metadata) { + const normalized = cloneMetadata(metadata); + normalized.hadDuplicateExpectedErrors = false; + normalized.parseError = false; + if (!normalized.tokens.length) { + normalized.leading = ''; + normalized.trailing = ''; + } + return normalized; +} + +function setCompilerExpectedLines(metadata, lines) { + const normalizedLines = getSortedUniqueNumbers(lines); + if (normalizedLines.length === 0) { + return removeCompilerExpectedLines(metadata); + } + + const next = cloneMetadata(metadata); + let token = findExpectedErrorsToken(next); + if (!token) { + token = {type: 'expectedErrors', entries: {}}; + next.tokens = [token, ...next.tokens]; + } + + token.entries[REACT_COMPILER_KEY] = normalizedLines; + return normalizeMetadata(next); +} + +function removeCompilerExpectedLines(metadata) { + const next = cloneMetadata(metadata); + const token = findExpectedErrorsToken(next); + if (!token) { + return normalizeMetadata(next); + } + + delete token.entries[REACT_COMPILER_KEY]; + + const hasEntries = Object.values(token.entries).some( + (value) => Array.isArray(value) && value.length > 0 + ); + + if (!hasEntries) { + next.tokens = next.tokens.filter((item) => item !== token); + } + + return normalizeMetadata(next); +} + +module.exports = { + buildFenceLine, + getCompilerExpectedLines, + getSortedUniqueNumbers, + hasCompilerEntry, + metadataEquals, + metadataHasExpectedErrorsToken, + parseFenceMetadata, + removeCompilerExpectedLines, + setCompilerExpectedLines, + stringifyFenceMetadata, +}; diff --git a/eslint-local-rules/rules/react-compiler.js b/eslint-local-rules/rules/react-compiler.js new file mode 100644 index 0000000000..26d3878ee8 --- /dev/null +++ b/eslint-local-rules/rules/react-compiler.js @@ -0,0 +1,122 @@ +/** + * 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. + */ + +const {transformFromAstSync} = require('@babel/core'); +const {parse: babelParse} = require('@babel/parser'); +const BabelPluginReactCompiler = require('babel-plugin-react-compiler').default; +const { + parsePluginOptions, + validateEnvironmentConfig, +} = require('babel-plugin-react-compiler'); + +const COMPILER_OPTIONS = { + noEmit: true, + panicThreshold: 'none', + environment: validateEnvironmentConfig({ + validateRefAccessDuringRender: true, + validateNoSetStateInRender: true, + validateNoSetStateInEffects: true, + validateNoJSXInTryStatements: true, + validateNoImpureFunctionsInRender: true, + validateStaticComponents: true, + validateNoFreezingKnownMutableFunctions: true, + validateNoVoidUseMemo: true, + validateNoCapitalizedCalls: [], + validateHooksUsage: true, + validateNoDerivedComputationsInEffects: true, + }), +}; + +function hasRelevantCode(code) { + const functionPattern = /^(export\s+)?(default\s+)?function\s+\w+/m; + const arrowPattern = + /^(export\s+)?(const|let|var)\s+\w+\s*=\s*(\([^)]*\)|\w+)\s*=>/m; + const hasImports = /^import\s+/m.test(code); + + return functionPattern.test(code) || arrowPattern.test(code) || hasImports; +} + +function runReactCompiler(code, filename) { + const result = { + sourceCode: code, + events: [], + }; + + if (!hasRelevantCode(code)) { + return {...result, diagnostics: []}; + } + + const options = parsePluginOptions({ + ...COMPILER_OPTIONS, + }); + + options.logger = { + logEvent: (_, event) => { + if (event.kind === 'CompileError') { + const category = event.detail?.category; + if (category === 'Todo' || category === 'Invariant') { + return; + } + result.events.push(event); + } + }, + }; + + try { + const ast = babelParse(code, { + sourceFilename: filename, + sourceType: 'module', + plugins: ['jsx', 'typescript'], + }); + + transformFromAstSync(ast, code, { + filename, + highlightCode: false, + retainLines: true, + plugins: [[BabelPluginReactCompiler, options]], + sourceType: 'module', + configFile: false, + babelrc: false, + }); + } catch (error) { + return {...result, diagnostics: []}; + } + + const diagnostics = []; + + for (const event of result.events) { + if (event.kind !== 'CompileError') { + continue; + } + + const detail = event.detail; + if (!detail) { + continue; + } + + const loc = typeof detail.primaryLocation === 'function' + ? detail.primaryLocation() + : null; + + if (loc == null || typeof loc === 'symbol') { + continue; + } + + const message = typeof detail.printErrorMessage === 'function' + ? detail.printErrorMessage(result.sourceCode, {eslint: true}) + : detail.description || 'Unknown React Compiler error'; + + diagnostics.push({detail, loc, message}); + } + + return {...result, diagnostics}; +} + +module.exports = { + hasRelevantCode, + runReactCompiler, +}; diff --git a/eslint-local-rules/yarn.lock b/eslint-local-rules/yarn.lock new file mode 100644 index 0000000000..5a7cf126da --- /dev/null +++ b/eslint-local-rules/yarn.lock @@ -0,0 +1,1421 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@babel/code-frame@^7.16.0": + version "7.27.1" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.27.1.tgz#200f715e66d52a23b221a9435534a91cc13ad5be" + integrity sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg== + dependencies: + "@babel/helper-validator-identifier" "^7.27.1" + js-tokens "^4.0.0" + picocolors "^1.1.1" + +"@babel/helper-validator-identifier@^7.27.1": + version "7.27.1" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz#a7054dcc145a967dd4dc8fee845a57c1316c9df8" + integrity sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow== + +"@isaacs/cliui@^8.0.2": + version "8.0.2" + resolved "https://registry.yarnpkg.com/@isaacs/cliui/-/cliui-8.0.2.tgz#b37667b7bc181c168782259bab42474fbf52b550" + integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== + dependencies: + string-width "^5.1.2" + string-width-cjs "npm:string-width@^4.2.0" + strip-ansi "^7.0.1" + strip-ansi-cjs "npm:strip-ansi@^6.0.1" + wrap-ansi "^8.1.0" + wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" + +"@npmcli/config@^6.0.0": + version "6.4.1" + resolved "https://registry.yarnpkg.com/@npmcli/config/-/config-6.4.1.tgz#006409c739635db008e78bf58c92421cc147911d" + integrity sha512-uSz+elSGzjCMANWa5IlbGczLYPkNI/LeR+cHrgaTqTrTSh9RHhOFA4daD2eRUz6lMtOW+Fnsb+qv7V2Zz8ML0g== + dependencies: + "@npmcli/map-workspaces" "^3.0.2" + ci-info "^4.0.0" + ini "^4.1.0" + nopt "^7.0.0" + proc-log "^3.0.0" + read-package-json-fast "^3.0.2" + semver "^7.3.5" + walk-up-path "^3.0.1" + +"@npmcli/map-workspaces@^3.0.2": + version "3.0.6" + resolved "https://registry.yarnpkg.com/@npmcli/map-workspaces/-/map-workspaces-3.0.6.tgz#27dc06c20c35ef01e45a08909cab9cb3da08cea6" + integrity sha512-tkYs0OYnzQm6iIRdfy+LcLBjcKuQCeE5YLb8KnrIlutJfheNaPvPpgoFEyEFgbjzl5PLZ3IA/BWAwRU0eHuQDA== + dependencies: + "@npmcli/name-from-folder" "^2.0.0" + glob "^10.2.2" + minimatch "^9.0.0" + read-package-json-fast "^3.0.0" + +"@npmcli/name-from-folder@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/name-from-folder/-/name-from-folder-2.0.0.tgz#c44d3a7c6d5c184bb6036f4d5995eee298945815" + integrity sha512-pwK+BfEBZJbKdNYpHHRTNBwBoqrN/iIMO0AiGvYsp3Hoaq0WbgGSWQR6SCldZovoDpY3yje5lkFUe6gsDgJ2vg== + +"@pkgjs/parseargs@^0.11.0": + version "0.11.0" + resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" + integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== + +"@pkgr/core@^0.1.0": + version "0.1.2" + resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.1.2.tgz#1cf95080bb7072fafaa3cb13b442fab4695c3893" + integrity sha512-fdDH1LSGfZdTH2sxdpVMw31BanV28K/Gry0cVFxaNP77neJSkd82mM8ErPNYs9e+0O7SdHBLTDzDgwUuy18RnQ== + +"@types/acorn@^4.0.0": + version "4.0.6" + resolved "https://registry.yarnpkg.com/@types/acorn/-/acorn-4.0.6.tgz#d61ca5480300ac41a7d973dd5b84d0a591154a22" + integrity sha512-veQTnWP+1D/xbxVrPC3zHnCZRjSrKfhbMUlEA43iMZLu7EsnTtkJklIuwrCPbOi8YkvDQAiW05VQQFvvz9oieQ== + dependencies: + "@types/estree" "*" + +"@types/concat-stream@^2.0.0": + version "2.0.3" + resolved "https://registry.yarnpkg.com/@types/concat-stream/-/concat-stream-2.0.3.tgz#1f5c2ad26525716c181191f7ed53408f78eb758e" + integrity sha512-3qe4oQAPNwVNwK4C9c8u+VJqv9kez+2MR4qJpoPFfXtgxxif1QbFusvXzK0/Wra2VX07smostI2VMmJNSpZjuQ== + dependencies: + "@types/node" "*" + +"@types/debug@^4.0.0": + version "4.1.12" + resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.12.tgz#a155f21690871953410df4b6b6f53187f0500917" + integrity sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ== + dependencies: + "@types/ms" "*" + +"@types/estree-jsx@^1.0.0": + version "1.0.5" + resolved "https://registry.yarnpkg.com/@types/estree-jsx/-/estree-jsx-1.0.5.tgz#858a88ea20f34fe65111f005a689fa1ebf70dc18" + integrity sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg== + dependencies: + "@types/estree" "*" + +"@types/estree@*", "@types/estree@^1.0.0": + version "1.0.8" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.8.tgz#958b91c991b1867ced318bedea0e215ee050726e" + integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w== + +"@types/hast@^2.0.0": + version "2.3.10" + resolved "https://registry.yarnpkg.com/@types/hast/-/hast-2.3.10.tgz#5c9d9e0b304bbb8879b857225c5ebab2d81d7643" + integrity sha512-McWspRw8xx8J9HurkVBfYj0xKoE25tOFlHGdx4MJ5xORQrMGZNqJhVQWaIbm6Oyla5kYOXtDiopzKRJzEOkwJw== + dependencies: + "@types/unist" "^2" + +"@types/is-empty@^1.0.0": + version "1.2.3" + resolved "https://registry.yarnpkg.com/@types/is-empty/-/is-empty-1.2.3.tgz#a2d55ea8a5ec57bf61e411ba2a9e5132fe4f0899" + integrity sha512-4J1l5d79hoIvsrKh5VUKVRA1aIdsOb10Hu5j3J2VfP/msDnfTdGPmNp2E1Wg+vs97Bktzo+MZePFFXSGoykYJw== + +"@types/mdast@^3.0.0": + version "3.0.15" + resolved "https://registry.yarnpkg.com/@types/mdast/-/mdast-3.0.15.tgz#49c524a263f30ffa28b71ae282f813ed000ab9f5" + integrity sha512-LnwD+mUEfxWMa1QpDraczIn6k0Ee3SMicuYSSzS6ZYl2gKS09EClnJYGd8Du6rfc5r/GZEk5o1mRb8TaTj03sQ== + dependencies: + "@types/unist" "^2" + +"@types/ms@*": + version "2.1.0" + resolved "https://registry.yarnpkg.com/@types/ms/-/ms-2.1.0.tgz#052aa67a48eccc4309d7f0191b7e41434b90bb78" + integrity sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA== + +"@types/node@*": + version "24.5.1" + resolved "https://registry.yarnpkg.com/@types/node/-/node-24.5.1.tgz#dab6917c47113eb4502d27d06e89a407ec0eff95" + integrity sha512-/SQdmUP2xa+1rdx7VwB9yPq8PaKej8TD5cQ+XfKDPWWC+VDJU4rvVVagXqKUzhKjtFoNA8rXDJAkCxQPAe00+Q== + dependencies: + undici-types "~7.12.0" + +"@types/node@^18.0.0": + version "18.19.126" + resolved "https://registry.yarnpkg.com/@types/node/-/node-18.19.126.tgz#b1a9e0bac6338098f465ab242cbd6a8884d79b80" + integrity sha512-8AXQlBfrGmtYJEJUPs63F/uZQqVeFiN9o6NUjbDJYfxNxFnArlZufANPw4h6dGhYGKxcyw+TapXFvEsguzIQow== + dependencies: + undici-types "~5.26.4" + +"@types/supports-color@^8.0.0": + version "8.1.3" + resolved "https://registry.yarnpkg.com/@types/supports-color/-/supports-color-8.1.3.tgz#b769cdce1d1bb1a3fa794e35b62c62acdf93c139" + integrity sha512-Hy6UMpxhE3j1tLpl27exp1XqHD7n8chAiNPzWfz16LPZoMMoSc4dzLl6w9qijkEb/r5O1ozdu1CWGA2L83ZeZg== + +"@types/unist@^2", "@types/unist@^2.0.0": + version "2.0.11" + resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.11.tgz#11af57b127e32487774841f7a4e54eab166d03c4" + integrity sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA== + +abbrev@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-2.0.0.tgz#cf59829b8b4f03f89dda2771cb7f3653828c89bf" + integrity sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ== + +acorn-jsx@^5.0.0, acorn-jsx@^5.3.2: + version "5.3.2" + resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" + integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== + +acorn@^8.0.0, acorn@^8.10.0, acorn@^8.9.0: + version "8.15.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.15.0.tgz#a360898bc415edaac46c8241f6383975b930b816" + integrity sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg== + +ansi-regex@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" + integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== + +ansi-regex@^6.0.1: + version "6.2.2" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.2.2.tgz#60216eea464d864597ce2832000738a0589650c1" + integrity sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg== + +ansi-styles@^4.0.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + +ansi-styles@^6.1.0: + version "6.2.3" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.3.tgz#c044d5dcc521a076413472597a1acb1f103c4041" + integrity sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg== + +bail@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/bail/-/bail-2.0.2.tgz#d26f5cd8fe5d6f832a31517b9f7c356040ba6d5d" + integrity sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw== + +balanced-match@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" + integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== + +brace-expansion@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.2.tgz#54fc53237a613d854c7bd37463aad17df87214e7" + integrity sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ== + dependencies: + balanced-match "^1.0.0" + +buffer-from@^1.0.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" + integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== + +ccount@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/ccount/-/ccount-2.0.1.tgz#17a3bf82302e0870d6da43a01311a8bc02a3ecf5" + integrity sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg== + +character-entities-html4@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/character-entities-html4/-/character-entities-html4-2.1.0.tgz#1f1adb940c971a4b22ba39ddca6b618dc6e56b2b" + integrity sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA== + +character-entities-legacy@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz#76bc83a90738901d7bc223a9e93759fdd560125b" + integrity sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ== + +character-entities@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/character-entities/-/character-entities-2.0.2.tgz#2d09c2e72cd9523076ccb21157dff66ad43fcc22" + integrity sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ== + +character-reference-invalid@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz#85c66b041e43b47210faf401278abf808ac45cb9" + integrity sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw== + +ci-info@^4.0.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-4.3.0.tgz#c39b1013f8fdbd28cd78e62318357d02da160cd7" + integrity sha512-l+2bNRMiQgcfILUi33labAZYIWlH1kWDp+ecNo5iisRKrbm0xcRyCww71/YU0Fkw0mAFpz9bJayXPjey6vkmaQ== + +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + +concat-stream@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-2.0.0.tgz#414cf5af790a48c60ab9be4527d56d5e41133cb1" + integrity sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A== + dependencies: + buffer-from "^1.0.0" + inherits "^2.0.3" + readable-stream "^3.0.2" + typedarray "^0.0.6" + +cross-spawn@^7.0.6: + version "7.0.6" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" + integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA== + dependencies: + path-key "^3.1.0" + shebang-command "^2.0.0" + which "^2.0.1" + +debug@^4.0.0: + version "4.4.3" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" + integrity sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA== + dependencies: + ms "^2.1.3" + +decode-named-character-reference@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz#25c32ae6dd5e21889549d40f676030e9514cc0ed" + integrity sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q== + dependencies: + character-entities "^2.0.0" + +dequal@^2.0.0: + version "2.0.3" + resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" + integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== + +diff@^5.0.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/diff/-/diff-5.2.0.tgz#26ded047cd1179b78b9537d5ef725503ce1ae531" + integrity sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A== + +eastasianwidth@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" + integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== + +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + +error-ex@^1.3.2: + version "1.3.4" + resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.4.tgz#b3a8d8bb6f92eecc1629e3e27d3c8607a8a32414" + integrity sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ== + dependencies: + is-arrayish "^0.2.1" + +eslint-mdx@^2: + version "2.3.4" + resolved "https://registry.yarnpkg.com/eslint-mdx/-/eslint-mdx-2.3.4.tgz#87a5d95d6fcb27bafd2b15092f16f5aa559e336b" + integrity sha512-u4NszEUyoGtR7Q0A4qs0OymsEQdCO6yqWlTzDa9vGWsK7aMotdnW0hqifHTkf6lEtA2vHk2xlkWHTCrhYLyRbw== + dependencies: + acorn "^8.10.0" + acorn-jsx "^5.3.2" + espree "^9.6.1" + estree-util-visit "^1.2.1" + remark-mdx "^2.3.0" + remark-parse "^10.0.2" + remark-stringify "^10.0.3" + synckit "^0.9.0" + tslib "^2.6.1" + unified "^10.1.2" + unified-engine "^10.1.0" + unist-util-visit "^4.1.2" + uvu "^0.5.6" + vfile "^5.3.7" + +eslint-visitor-keys@^3.4.1: + version "3.4.3" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" + integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== + +espree@^9.6.1: + version "9.6.1" + resolved "https://registry.yarnpkg.com/espree/-/espree-9.6.1.tgz#a2a17b8e434690a5432f2f8018ce71d331a48c6f" + integrity sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ== + dependencies: + acorn "^8.9.0" + acorn-jsx "^5.3.2" + eslint-visitor-keys "^3.4.1" + +estree-util-is-identifier-name@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/estree-util-is-identifier-name/-/estree-util-is-identifier-name-2.1.0.tgz#fb70a432dcb19045e77b05c8e732f1364b4b49b2" + integrity sha512-bEN9VHRyXAUOjkKVQVvArFym08BTWB0aJPppZZr0UNyAqWsLaVfAqP7hbaTJjzHifmB5ebnR8Wm7r7yGN/HonQ== + +estree-util-visit@^1.0.0, estree-util-visit@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/estree-util-visit/-/estree-util-visit-1.2.1.tgz#8bc2bc09f25b00827294703835aabee1cc9ec69d" + integrity sha512-xbgqcrkIVbIG+lI/gzbvd9SGTJL4zqJKBFttUl5pP27KhAjtMKbX/mQXJ7qgyXpMgVy/zvpm0xoQQaGL8OloOw== + dependencies: + "@types/estree-jsx" "^1.0.0" + "@types/unist" "^2.0.0" + +extend@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" + integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== + +fault@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/fault/-/fault-2.0.1.tgz#d47ca9f37ca26e4bd38374a7c500b5a384755b6c" + integrity sha512-WtySTkS4OKev5JtpHXnib4Gxiurzh5NCGvWrFaZ34m6JehfTUhKZvn9njTfw48t6JumVQOmrKqpmGcdwxnhqBQ== + dependencies: + format "^0.2.0" + +foreground-child@^3.1.0: + version "3.3.1" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.3.1.tgz#32e8e9ed1b68a3497befb9ac2b6adf92a638576f" + integrity sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw== + dependencies: + cross-spawn "^7.0.6" + signal-exit "^4.0.1" + +format@^0.2.0: + version "0.2.2" + resolved "https://registry.yarnpkg.com/format/-/format-0.2.2.tgz#d6170107e9efdc4ed30c9dc39016df942b5cb58b" + integrity sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww== + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw== + +glob@^10.2.2: + version "10.4.5" + resolved "https://registry.yarnpkg.com/glob/-/glob-10.4.5.tgz#f4d9f0b90ffdbab09c9d77f5f29b4262517b0956" + integrity sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg== + dependencies: + foreground-child "^3.1.0" + jackspeak "^3.1.2" + minimatch "^9.0.4" + minipass "^7.1.2" + package-json-from-dist "^1.0.0" + path-scurry "^1.11.1" + +glob@^8.0.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/glob/-/glob-8.1.0.tgz#d388f656593ef708ee3e34640fdfb99a9fd1c33e" + integrity sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^5.0.1" + once "^1.3.0" + +ignore@^5.0.0: + version "5.3.2" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.2.tgz#3cd40e729f3643fd87cb04e50bf0eb722bc596f5" + integrity sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g== + +import-meta-resolve@^2.0.0: + version "2.2.2" + resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-2.2.2.tgz#75237301e72d1f0fbd74dbc6cca9324b164c2cc9" + integrity sha512-f8KcQ1D80V7RnqVm+/lirO9zkOxjGxhaTC1IPrBGd3MEfNgmNG67tSUO9gTi2F3Blr2Az6g1vocaxzkVnWl9MA== + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + integrity sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA== + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +ini@^4.1.0: + version "4.1.3" + resolved "https://registry.yarnpkg.com/ini/-/ini-4.1.3.tgz#4c359675a6071a46985eb39b14e4a2c0ec98a795" + integrity sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg== + +is-alphabetical@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-2.0.1.tgz#01072053ea7c1036df3c7d19a6daaec7f19e789b" + integrity sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ== + +is-alphanumerical@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz#7c03fbe96e3e931113e57f964b0a368cc2dfd875" + integrity sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw== + dependencies: + is-alphabetical "^2.0.0" + is-decimal "^2.0.0" + +is-arrayish@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== + +is-buffer@^2.0.0: + version "2.0.5" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191" + integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== + +is-decimal@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-2.0.1.tgz#9469d2dc190d0214fd87d78b78caecc0cc14eef7" + integrity sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A== + +is-empty@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/is-empty/-/is-empty-1.2.0.tgz#de9bb5b278738a05a0b09a57e1fb4d4a341a9f6b" + integrity sha512-F2FnH/otLNJv0J6wc73A5Xo7oHLNnqplYqZhUu01tD54DIPvxIRSTSLkrUB/M0nHO4vo1O9PDfN4KoTxCzLh/w== + +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + +is-hexadecimal@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz#86b5bf668fca307498d319dfc03289d781a90027" + integrity sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg== + +is-plain-obj@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-4.1.0.tgz#d65025edec3657ce032fd7db63c97883eaed71f0" + integrity sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg== + +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== + +jackspeak@^3.1.2: + version "3.4.3" + resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-3.4.3.tgz#8833a9d89ab4acde6188942bd1c53b6390ed5a8a" + integrity sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw== + dependencies: + "@isaacs/cliui" "^8.0.2" + optionalDependencies: + "@pkgjs/parseargs" "^0.11.0" + +js-tokens@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" + integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== + +json-parse-even-better-errors@^2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" + integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== + +json-parse-even-better-errors@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-3.0.2.tgz#b43d35e89c0f3be6b5fbbe9dc6c82467b30c28da" + integrity sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ== + +kleur@^4.0.3: + version "4.1.5" + resolved "https://registry.yarnpkg.com/kleur/-/kleur-4.1.5.tgz#95106101795f7050c6c650f350c683febddb1780" + integrity sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ== + +lines-and-columns@^2.0.2: + version "2.0.4" + resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-2.0.4.tgz#d00318855905d2660d8c0822e3f5a4715855fc42" + integrity sha512-wM1+Z03eypVAVUCE7QdSqpVIvelbOakn1M0bPDoA4SGWPx3sNDVUiMo3L6To6WWGClB7VyXnhQ4Sn7gxiJbE6A== + +load-plugin@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/load-plugin/-/load-plugin-5.1.0.tgz#15600f5191c742b16e058cfc908c227c13db0104" + integrity sha512-Lg1CZa1CFj2CbNaxijTL6PCbzd4qGTlZov+iH2p5Xwy/ApcZJh+i6jMN2cYePouTfjJfrNu3nXFdEw8LvbjPFQ== + dependencies: + "@npmcli/config" "^6.0.0" + import-meta-resolve "^2.0.0" + +longest-streak@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/longest-streak/-/longest-streak-3.1.0.tgz#62fa67cd958742a1574af9f39866364102d90cd4" + integrity sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g== + +lru-cache@^10.2.0: + version "10.4.3" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.4.3.tgz#410fc8a17b70e598013df257c2446b7f3383f119" + integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ== + +mdast-util-from-markdown@^1.0.0, mdast-util-from-markdown@^1.1.0: + version "1.3.1" + resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.1.tgz#9421a5a247f10d31d2faed2a30df5ec89ceafcf0" + integrity sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww== + dependencies: + "@types/mdast" "^3.0.0" + "@types/unist" "^2.0.0" + decode-named-character-reference "^1.0.0" + mdast-util-to-string "^3.1.0" + micromark "^3.0.0" + micromark-util-decode-numeric-character-reference "^1.0.0" + micromark-util-decode-string "^1.0.0" + micromark-util-normalize-identifier "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + unist-util-stringify-position "^3.0.0" + uvu "^0.5.0" + +mdast-util-mdx-expression@^1.0.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/mdast-util-mdx-expression/-/mdast-util-mdx-expression-1.3.2.tgz#d027789e67524d541d6de543f36d51ae2586f220" + integrity sha512-xIPmR5ReJDu/DHH1OoIT1HkuybIfRGYRywC+gJtI7qHjCJp/M9jrmBEJW22O8lskDWm562BX2W8TiAwRTb0rKA== + dependencies: + "@types/estree-jsx" "^1.0.0" + "@types/hast" "^2.0.0" + "@types/mdast" "^3.0.0" + mdast-util-from-markdown "^1.0.0" + mdast-util-to-markdown "^1.0.0" + +mdast-util-mdx-jsx@^2.0.0: + version "2.1.4" + resolved "https://registry.yarnpkg.com/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-2.1.4.tgz#7c1f07f10751a78963cfabee38017cbc8b7786d1" + integrity sha512-DtMn9CmVhVzZx3f+optVDF8yFgQVt7FghCRNdlIaS3X5Bnym3hZwPbg/XW86vdpKjlc1PVj26SpnLGeJBXD3JA== + dependencies: + "@types/estree-jsx" "^1.0.0" + "@types/hast" "^2.0.0" + "@types/mdast" "^3.0.0" + "@types/unist" "^2.0.0" + ccount "^2.0.0" + mdast-util-from-markdown "^1.1.0" + mdast-util-to-markdown "^1.3.0" + parse-entities "^4.0.0" + stringify-entities "^4.0.0" + unist-util-remove-position "^4.0.0" + unist-util-stringify-position "^3.0.0" + vfile-message "^3.0.0" + +mdast-util-mdx@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/mdast-util-mdx/-/mdast-util-mdx-2.0.1.tgz#49b6e70819b99bb615d7223c088d295e53bb810f" + integrity sha512-38w5y+r8nyKlGvNjSEqWrhG0w5PmnRA+wnBvm+ulYCct7nsGYhFVb0lljS9bQav4psDAS1eGkP2LMVcZBi/aqw== + dependencies: + mdast-util-from-markdown "^1.0.0" + mdast-util-mdx-expression "^1.0.0" + mdast-util-mdx-jsx "^2.0.0" + mdast-util-mdxjs-esm "^1.0.0" + mdast-util-to-markdown "^1.0.0" + +mdast-util-mdxjs-esm@^1.0.0: + version "1.3.1" + resolved "https://registry.yarnpkg.com/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-1.3.1.tgz#645d02cd607a227b49721d146fd81796b2e2d15b" + integrity sha512-SXqglS0HrEvSdUEfoXFtcg7DRl7S2cwOXc7jkuusG472Mmjag34DUDeOJUZtl+BVnyeO1frIgVpHlNRWc2gk/w== + dependencies: + "@types/estree-jsx" "^1.0.0" + "@types/hast" "^2.0.0" + "@types/mdast" "^3.0.0" + mdast-util-from-markdown "^1.0.0" + mdast-util-to-markdown "^1.0.0" + +mdast-util-phrasing@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/mdast-util-phrasing/-/mdast-util-phrasing-3.0.1.tgz#c7c21d0d435d7fb90956038f02e8702781f95463" + integrity sha512-WmI1gTXUBJo4/ZmSk79Wcb2HcjPJBzM1nlI/OUWA8yk2X9ik3ffNbBGsU+09BFmXaL1IBb9fiuvq6/KMiNycSg== + dependencies: + "@types/mdast" "^3.0.0" + unist-util-is "^5.0.0" + +mdast-util-to-markdown@^1.0.0, mdast-util-to-markdown@^1.3.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/mdast-util-to-markdown/-/mdast-util-to-markdown-1.5.0.tgz#c13343cb3fc98621911d33b5cd42e7d0731171c6" + integrity sha512-bbv7TPv/WC49thZPg3jXuqzuvI45IL2EVAr/KxF0BSdHsU0ceFHOmwQn6evxAh1GaoK/6GQ1wp4R4oW2+LFL/A== + dependencies: + "@types/mdast" "^3.0.0" + "@types/unist" "^2.0.0" + longest-streak "^3.0.0" + mdast-util-phrasing "^3.0.0" + mdast-util-to-string "^3.0.0" + micromark-util-decode-string "^1.0.0" + unist-util-visit "^4.0.0" + zwitch "^2.0.0" + +mdast-util-to-string@^3.0.0, mdast-util-to-string@^3.1.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-3.2.0.tgz#66f7bb6324756741c5f47a53557f0cbf16b6f789" + integrity sha512-V4Zn/ncyN1QNSqSBxTrMOLpjr+IKdHl2v3KVLoWmDPscP4r9GcCi71gjgvUV1SFSKh92AjAG4peFuBl2/YgCJg== + dependencies: + "@types/mdast" "^3.0.0" + +micromark-core-commonmark@^1.0.0, micromark-core-commonmark@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-core-commonmark/-/micromark-core-commonmark-1.1.0.tgz#1386628df59946b2d39fb2edfd10f3e8e0a75bb8" + integrity sha512-BgHO1aRbolh2hcrzL2d1La37V0Aoz73ymF8rAcKnohLy93titmv62E0gP8Hrx9PKcKrqCZ1BbLGbP3bEhoXYlw== + dependencies: + decode-named-character-reference "^1.0.0" + micromark-factory-destination "^1.0.0" + micromark-factory-label "^1.0.0" + micromark-factory-space "^1.0.0" + micromark-factory-title "^1.0.0" + micromark-factory-whitespace "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-chunked "^1.0.0" + micromark-util-classify-character "^1.0.0" + micromark-util-html-tag-name "^1.0.0" + micromark-util-normalize-identifier "^1.0.0" + micromark-util-resolve-all "^1.0.0" + micromark-util-subtokenize "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.1" + uvu "^0.5.0" + +micromark-extension-mdx-expression@^1.0.0: + version "1.0.8" + resolved "https://registry.yarnpkg.com/micromark-extension-mdx-expression/-/micromark-extension-mdx-expression-1.0.8.tgz#5bc1f5fd90388e8293b3ef4f7c6f06c24aff6314" + integrity sha512-zZpeQtc5wfWKdzDsHRBY003H2Smg+PUi2REhqgIhdzAa5xonhP03FcXxqFSerFiNUr5AWmHpaNPQTBVOS4lrXw== + dependencies: + "@types/estree" "^1.0.0" + micromark-factory-mdx-expression "^1.0.0" + micromark-factory-space "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-events-to-acorn "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + uvu "^0.5.0" + +micromark-extension-mdx-jsx@^1.0.0: + version "1.0.5" + resolved "https://registry.yarnpkg.com/micromark-extension-mdx-jsx/-/micromark-extension-mdx-jsx-1.0.5.tgz#e72d24b7754a30d20fb797ece11e2c4e2cae9e82" + integrity sha512-gPH+9ZdmDflbu19Xkb8+gheqEDqkSpdCEubQyxuz/Hn8DOXiXvrXeikOoBA71+e8Pfi0/UYmU3wW3H58kr7akA== + dependencies: + "@types/acorn" "^4.0.0" + "@types/estree" "^1.0.0" + estree-util-is-identifier-name "^2.0.0" + micromark-factory-mdx-expression "^1.0.0" + micromark-factory-space "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + uvu "^0.5.0" + vfile-message "^3.0.0" + +micromark-extension-mdx-md@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/micromark-extension-mdx-md/-/micromark-extension-mdx-md-1.0.1.tgz#595d4b2f692b134080dca92c12272ab5b74c6d1a" + integrity sha512-7MSuj2S7xjOQXAjjkbjBsHkMtb+mDGVW6uI2dBL9snOBCbZmoNgDAeZ0nSn9j3T42UE/g2xVNMn18PJxZvkBEA== + dependencies: + micromark-util-types "^1.0.0" + +micromark-extension-mdxjs-esm@^1.0.0: + version "1.0.5" + resolved "https://registry.yarnpkg.com/micromark-extension-mdxjs-esm/-/micromark-extension-mdxjs-esm-1.0.5.tgz#e4f8be9c14c324a80833d8d3a227419e2b25dec1" + integrity sha512-xNRBw4aoURcyz/S69B19WnZAkWJMxHMT5hE36GtDAyhoyn/8TuAeqjFJQlwk+MKQsUD7b3l7kFX+vlfVWgcX1w== + dependencies: + "@types/estree" "^1.0.0" + micromark-core-commonmark "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-events-to-acorn "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + unist-util-position-from-estree "^1.1.0" + uvu "^0.5.0" + vfile-message "^3.0.0" + +micromark-extension-mdxjs@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/micromark-extension-mdxjs/-/micromark-extension-mdxjs-1.0.1.tgz#f78d4671678d16395efeda85170c520ee795ded8" + integrity sha512-7YA7hF6i5eKOfFUzZ+0z6avRG52GpWR8DL+kN47y3f2KhxbBZMhmxe7auOeaTBrW2DenbbZTf1ea9tA2hDpC2Q== + dependencies: + acorn "^8.0.0" + acorn-jsx "^5.0.0" + micromark-extension-mdx-expression "^1.0.0" + micromark-extension-mdx-jsx "^1.0.0" + micromark-extension-mdx-md "^1.0.0" + micromark-extension-mdxjs-esm "^1.0.0" + micromark-util-combine-extensions "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-factory-destination@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-factory-destination/-/micromark-factory-destination-1.1.0.tgz#eb815957d83e6d44479b3df640f010edad667b9f" + integrity sha512-XaNDROBgx9SgSChd69pjiGKbV+nfHGDPVYFs5dOoDd7ZnMAE+Cuu91BCpsY8RT2NP9vo/B8pds2VQNCLiu0zhg== + dependencies: + micromark-util-character "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-factory-label@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-factory-label/-/micromark-factory-label-1.1.0.tgz#cc95d5478269085cfa2a7282b3de26eb2e2dec68" + integrity sha512-OLtyez4vZo/1NjxGhcpDSbHQ+m0IIGnT8BoPamh+7jVlzLJBH98zzuCoUeMxvM6WsNeh8wx8cKvqLiPHEACn0w== + dependencies: + micromark-util-character "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + uvu "^0.5.0" + +micromark-factory-mdx-expression@^1.0.0: + version "1.0.9" + resolved "https://registry.yarnpkg.com/micromark-factory-mdx-expression/-/micromark-factory-mdx-expression-1.0.9.tgz#57ba4571b69a867a1530f34741011c71c73a4976" + integrity sha512-jGIWzSmNfdnkJq05c7b0+Wv0Kfz3NJ3N4cBjnbO4zjXIlxJr+f8lk+5ZmwFvqdAbUy2q6B5rCY//g0QAAaXDWA== + dependencies: + "@types/estree" "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-events-to-acorn "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + unist-util-position-from-estree "^1.0.0" + uvu "^0.5.0" + vfile-message "^3.0.0" + +micromark-factory-space@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-factory-space/-/micromark-factory-space-1.1.0.tgz#c8f40b0640a0150751d3345ed885a080b0d15faf" + integrity sha512-cRzEj7c0OL4Mw2v6nwzttyOZe8XY/Z8G0rzmWQZTBi/jjwyw/U4uqKtUORXQrR5bAZZnbTI/feRV/R7hc4jQYQ== + dependencies: + micromark-util-character "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-factory-title@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-factory-title/-/micromark-factory-title-1.1.0.tgz#dd0fe951d7a0ac71bdc5ee13e5d1465ad7f50ea1" + integrity sha512-J7n9R3vMmgjDOCY8NPw55jiyaQnH5kBdV2/UXCtZIpnHH3P6nHUKaH7XXEYuWwx/xUJcawa8plLBEjMPU24HzQ== + dependencies: + micromark-factory-space "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-factory-whitespace@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-factory-whitespace/-/micromark-factory-whitespace-1.1.0.tgz#798fb7489f4c8abafa7ca77eed6b5745853c9705" + integrity sha512-v2WlmiymVSp5oMg+1Q0N1Lxmt6pMhIHD457whWM7/GUlEks1hI9xj5w3zbc4uuMKXGisksZk8DzP2UyGbGqNsQ== + dependencies: + micromark-factory-space "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-util-character@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/micromark-util-character/-/micromark-util-character-1.2.0.tgz#4fedaa3646db249bc58caeb000eb3549a8ca5dcc" + integrity sha512-lXraTwcX3yH/vMDaFWCQJP1uIszLVebzUa3ZHdrgxr7KEU/9mL4mVgCpGbyhvNLNlauROiNUq7WN5u7ndbY6xg== + dependencies: + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-util-chunked@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-chunked/-/micromark-util-chunked-1.1.0.tgz#37a24d33333c8c69a74ba12a14651fd9ea8a368b" + integrity sha512-Ye01HXpkZPNcV6FiyoW2fGZDUw4Yc7vT0E9Sad83+bEDiCJ1uXu0S3mr8WLpsz3HaG3x2q0HM6CTuPdcZcluFQ== + dependencies: + micromark-util-symbol "^1.0.0" + +micromark-util-classify-character@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-classify-character/-/micromark-util-classify-character-1.1.0.tgz#6a7f8c8838e8a120c8e3c4f2ae97a2bff9190e9d" + integrity sha512-SL0wLxtKSnklKSUplok1WQFoGhUdWYKggKUiqhX+Swala+BtptGCu5iPRc+xvzJ4PXE/hwM3FNXsfEVgoZsWbw== + dependencies: + micromark-util-character "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-util-combine-extensions@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.1.0.tgz#192e2b3d6567660a85f735e54d8ea6e3952dbe84" + integrity sha512-Q20sp4mfNf9yEqDL50WwuWZHUrCO4fEyeDCnMGmG5Pr0Cz15Uo7KBs6jq+dq0EgX4DPwwrh9m0X+zPV1ypFvUA== + dependencies: + micromark-util-chunked "^1.0.0" + micromark-util-types "^1.0.0" + +micromark-util-decode-numeric-character-reference@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.1.0.tgz#b1e6e17009b1f20bc652a521309c5f22c85eb1c6" + integrity sha512-m9V0ExGv0jB1OT21mrWcuf4QhP46pH1KkfWy9ZEezqHKAxkj4mPCy3nIH1rkbdMlChLHX531eOrymlwyZIf2iw== + dependencies: + micromark-util-symbol "^1.0.0" + +micromark-util-decode-string@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-decode-string/-/micromark-util-decode-string-1.1.0.tgz#dc12b078cba7a3ff690d0203f95b5d5537f2809c" + integrity sha512-YphLGCK8gM1tG1bd54azwyrQRjCFcmgj2S2GoJDNnh4vYtnL38JS8M4gpxzOPNyHdNEpheyWXCTnnTDY3N+NVQ== + dependencies: + decode-named-character-reference "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-decode-numeric-character-reference "^1.0.0" + micromark-util-symbol "^1.0.0" + +micromark-util-encode@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-encode/-/micromark-util-encode-1.1.0.tgz#92e4f565fd4ccb19e0dcae1afab9a173bbeb19a5" + integrity sha512-EuEzTWSTAj9PA5GOAs992GzNh2dGQO52UvAbtSOMvXTxv3Criqb6IOzJUBCmEqrrXSblJIJBbFFv6zPxpreiJw== + +micromark-util-events-to-acorn@^1.0.0: + version "1.2.3" + resolved "https://registry.yarnpkg.com/micromark-util-events-to-acorn/-/micromark-util-events-to-acorn-1.2.3.tgz#a4ab157f57a380e646670e49ddee97a72b58b557" + integrity sha512-ij4X7Wuc4fED6UoLWkmo0xJQhsktfNh1J0m8g4PbIMPlx+ek/4YdW5mvbye8z/aZvAPUoxgXHrwVlXAPKMRp1w== + dependencies: + "@types/acorn" "^4.0.0" + "@types/estree" "^1.0.0" + "@types/unist" "^2.0.0" + estree-util-visit "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + uvu "^0.5.0" + vfile-message "^3.0.0" + +micromark-util-html-tag-name@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.2.0.tgz#48fd7a25826f29d2f71479d3b4e83e94829b3588" + integrity sha512-VTQzcuQgFUD7yYztuQFKXT49KghjtETQ+Wv/zUjGSGBioZnkA4P1XXZPT1FHeJA6RwRXSF47yvJ1tsJdoxwO+Q== + +micromark-util-normalize-identifier@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.1.0.tgz#7a73f824eb9f10d442b4d7f120fecb9b38ebf8b7" + integrity sha512-N+w5vhqrBihhjdpM8+5Xsxy71QWqGn7HYNUvch71iV2PM7+E3uWGox1Qp90loa1ephtCxG2ftRV/Conitc6P2Q== + dependencies: + micromark-util-symbol "^1.0.0" + +micromark-util-resolve-all@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-resolve-all/-/micromark-util-resolve-all-1.1.0.tgz#4652a591ee8c8fa06714c9b54cd6c8e693671188" + integrity sha512-b/G6BTMSg+bX+xVCshPTPyAu2tmA0E4X98NSR7eIbeC6ycCqCeE7wjfDIgzEbkzdEVJXRtOG4FbEm/uGbCRouA== + dependencies: + micromark-util-types "^1.0.0" + +micromark-util-sanitize-uri@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.2.0.tgz#613f738e4400c6eedbc53590c67b197e30d7f90d" + integrity sha512-QO4GXv0XZfWey4pYFndLUKEAktKkG5kZTdUNaTAkzbuJxn2tNBOr+QtxR2XpWaMhbImT2dPzyLrPXLlPhph34A== + dependencies: + micromark-util-character "^1.0.0" + micromark-util-encode "^1.0.0" + micromark-util-symbol "^1.0.0" + +micromark-util-subtokenize@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-subtokenize/-/micromark-util-subtokenize-1.1.0.tgz#941c74f93a93eaf687b9054aeb94642b0e92edb1" + integrity sha512-kUQHyzRoxvZO2PuLzMt2P/dwVsTiivCK8icYTeR+3WgbuPqfHgPPy7nFKbeqRivBvn/3N3GBiNC+JRTMSxEC7A== + dependencies: + micromark-util-chunked "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.0" + uvu "^0.5.0" + +micromark-util-symbol@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-symbol/-/micromark-util-symbol-1.1.0.tgz#813cd17837bdb912d069a12ebe3a44b6f7063142" + integrity sha512-uEjpEYY6KMs1g7QfJ2eX1SQEV+ZT4rUD3UcF6l57acZvLNK7PBZL+ty82Z1qhK1/yXIY4bdx04FKMgR0g4IAag== + +micromark-util-types@^1.0.0, micromark-util-types@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/micromark-util-types/-/micromark-util-types-1.1.0.tgz#e6676a8cae0bb86a2171c498167971886cb7e283" + integrity sha512-ukRBgie8TIAcacscVHSiddHjO4k/q3pnedmzMQ4iwDcK0FtFCohKOlFbaOL/mPgfnPsL3C1ZyxJa4sbWrBl3jg== + +micromark@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/micromark/-/micromark-3.2.0.tgz#1af9fef3f995ea1ea4ac9c7e2f19c48fd5c006e9" + integrity sha512-uD66tJj54JLYq0De10AhWycZWGQNUvDI55xPgk2sQM5kn1JYlhbCMTtEeT27+vAhW2FBQxLlOmS3pmA7/2z4aA== + dependencies: + "@types/debug" "^4.0.0" + debug "^4.0.0" + decode-named-character-reference "^1.0.0" + micromark-core-commonmark "^1.0.1" + micromark-factory-space "^1.0.0" + micromark-util-character "^1.0.0" + micromark-util-chunked "^1.0.0" + micromark-util-combine-extensions "^1.0.0" + micromark-util-decode-numeric-character-reference "^1.0.0" + micromark-util-encode "^1.0.0" + micromark-util-normalize-identifier "^1.0.0" + micromark-util-resolve-all "^1.0.0" + micromark-util-sanitize-uri "^1.0.0" + micromark-util-subtokenize "^1.0.0" + micromark-util-symbol "^1.0.0" + micromark-util-types "^1.0.1" + uvu "^0.5.0" + +minimatch@^5.0.1: + version "5.1.6" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" + integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== + dependencies: + brace-expansion "^2.0.1" + +minimatch@^9.0.0, minimatch@^9.0.4: + version "9.0.5" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.5.tgz#d74f9dd6b57d83d8e98cfb82133b03978bc929e5" + integrity sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow== + dependencies: + brace-expansion "^2.0.1" + +"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.1.2: + version "7.1.2" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.2.tgz#93a9626ce5e5e66bd4db86849e7515e92340a707" + integrity sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw== + +mri@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b" + integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA== + +ms@^2.1.3: + version "2.1.3" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" + integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== + +nopt@^7.0.0: + version "7.2.1" + resolved "https://registry.yarnpkg.com/nopt/-/nopt-7.2.1.tgz#1cac0eab9b8e97c9093338446eddd40b2c8ca1e7" + integrity sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w== + dependencies: + abbrev "^2.0.0" + +npm-normalize-package-bin@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/npm-normalize-package-bin/-/npm-normalize-package-bin-3.0.1.tgz#25447e32a9a7de1f51362c61a559233b89947832" + integrity sha512-dMxCf+zZ+3zeQZXKxmyuCKlIDPGuv8EF940xbkC4kQVDTtqoh6rJFO+JTKSA6/Rwi0getWmtuy4Itup0AMcaDQ== + +once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== + dependencies: + wrappy "1" + +package-json-from-dist@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz#4f1471a010827a86f94cfd9b0727e36d267de505" + integrity sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw== + +parse-entities@^4.0.0: + version "4.0.2" + resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-4.0.2.tgz#61d46f5ed28e4ee62e9ddc43d6b010188443f159" + integrity sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw== + dependencies: + "@types/unist" "^2.0.0" + character-entities-legacy "^3.0.0" + character-reference-invalid "^2.0.0" + decode-named-character-reference "^1.0.0" + is-alphanumerical "^2.0.0" + is-decimal "^2.0.0" + is-hexadecimal "^2.0.0" + +parse-json@^6.0.0: + version "6.0.2" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-6.0.2.tgz#6bf79c201351cc12d5d66eba48d5a097c13dc200" + integrity sha512-SA5aMiaIjXkAiBrW/yPgLgQAQg42f7K3ACO+2l/zOvtQBwX58DMUsFJXelW2fx3yMBmWOVkR6j1MGsdSbCA4UA== + dependencies: + "@babel/code-frame" "^7.16.0" + error-ex "^1.3.2" + json-parse-even-better-errors "^2.3.1" + lines-and-columns "^2.0.2" + +path-key@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" + integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== + +path-scurry@^1.11.1: + version "1.11.1" + resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.11.1.tgz#7960a668888594a0720b12a911d1a742ab9f11d2" + integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA== + dependencies: + lru-cache "^10.2.0" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" + +picocolors@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" + integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== + +proc-log@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/proc-log/-/proc-log-3.0.0.tgz#fb05ef83ccd64fd7b20bbe9c8c1070fc08338dd8" + integrity sha512-++Vn7NS4Xf9NacaU9Xq3URUuqZETPsf8L4j5/ckhaRYsfPeRyzGw+iDjFhV/Jr3uNmTvvddEJFWh5R1gRgUH8A== + +read-package-json-fast@^3.0.0, read-package-json-fast@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/read-package-json-fast/-/read-package-json-fast-3.0.2.tgz#394908a9725dc7a5f14e70c8e7556dff1d2b1049" + integrity sha512-0J+Msgym3vrLOUB3hzQCuZHII0xkNGCtz/HJH9xZshwv9DbDwkw1KaE3gx/e2J5rpEY5rtOy6cyhKOPrkP7FZw== + dependencies: + json-parse-even-better-errors "^3.0.0" + npm-normalize-package-bin "^3.0.0" + +readable-stream@^3.0.2: + version "3.6.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +remark-mdx@^2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/remark-mdx/-/remark-mdx-2.3.0.tgz#efe678025a8c2726681bde8bf111af4a93943db4" + integrity sha512-g53hMkpM0I98MU266IzDFMrTD980gNF3BJnkyFcmN+dD873mQeD5rdMO3Y2X+x8umQfbSE0PcoEDl7ledSA+2g== + dependencies: + mdast-util-mdx "^2.0.0" + micromark-extension-mdxjs "^1.0.0" + +remark-parse@^10.0.2: + version "10.0.2" + resolved "https://registry.yarnpkg.com/remark-parse/-/remark-parse-10.0.2.tgz#ca241fde8751c2158933f031a4e3efbaeb8bc262" + integrity sha512-3ydxgHa/ZQzG8LvC7jTXccARYDcRld3VfcgIIFs7bI6vbRSxJJmzgLEIIoYKyrfhaY+ujuWaf/PJiMZXoiCXgw== + dependencies: + "@types/mdast" "^3.0.0" + mdast-util-from-markdown "^1.0.0" + unified "^10.0.0" + +remark-stringify@^10.0.3: + version "10.0.3" + resolved "https://registry.yarnpkg.com/remark-stringify/-/remark-stringify-10.0.3.tgz#83b43f2445c4ffbb35b606f967d121b2b6d69717" + integrity sha512-koyOzCMYoUHudypbj4XpnAKFbkddRMYZHwghnxd7ue5210WzGw6kOBwauJTRUMq16jsovXx8dYNvSSWP89kZ3A== + dependencies: + "@types/mdast" "^3.0.0" + mdast-util-to-markdown "^1.0.0" + unified "^10.0.0" + +sade@^1.7.3: + version "1.8.1" + resolved "https://registry.yarnpkg.com/sade/-/sade-1.8.1.tgz#0a78e81d658d394887be57d2a409bf703a3b2701" + integrity sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A== + dependencies: + mri "^1.1.0" + +safe-buffer@~5.2.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== + +semver@^7.3.5: + version "7.7.2" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.2.tgz#67d99fdcd35cec21e6f8b87a7fd515a33f982b58" + integrity sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA== + +shebang-command@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" + integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== + dependencies: + shebang-regex "^3.0.0" + +shebang-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" + integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== + +signal-exit@^4.0.1: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^4.1.0: + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^5.0.0, string-width@^5.0.1, string-width@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" + integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== + dependencies: + eastasianwidth "^0.2.0" + emoji-regex "^9.2.2" + strip-ansi "^7.0.1" + +string_decoder@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== + dependencies: + safe-buffer "~5.2.0" + +stringify-entities@^4.0.0: + version "4.0.4" + resolved "https://registry.yarnpkg.com/stringify-entities/-/stringify-entities-4.0.4.tgz#b3b79ef5f277cc4ac73caeb0236c5ba939b3a4f3" + integrity sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg== + dependencies: + character-entities-html4 "^2.0.0" + character-entities-legacy "^3.0.0" + +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^7.0.1: + version "7.1.2" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.2.tgz#132875abde678c7ea8d691533f2e7e22bb744dba" + integrity sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA== + dependencies: + ansi-regex "^6.0.1" + +supports-color@^9.0.0: + version "9.4.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.4.0.tgz#17bfcf686288f531db3dea3215510621ccb55954" + integrity sha512-VL+lNrEoIXww1coLPOmiEmK/0sGigko5COxI09KzHc2VJXJsQ37UaQ+8quuxjDeA7+KnLGTWRyOXSLLR2Wb4jw== + +synckit@^0.9.0: + version "0.9.3" + resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.9.3.tgz#1cfd60d9e61f931e07fb7f56f474b5eb31b826a7" + integrity sha512-JJoOEKTfL1urb1mDoEblhD9NhEbWmq9jHEMEnxoC4ujUaZ4itA8vKgwkFAyNClgxplLi9tsUKX+EduK0p/l7sg== + dependencies: + "@pkgr/core" "^0.1.0" + tslib "^2.6.2" + +to-vfile@^7.0.0: + version "7.2.4" + resolved "https://registry.yarnpkg.com/to-vfile/-/to-vfile-7.2.4.tgz#b97ecfcc15905ffe020bc975879053928b671378" + integrity sha512-2eQ+rJ2qGbyw3senPI0qjuM7aut8IYXK6AEoOWb+fJx/mQYzviTckm1wDjq91QYHAPBTYzmdJXxMFA6Mk14mdw== + dependencies: + is-buffer "^2.0.0" + vfile "^5.1.0" + +trough@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/trough/-/trough-2.2.0.tgz#94a60bd6bd375c152c1df911a4b11d5b0256f50f" + integrity sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw== + +tslib@^2.6.1, tslib@^2.6.2: + version "2.8.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f" + integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== + +typedarray@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + integrity sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA== + +undici-types@~5.26.4: + version "5.26.5" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" + integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== + +undici-types@~7.12.0: + version "7.12.0" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-7.12.0.tgz#15c5c7475c2a3ba30659529f5cdb4674b622fafb" + integrity sha512-goOacqME2GYyOZZfb5Lgtu+1IDmAlAEu5xnD3+xTzS10hT0vzpf0SPjkXwAw9Jm+4n/mQGDP3LO8CPbYROeBfQ== + +unified-engine@^10.1.0: + version "10.1.0" + resolved "https://registry.yarnpkg.com/unified-engine/-/unified-engine-10.1.0.tgz#6899f00d1f53ee9af94f7abd0ec21242aae3f56c" + integrity sha512-5+JDIs4hqKfHnJcVCxTid1yBoI/++FfF/1PFdSMpaftZZZY+qg2JFruRbf7PaIwa9KgLotXQV3gSjtY0IdcFGQ== + dependencies: + "@types/concat-stream" "^2.0.0" + "@types/debug" "^4.0.0" + "@types/is-empty" "^1.0.0" + "@types/node" "^18.0.0" + "@types/unist" "^2.0.0" + concat-stream "^2.0.0" + debug "^4.0.0" + fault "^2.0.0" + glob "^8.0.0" + ignore "^5.0.0" + is-buffer "^2.0.0" + is-empty "^1.0.0" + is-plain-obj "^4.0.0" + load-plugin "^5.0.0" + parse-json "^6.0.0" + to-vfile "^7.0.0" + trough "^2.0.0" + unist-util-inspect "^7.0.0" + vfile-message "^3.0.0" + vfile-reporter "^7.0.0" + vfile-statistics "^2.0.0" + yaml "^2.0.0" + +unified@^10.0.0, unified@^10.1.2: + version "10.1.2" + resolved "https://registry.yarnpkg.com/unified/-/unified-10.1.2.tgz#b1d64e55dafe1f0b98bb6c719881103ecf6c86df" + integrity sha512-pUSWAi/RAnVy1Pif2kAoeWNBa3JVrx0MId2LASj8G+7AiHWoKZNTomq6LG326T68U7/e263X6fTdcXIy7XnF7Q== + dependencies: + "@types/unist" "^2.0.0" + bail "^2.0.0" + extend "^3.0.0" + is-buffer "^2.0.0" + is-plain-obj "^4.0.0" + trough "^2.0.0" + vfile "^5.0.0" + +unist-util-inspect@^7.0.0: + version "7.0.2" + resolved "https://registry.yarnpkg.com/unist-util-inspect/-/unist-util-inspect-7.0.2.tgz#858e4f02ee4053f7c6ada8bc81662901a0ee1893" + integrity sha512-Op0XnmHUl6C2zo/yJCwhXQSm/SmW22eDZdWP2qdf4WpGrgO1ZxFodq+5zFyeRGasFjJotAnLgfuD1jkcKqiH1Q== + dependencies: + "@types/unist" "^2.0.0" + +unist-util-is@^5.0.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-5.2.1.tgz#b74960e145c18dcb6226bc57933597f5486deae9" + integrity sha512-u9njyyfEh43npf1M+yGKDGVPbY/JWEemg5nH05ncKPfi+kBbKBJoTdsogMu33uhytuLlv9y0O7GH7fEdwLdLQw== + dependencies: + "@types/unist" "^2.0.0" + +unist-util-position-from-estree@^1.0.0, unist-util-position-from-estree@^1.1.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/unist-util-position-from-estree/-/unist-util-position-from-estree-1.1.2.tgz#8ac2480027229de76512079e377afbcabcfcce22" + integrity sha512-poZa0eXpS+/XpoQwGwl79UUdea4ol2ZuCYguVaJS4qzIOMDzbqz8a3erUCOmubSZkaOuGamb3tX790iwOIROww== + dependencies: + "@types/unist" "^2.0.0" + +unist-util-remove-position@^4.0.0: + version "4.0.2" + resolved "https://registry.yarnpkg.com/unist-util-remove-position/-/unist-util-remove-position-4.0.2.tgz#a89be6ea72e23b1a402350832b02a91f6a9afe51" + integrity sha512-TkBb0HABNmxzAcfLf4qsIbFbaPDvMO6wa3b3j4VcEzFVaw1LBKwnW4/sRJ/atSLSzoIg41JWEdnE7N6DIhGDGQ== + dependencies: + "@types/unist" "^2.0.0" + unist-util-visit "^4.0.0" + +unist-util-stringify-position@^3.0.0: + version "3.0.3" + resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-3.0.3.tgz#03ad3348210c2d930772d64b489580c13a7db39d" + integrity sha512-k5GzIBZ/QatR8N5X2y+drfpWG8IDBzdnVj6OInRNWm1oXrzydiaAT2OQiA8DPRRZyAKb9b6I2a6PxYklZD0gKg== + dependencies: + "@types/unist" "^2.0.0" + +unist-util-visit-parents@^5.1.1: + version "5.1.3" + resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz#b4520811b0ca34285633785045df7a8d6776cfeb" + integrity sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg== + dependencies: + "@types/unist" "^2.0.0" + unist-util-is "^5.0.0" + +unist-util-visit@^4.0.0, unist-util-visit@^4.1.2: + version "4.1.2" + resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.2.tgz#125a42d1eb876283715a3cb5cceaa531828c72e2" + integrity sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg== + dependencies: + "@types/unist" "^2.0.0" + unist-util-is "^5.0.0" + unist-util-visit-parents "^5.1.1" + +util-deprecate@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== + +uvu@^0.5.0, uvu@^0.5.6: + version "0.5.6" + resolved "https://registry.yarnpkg.com/uvu/-/uvu-0.5.6.tgz#2754ca20bcb0bb59b64e9985e84d2e81058502df" + integrity sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA== + dependencies: + dequal "^2.0.0" + diff "^5.0.0" + kleur "^4.0.3" + sade "^1.7.3" + +vfile-message@^3.0.0: + version "3.1.4" + resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-3.1.4.tgz#15a50816ae7d7c2d1fa87090a7f9f96612b59dea" + integrity sha512-fa0Z6P8HUrQN4BZaX05SIVXic+7kE3b05PWAtPuYP9QLHsLKYR7/AlLW3NtOrpXRLeawpDLMsVkmk5DG0NXgWw== + dependencies: + "@types/unist" "^2.0.0" + unist-util-stringify-position "^3.0.0" + +vfile-reporter@^7.0.0: + version "7.0.5" + resolved "https://registry.yarnpkg.com/vfile-reporter/-/vfile-reporter-7.0.5.tgz#a0cbf3922c08ad428d6db1161ec64a53b5725785" + integrity sha512-NdWWXkv6gcd7AZMvDomlQbK3MqFWL1RlGzMn++/O2TI+68+nqxCPTvLugdOtfSzXmjh+xUyhp07HhlrbJjT+mw== + dependencies: + "@types/supports-color" "^8.0.0" + string-width "^5.0.0" + supports-color "^9.0.0" + unist-util-stringify-position "^3.0.0" + vfile "^5.0.0" + vfile-message "^3.0.0" + vfile-sort "^3.0.0" + vfile-statistics "^2.0.0" + +vfile-sort@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/vfile-sort/-/vfile-sort-3.0.1.tgz#4b06ec63e2946749b0bb514e736554cd75e441a2" + integrity sha512-1os1733XY6y0D5x0ugqSeaVJm9lYgj0j5qdcZQFyxlZOSy1jYarL77lLyb5gK4Wqr1d5OxmuyflSO3zKyFnTFw== + dependencies: + vfile "^5.0.0" + vfile-message "^3.0.0" + +vfile-statistics@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/vfile-statistics/-/vfile-statistics-2.0.1.tgz#2e1adae1cd3a45c1ed4f2a24bd103c3d71e4bce3" + integrity sha512-W6dkECZmP32EG/l+dp2jCLdYzmnDBIw6jwiLZSER81oR5AHRcVqL+k3Z+pfH1R73le6ayDkJRMk0sutj1bMVeg== + dependencies: + vfile "^5.0.0" + vfile-message "^3.0.0" + +vfile@^5.0.0, vfile@^5.1.0, vfile@^5.3.7: + version "5.3.7" + resolved "https://registry.yarnpkg.com/vfile/-/vfile-5.3.7.tgz#de0677e6683e3380fafc46544cfe603118826ab7" + integrity sha512-r7qlzkgErKjobAmyNIkkSpizsFPYiUPuJb5pNW1RB4JcYVZhs4lIbVqk8XPk033CV/1z8ss5pkax8SuhGpcG8g== + dependencies: + "@types/unist" "^2.0.0" + is-buffer "^2.0.0" + unist-util-stringify-position "^3.0.0" + vfile-message "^3.0.0" + +walk-up-path@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/walk-up-path/-/walk-up-path-3.0.1.tgz#c8d78d5375b4966c717eb17ada73dbd41490e886" + integrity sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA== + +which@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== + dependencies: + isexe "^2.0.0" + +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" + integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== + dependencies: + ansi-styles "^6.1.0" + string-width "^5.0.1" + strip-ansi "^7.0.1" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== + +yaml@^2.0.0: + version "2.8.1" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.8.1.tgz#1870aa02b631f7e8328b93f8bc574fac5d6c4d79" + integrity sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw== + +zwitch@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-2.0.4.tgz#c827d4b0acb76fc3e685a4c6ec2902d51070e9d7" + integrity sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A== diff --git a/next.config.js b/next.config.js index 861792c8e5..f8ec196e13 100644 --- a/next.config.js +++ b/next.config.js @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -12,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) { @@ -29,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 db4106809e..10ec29d016 100644 --- a/package.json +++ b/package.json @@ -7,20 +7,23 @@ "analyze": "ANALYZE=true next build", "dev": "next-remote-watch ./src/content", "build": "next build && node --experimental-modules ./scripts/downloadFonts.mjs", - "lint": "next lint", - "lint:fix": "next lint --fix", + "lint": "next lint && eslint \"src/content/**/*.md\"", + "lint:fix": "next lint --fix && eslint \"src/content/**/*.md\" --fix", "format:source": "prettier --config .prettierrc --write \"{plugins,src}/**/*.{js,ts,jsx,tsx,css}\"", "nit:source": "prettier --config .prettierrc --list-different \"{plugins,src}/**/*.{js,ts,jsx,tsx,css}\"", "prettier": "yarn format:source", "prettier:diff": "yarn nit:source", "lint-heading-ids": "node scripts/headingIdLinter.js", "fix-headings": "node scripts/headingIdLinter.js --fix", - "ci-check": "npm-run-all prettier:diff --parallel lint tsc lint-heading-ids rss", + "ci-check": "npm-run-all prettier:diff --parallel lint tsc lint-heading-ids rss deadlinks", "tsc": "tsc --noEmit", "start": "next start", - "postinstall": "is-ci || husky install .husky", + "postinstall": "yarn --cwd eslint-local-rules install && is-ci || husky install .husky", "check-all": "npm-run-all prettier lint:fix tsc rss", - "rss": "node scripts/generateRss.js" + "rss": "node scripts/generateRss.js", + "deadlinks": "node scripts/deadLinkChecker.js", + "copyright": "node scripts/copyright.js", + "test:eslint-local-rules": "yarn --cwd eslint-local-rules test" }, "dependencies": { "@codesandbox/sandpack-react": "2.13.5", @@ -30,10 +33,13 @@ "@radix-ui/react-context-menu": "^2.1.5", "body-scroll-lock": "^3.1.3", "classnames": "^2.2.6", - "date-fns": "^2.16.1", "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", @@ -61,13 +67,15 @@ "asyncro": "^3.0.0", "autoprefixer": "^10.4.2", "babel-eslint": "10.x", - "babel-plugin-react-compiler": "19.0.0-beta-e552027-20250112", + "babel-plugin-react-compiler": "^1.0.0", + "chalk": "4.1.2", "eslint": "7.x", "eslint-config-next": "12.0.3", "eslint-config-react-app": "^5.2.1", "eslint-plugin-flowtype": "4.x", "eslint-plugin-import": "2.x", "eslint-plugin-jsx-a11y": "6.x", + "eslint-plugin-local-rules": "link:eslint-local-rules", "eslint-plugin-react": "7.x", "eslint-plugin-react-compiler": "^19.0.0-beta-e552027-20250112", "eslint-plugin-react-hooks": "^0.0.0-experimental-fabef7a6b-20221215", diff --git a/plugins/markdownToHtml.js b/plugins/markdownToHtml.js index 0d5fe7afb4..e9b0c3ec32 100644 --- a/plugins/markdownToHtml.js +++ b/plugins/markdownToHtml.js @@ -1,3 +1,10 @@ +/** + * 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. + */ + const remark = require('remark'); const externalLinks = require('remark-external-links'); // Add _target and rel to external links const customHeaders = require('./remark-header-custom-ids'); // Custom header id's for i18n diff --git a/plugins/remark-header-custom-ids.js b/plugins/remark-header-custom-ids.js index 356de1bf13..c5430ce8a6 100644 --- a/plugins/remark-header-custom-ids.js +++ b/plugins/remark-header-custom-ids.js @@ -1,5 +1,8 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. */ /*! diff --git a/plugins/remark-smartypants.js b/plugins/remark-smartypants.js index 4694ff6746..c819624ba2 100644 --- a/plugins/remark-smartypants.js +++ b/plugins/remark-smartypants.js @@ -1,3 +1,10 @@ +/** + * 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. + */ + /*! * Based on 'silvenon/remark-smartypants' * https://github.com/silvenon/remark-smartypants/pull/80 @@ -7,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, @@ -36,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/postcss.config.js b/postcss.config.js index d55c43c909..6b55f92779 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -1,3 +1,10 @@ +/** + * 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. */ 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 0000000000..51c19598f6 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 0000000000..89efa6027b 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 0000000000..4aedaf4641 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 0000000000..09b48b70d7 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 0000000000..e836596937 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 0000000000..babb3d57c5 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 0000000000..116e40337a 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 0000000000..5fcf38ca99 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 0000000000..29ff140939 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 0000000000..0ae652f792 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 0000000000..758afceb15 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 0000000000..7e260135f0 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 0000000000..6709a7ea88 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 0000000000..33efe92893 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 0000000000..57e3a30b09 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 0000000000..ff315b99df 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 0000000000..c0608b153f 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 0000000000..4367377670 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 0000000000..07513fe90b 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 0000000000..835a247cf6 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 0000000000..beb4512d2d 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 0000000000..8631c4896f 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 0000000000..df252663a4 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 0000000000..79a361d2aa 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 0000000000..7e48020f8a 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 0000000000..1cd07a1447 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 0000000000..221fb1204a 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 0000000000..85c7eed27a Binary files /dev/null and b/public/images/docs/performance-tracks/server-overview.png differ diff --git a/public/images/tutorial/react-starter-code-codesandbox.png b/public/images/tutorial/react-starter-code-codesandbox.png old mode 100644 new mode 100755 index d65f161bcc..b01e182978 Binary files a/public/images/tutorial/react-starter-code-codesandbox.png and b/public/images/tutorial/react-starter-code-codesandbox.png differ diff --git a/public/js/jsfiddle-integration-babel.js b/public/js/jsfiddle-integration-babel.js index 56059472ff..56133855a6 100644 --- a/public/js/jsfiddle-integration-babel.js +++ b/public/js/jsfiddle-integration-babel.js @@ -1,5 +1,8 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. */ // Do not delete or move this file. diff --git a/public/js/jsfiddle-integration.js b/public/js/jsfiddle-integration.js index 2151435d43..aeae13607b 100644 --- a/public/js/jsfiddle-integration.js +++ b/public/js/jsfiddle-integration.js @@ -1,5 +1,8 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. */ // Do not delete or move this file. diff --git a/scripts/copyright.js b/scripts/copyright.js new file mode 100644 index 0000000000..f1c6f786cd --- /dev/null +++ b/scripts/copyright.js @@ -0,0 +1,84 @@ +/** + * 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. + */ + +'use strict'; + +const fs = require('fs'); +const glob = require('glob'); + +const META_COPYRIGHT_COMMENT_BLOCK = + `/** + * 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. + */`.trim() + '\n\n'; + +const files = glob.sync('**/*.{js,ts,tsx,jsx,rs}', { + ignore: [ + '**/dist/**', + '**/node_modules/**', + '**/tests/fixtures/**', + '**/__tests__/fixtures/**', + ], +}); + +const updatedFiles = new Map(); +let hasErrors = false; +files.forEach((file) => { + try { + const result = processFile(file); + if (result != null) { + updatedFiles.set(file, result); + } + } catch (e) { + console.error(e); + hasErrors = true; + } +}); +if (hasErrors) { + console.error('Update failed'); + process.exit(1); +} else { + for (const [file, source] of updatedFiles) { + fs.writeFileSync(file, source, 'utf8'); + } + console.log('Update complete'); +} + +function processFile(file) { + if (fs.lstatSync(file).isDirectory()) { + return; + } + let source = fs.readFileSync(file, 'utf8'); + let shebang = ''; + + if (source.startsWith('#!')) { + const newlineIndex = source.indexOf('\n'); + if (newlineIndex === -1) { + shebang = `${source}\n`; + source = ''; + } else { + shebang = source.slice(0, newlineIndex + 1); + source = source.slice(newlineIndex + 1); + } + } + + if (source.indexOf(META_COPYRIGHT_COMMENT_BLOCK) === 0) { + return null; + } + if (/^\/\*\*/.test(source)) { + source = source.replace(/\/\*\*[^\/]+\/\s+/, META_COPYRIGHT_COMMENT_BLOCK); + } else { + source = `${META_COPYRIGHT_COMMENT_BLOCK}${source}`; + } + + if (shebang) { + return `${shebang}${source}`; + } + return source; +} diff --git a/scripts/deadLinkChecker.js b/scripts/deadLinkChecker.js new file mode 100644 index 0000000000..46a21cdc9e --- /dev/null +++ b/scripts/deadLinkChecker.js @@ -0,0 +1,391 @@ +#!/usr/bin/env node +/** + * 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. + */ + +const fs = require('fs'); +const path = require('path'); +const globby = require('globby'); +const chalk = require('chalk'); + +const CONTENT_DIR = path.join(__dirname, '../src/content'); +const PUBLIC_DIR = path.join(__dirname, '../public'); +const fileCache = new Map(); +const anchorMap = new Map(); // Map<filepath, Set<anchorId>> +const contributorMap = new Map(); // Map<anchorId, URL> +const redirectMap = new Map(); // Map<source, destination> +let errorCodes = new Set(); + +async function readFileWithCache(filePath) { + if (!fileCache.has(filePath)) { + try { + const content = await fs.promises.readFile(filePath, 'utf8'); + fileCache.set(filePath, content); + } catch (error) { + throw new Error(`Failed to read file ${filePath}: ${error.message}`); + } + } + return fileCache.get(filePath); +} + +async function fileExists(filePath) { + try { + await fs.promises.access(filePath, fs.constants.R_OK); + return true; + } catch { + return false; + } +} + +function getMarkdownFiles() { + // Convert Windows paths to POSIX for globby compatibility + const baseDir = CONTENT_DIR.replace(/\\/g, '/'); + const patterns = [ + path.posix.join(baseDir, '**/*.md'), + path.posix.join(baseDir, '**/*.mdx'), + ]; + return globby.sync(patterns); +} + +function extractAnchorsFromContent(content) { + const anchors = new Set(); + + // MDX-style heading IDs: {/*anchor-id*/} + const mdxPattern = /\{\/\*([a-zA-Z0-9-_]+)\*\/\}/g; + let match; + while ((match = mdxPattern.exec(content)) !== null) { + anchors.add(match[1].toLowerCase()); + } + + // HTML id attributes + const htmlIdPattern = /\sid=["']([a-zA-Z0-9-_]+)["']/g; + while ((match = htmlIdPattern.exec(content)) !== null) { + anchors.add(match[1].toLowerCase()); + } + + // Markdown heading with explicit ID: ## Heading {#anchor-id} + const markdownHeadingPattern = /^#+\s+.*\{#([a-zA-Z0-9-_]+)\}/gm; + while ((match = markdownHeadingPattern.exec(content)) !== null) { + anchors.add(match[1].toLowerCase()); + } + + return anchors; +} + +async function buildAnchorMap(files) { + for (const filePath of files) { + const content = await readFileWithCache(filePath); + const anchors = extractAnchorsFromContent(content); + if (anchors.size > 0) { + anchorMap.set(filePath, anchors); + } + } +} + +function extractLinksFromContent(content) { + const linkPattern = /\[([^\]]*)\]\(([^)]+)\)/g; + const links = []; + let match; + + while ((match = linkPattern.exec(content)) !== null) { + const [, linkText, linkUrl] = match; + if (linkUrl.startsWith('/') && !linkUrl.startsWith('//')) { + const lines = content.substring(0, match.index).split('\n'); + const line = lines.length; + const lastLineStart = + lines.length > 1 ? content.lastIndexOf('\n', match.index - 1) + 1 : 0; + const column = match.index - lastLineStart + 1; + + links.push({ + text: linkText, + url: linkUrl, + line, + column, + }); + } + } + + return links; +} + +async function findTargetFile(urlPath) { + // Check if it's an image or static asset that might be in the public directory + const imageExtensions = [ + '.png', + '.jpg', + '.jpeg', + '.gif', + '.svg', + '.ico', + '.webp', + ]; + const hasImageExtension = imageExtensions.some((ext) => + urlPath.toLowerCase().endsWith(ext) + ); + + if (hasImageExtension || urlPath.includes('.')) { + // Check in public directory (with and without leading slash) + const publicPaths = [ + path.join(PUBLIC_DIR, urlPath), + path.join(PUBLIC_DIR, urlPath.substring(1)), + ]; + + for (const p of publicPaths) { + if (await fileExists(p)) { + return p; + } + } + } + + const possiblePaths = [ + path.join(CONTENT_DIR, urlPath + '.md'), + path.join(CONTENT_DIR, urlPath + '.mdx'), + path.join(CONTENT_DIR, urlPath, 'index.md'), + path.join(CONTENT_DIR, urlPath, 'index.mdx'), + // Without leading slash + path.join(CONTENT_DIR, urlPath.substring(1) + '.md'), + path.join(CONTENT_DIR, urlPath.substring(1) + '.mdx'), + path.join(CONTENT_DIR, urlPath.substring(1), 'index.md'), + path.join(CONTENT_DIR, urlPath.substring(1), 'index.mdx'), + ]; + + for (const p of possiblePaths) { + if (await fileExists(p)) { + return p; + } + } + return null; +} + +async function validateLink(link) { + const urlAnchorPattern = /#([a-zA-Z0-9-_]+)$/; + const anchorMatch = link.url.match(urlAnchorPattern); + const urlWithoutAnchor = link.url.replace(urlAnchorPattern, ''); + + if (urlWithoutAnchor === '/') { + return {valid: true}; + } + + // Check for redirects + if (redirectMap.has(urlWithoutAnchor)) { + const redirectDestination = redirectMap.get(urlWithoutAnchor); + if ( + redirectDestination.startsWith('http://') || + redirectDestination.startsWith('https://') + ) { + return {valid: true}; + } + const redirectedLink = { + ...link, + url: redirectDestination + (anchorMatch ? anchorMatch[0] : ''), + }; + return validateLink(redirectedLink); + } + + // Check if it's an error code link + const errorCodeMatch = urlWithoutAnchor.match(/^\/errors\/(\d+)$/); + if (errorCodeMatch) { + const code = errorCodeMatch[1]; + if (!errorCodes.has(code)) { + return { + valid: false, + reason: `Error code ${code} not found in React error codes`, + }; + } + return {valid: true}; + } + + // Check if it's a contributor link on the team or acknowledgements page + if ( + anchorMatch && + (urlWithoutAnchor === '/community/team' || + urlWithoutAnchor === '/community/acknowledgements') + ) { + const anchorId = anchorMatch[1].toLowerCase(); + if (contributorMap.has(anchorId)) { + const correctUrl = contributorMap.get(anchorId); + if (correctUrl !== link.url) { + return { + valid: false, + reason: `Contributor link should be updated to: ${correctUrl}`, + }; + } + return {valid: true}; + } else { + return { + valid: false, + reason: `Contributor link not found`, + }; + } + } + + const targetFile = await findTargetFile(urlWithoutAnchor); + + if (!targetFile) { + return { + valid: false, + reason: `Target file not found for: ${urlWithoutAnchor}`, + }; + } + + // Only check anchors for content files, not static assets + if (anchorMatch && targetFile.startsWith(CONTENT_DIR)) { + const anchorId = anchorMatch[1].toLowerCase(); + + // TODO handle more special cases. These are usually from custom MDX components that include + // a Heading from src/components/MDX/Heading.tsx which automatically injects an anchor tag. + switch (anchorId) { + case 'challenges': + case 'recap': { + return {valid: true}; + } + } + + const fileAnchors = anchorMap.get(targetFile); + + if (!fileAnchors || !fileAnchors.has(anchorId)) { + return { + valid: false, + reason: `Anchor #${anchorMatch[1]} not found in ${path.relative( + CONTENT_DIR, + targetFile + )}`, + }; + } + } + + return {valid: true}; +} + +async function processFile(filePath) { + const content = await readFileWithCache(filePath); + const links = extractLinksFromContent(content); + const deadLinks = []; + + for (const link of links) { + const result = await validateLink(link); + if (!result.valid) { + deadLinks.push({ + file: path.relative(process.cwd(), filePath), + line: link.line, + column: link.column, + text: link.text, + url: link.url, + reason: result.reason, + }); + } + } + + return {deadLinks, totalLinks: links.length}; +} + +async function buildContributorMap() { + const teamFile = path.join(CONTENT_DIR, 'community/team.md'); + const teamContent = await readFileWithCache(teamFile); + + const teamMemberPattern = /<TeamMember[^>]*permalink=["']([^"']+)["']/g; + let match; + + while ((match = teamMemberPattern.exec(teamContent)) !== null) { + const permalink = match[1]; + contributorMap.set(permalink, `/community/team#${permalink}`); + } + + const ackFile = path.join(CONTENT_DIR, 'community/acknowledgements.md'); + const ackContent = await readFileWithCache(ackFile); + const contributorPattern = /\*\s*\[([^\]]+)\]\(([^)]+)\)/g; + + while ((match = contributorPattern.exec(ackContent)) !== null) { + const name = match[1]; + const url = match[2]; + const hyphenatedName = name.toLowerCase().replace(/\s+/g, '-'); + if (!contributorMap.has(hyphenatedName)) { + contributorMap.set(hyphenatedName, url); + } + } +} + +async function fetchErrorCodes() { + try { + const response = await fetch( + 'https://raw.githubusercontent.com/facebook/react/main/scripts/error-codes/codes.json' + ); + if (!response.ok) { + throw new Error(`Failed to fetch error codes: ${response.status}`); + } + const codes = await response.json(); + errorCodes = new Set(Object.keys(codes)); + console.log(chalk.gray(`Fetched ${errorCodes.size} React error codes`)); + } catch (error) { + throw new Error(`Failed to fetch error codes: ${error.message}`); + } +} + +async function buildRedirectsMap() { + try { + const vercelConfigPath = path.join(__dirname, '../vercel.json'); + const vercelConfig = JSON.parse( + await fs.promises.readFile(vercelConfigPath, 'utf8') + ); + + if (vercelConfig.redirects) { + for (const redirect of vercelConfig.redirects) { + redirectMap.set(redirect.source, redirect.destination); + } + console.log( + chalk.gray(`Loaded ${redirectMap.size} redirects from vercel.json`) + ); + } + } catch (error) { + console.log( + chalk.yellow( + `Warning: Could not load redirects from vercel.json: ${error.message}\n` + ) + ); + } +} + +async function main() { + const files = getMarkdownFiles(); + console.log(chalk.gray(`Checking ${files.length} markdown files...`)); + + await fetchErrorCodes(); + await buildRedirectsMap(); + await buildContributorMap(); + await buildAnchorMap(files); + + const filePromises = files.map((filePath) => processFile(filePath)); + const results = await Promise.all(filePromises); + const deadLinks = results.flatMap((r) => r.deadLinks); + const totalLinks = results.reduce((sum, r) => sum + r.totalLinks, 0); + + if (deadLinks.length > 0) { + console.log('\n'); + for (const link of deadLinks) { + console.log(chalk.yellow(`${link.file}:${link.line}:${link.column}`)); + console.log(chalk.reset(` Link text: ${link.text}`)); + console.log(chalk.reset(` URL: ${link.url}`)); + console.log(` ${chalk.red('βœ—')} ${chalk.red(link.reason)}\n`); + } + + console.log( + chalk.red( + `\nFound ${deadLinks.length} dead link${ + deadLinks.length > 1 ? 's' : '' + } out of ${totalLinks} total links\n` + ) + ); + process.exit(1); + } + + console.log(chalk.green(`\nβœ“ All ${totalLinks} links are valid!\n`)); + process.exit(0); +} + +main().catch((error) => { + console.log(chalk.red(`Error: ${error.message}`)); + process.exit(1); +}); diff --git a/scripts/generateRss.js b/scripts/generateRss.js index e0f3d5561d..3231b1d735 100644 --- a/scripts/generateRss.js +++ b/scripts/generateRss.js @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/scripts/headingIDHelpers/generateHeadingIDs.js b/scripts/headingIDHelpers/generateHeadingIDs.js index 40925d444c..79839f513d 100644 --- a/scripts/headingIDHelpers/generateHeadingIDs.js +++ b/scripts/headingIDHelpers/generateHeadingIDs.js @@ -1,5 +1,8 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. */ // To do: Make this ESM. diff --git a/scripts/headingIDHelpers/validateHeadingIDs.js b/scripts/headingIDHelpers/validateHeadingIDs.js index c3cf1ab8c8..798a63e12c 100644 --- a/scripts/headingIDHelpers/validateHeadingIDs.js +++ b/scripts/headingIDHelpers/validateHeadingIDs.js @@ -1,6 +1,10 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. */ + const fs = require('fs'); const walk = require('./walk'); diff --git a/scripts/headingIDHelpers/walk.js b/scripts/headingIDHelpers/walk.js index 54cd500ca3..f1ed5e0b31 100644 --- a/scripts/headingIDHelpers/walk.js +++ b/scripts/headingIDHelpers/walk.js @@ -1,3 +1,10 @@ +/** + * 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. + */ + const fs = require('fs'); module.exports = function walk(dir) { diff --git a/scripts/headingIdLinter.js b/scripts/headingIdLinter.js index 6b8f75fc71..32116752be 100644 --- a/scripts/headingIdLinter.js +++ b/scripts/headingIdLinter.js @@ -1,3 +1,10 @@ +/** + * 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. + */ + const validateHeaderIds = require('./headingIDHelpers/validateHeadingIDs'); const generateHeadingIds = require('./headingIDHelpers/generateHeadingIDs'); diff --git a/src/components/Breadcrumbs.tsx b/src/components/Breadcrumbs.tsx index e64b486d13..177af2c56a 100644 --- a/src/components/Breadcrumbs.tsx +++ b/src/components/Breadcrumbs.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Button.tsx b/src/components/Button.tsx index 65c0151ba3..6b79a958f2 100644 --- a/src/components/Button.tsx +++ b/src/components/Button.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/ButtonLink.tsx b/src/components/ButtonLink.tsx index 23c971756b..bd98d5b38e 100644 --- a/src/components/ButtonLink.tsx +++ b/src/components/ButtonLink.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/DocsFooter.tsx b/src/components/DocsFooter.tsx index 272a504707..171c87bd52 100644 --- a/src/components/DocsFooter.tsx +++ b/src/components/DocsFooter.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -80,7 +87,7 @@ function FooterLink({ /> <div className="flex flex-col overflow-hidden"> <span className="text-sm font-bold tracking-wide no-underline uppercase text-secondary dark:text-secondary-dark group-focus:text-link dark:group-focus:text-link-dark group-focus:text-opacity-100"> - {type} + {type === 'Previous' ? 'Previous' : 'Next'} </span> <span className="text-lg break-words group-hover:underline"> {title} diff --git a/src/components/ErrorDecoderContext.tsx b/src/components/ErrorDecoderContext.tsx index 080969efe9..77e9ebf7d5 100644 --- a/src/components/ErrorDecoderContext.tsx +++ b/src/components/ErrorDecoderContext.tsx @@ -1,3 +1,10 @@ +/** + * 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. + */ + // Error Decoder requires reading pregenerated error message from getStaticProps, // but MDX component doesn't support props. So we use React Context to populate // the value without prop-drilling. diff --git a/src/components/ExternalLink.tsx b/src/components/ExternalLink.tsx index 13fe6d3a90..ccd91fe9c4 100644 --- a/src/components/ExternalLink.tsx +++ b/src/components/ExternalLink.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconArrow.tsx b/src/components/Icon/IconArrow.tsx index 61e4e52cd6..2d0b9fecdc 100644 --- a/src/components/Icon/IconArrow.tsx +++ b/src/components/Icon/IconArrow.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconArrowSmall.tsx b/src/components/Icon/IconArrowSmall.tsx index 4a3d3ad02f..81301c0475 100644 --- a/src/components/Icon/IconArrowSmall.tsx +++ b/src/components/Icon/IconArrowSmall.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -19,6 +26,7 @@ export const IconArrowSmall = memo< const classes = cn(className, { 'rotate-180': displayDirection === 'left', 'rotate-180 rtl:rotate-0': displayDirection === 'start', + 'rtl:rotate-180': displayDirection === 'end', 'rotate-90': displayDirection === 'down', }); return ( diff --git a/src/components/Icon/IconBsky.tsx b/src/components/Icon/IconBsky.tsx index 5d461556fb..ec930923d3 100644 --- a/src/components/Icon/IconBsky.tsx +++ b/src/components/Icon/IconBsky.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconCanary.tsx b/src/components/Icon/IconCanary.tsx index 7f584fed76..97b9f7cef2 100644 --- a/src/components/Icon/IconCanary.tsx +++ b/src/components/Icon/IconCanary.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconChevron.tsx b/src/components/Icon/IconChevron.tsx index 4d40330ce0..15f34e1535 100644 --- a/src/components/Icon/IconChevron.tsx +++ b/src/components/Icon/IconChevron.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconClose.tsx b/src/components/Icon/IconClose.tsx index d685fb2178..dc4ad7c72d 100644 --- a/src/components/Icon/IconClose.tsx +++ b/src/components/Icon/IconClose.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconCodeBlock.tsx b/src/components/Icon/IconCodeBlock.tsx index 755a2ae34a..ba61f237ed 100644 --- a/src/components/Icon/IconCodeBlock.tsx +++ b/src/components/Icon/IconCodeBlock.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconCopy.tsx b/src/components/Icon/IconCopy.tsx index 500cd4fda9..f621346077 100644 --- a/src/components/Icon/IconCopy.tsx +++ b/src/components/Icon/IconCopy.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconDeepDive.tsx b/src/components/Icon/IconDeepDive.tsx index dfe1a928ca..121391f330 100644 --- a/src/components/Icon/IconDeepDive.tsx +++ b/src/components/Icon/IconDeepDive.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconDownload.tsx b/src/components/Icon/IconDownload.tsx index c0e7f49c21..be551d83e6 100644 --- a/src/components/Icon/IconDownload.tsx +++ b/src/components/Icon/IconDownload.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconError.tsx b/src/components/Icon/IconError.tsx index f101f62b22..966777fd44 100644 --- a/src/components/Icon/IconError.tsx +++ b/src/components/Icon/IconError.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconExperimental.tsx b/src/components/Icon/IconExperimental.tsx index 0bba612ebc..c0dce97f46 100644 --- a/src/components/Icon/IconExperimental.tsx +++ b/src/components/Icon/IconExperimental.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -6,7 +13,7 @@ import {memo} from 'react'; export const IconExperimental = memo< JSX.IntrinsicElements['svg'] & {title?: string; size?: 's' | 'md'} ->(function IconCanary( +>(function IconExperimental( {className, title, size} = { className: undefined, title: undefined, diff --git a/src/components/Icon/IconFacebookCircle.tsx b/src/components/Icon/IconFacebookCircle.tsx index 7f1080afa1..dea2764d55 100644 --- a/src/components/Icon/IconFacebookCircle.tsx +++ b/src/components/Icon/IconFacebookCircle.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconGitHub.tsx b/src/components/Icon/IconGitHub.tsx index 1852f52f1d..06c8f15564 100644 --- a/src/components/Icon/IconGitHub.tsx +++ b/src/components/Icon/IconGitHub.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconHamburger.tsx b/src/components/Icon/IconHamburger.tsx index 8bc90ee0c2..5ab29fa37e 100644 --- a/src/components/Icon/IconHamburger.tsx +++ b/src/components/Icon/IconHamburger.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconHint.tsx b/src/components/Icon/IconHint.tsx index b802bc79c0..802382b5d1 100644 --- a/src/components/Icon/IconHint.tsx +++ b/src/components/Icon/IconHint.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconInstagram.tsx b/src/components/Icon/IconInstagram.tsx index 79def08e32..00d25a909d 100644 --- a/src/components/Icon/IconInstagram.tsx +++ b/src/components/Icon/IconInstagram.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconLink.tsx b/src/components/Icon/IconLink.tsx index e6e716d005..0f7d4dfed2 100644 --- a/src/components/Icon/IconLink.tsx +++ b/src/components/Icon/IconLink.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconNavArrow.tsx b/src/components/Icon/IconNavArrow.tsx index f61175e9b5..40fde8afea 100644 --- a/src/components/Icon/IconNavArrow.tsx +++ b/src/components/Icon/IconNavArrow.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconNewPage.tsx b/src/components/Icon/IconNewPage.tsx index dfa13bac95..aaf3e8157b 100644 --- a/src/components/Icon/IconNewPage.tsx +++ b/src/components/Icon/IconNewPage.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconNote.tsx b/src/components/Icon/IconNote.tsx index 1510c91c7e..82ed947b44 100644 --- a/src/components/Icon/IconNote.tsx +++ b/src/components/Icon/IconNote.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconPitfall.tsx b/src/components/Icon/IconPitfall.tsx index ee62478913..a80fc7d68f 100644 --- a/src/components/Icon/IconPitfall.tsx +++ b/src/components/Icon/IconPitfall.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconRestart.tsx b/src/components/Icon/IconRestart.tsx index b4a6b62f5e..976203c65c 100644 --- a/src/components/Icon/IconRestart.tsx +++ b/src/components/Icon/IconRestart.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconRocket.tsx b/src/components/Icon/IconRocket.tsx index 457736c7c5..c5bb2473a9 100644 --- a/src/components/Icon/IconRocket.tsx +++ b/src/components/Icon/IconRocket.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconRss.tsx b/src/components/Icon/IconRss.tsx index 6208236f46..13029ec963 100644 --- a/src/components/Icon/IconRss.tsx +++ b/src/components/Icon/IconRss.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconSearch.tsx b/src/components/Icon/IconSearch.tsx index 917513561a..1dda00eb26 100644 --- a/src/components/Icon/IconSearch.tsx +++ b/src/components/Icon/IconSearch.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconSolution.tsx b/src/components/Icon/IconSolution.tsx index 668e41afe2..b0f1d44b38 100644 --- a/src/components/Icon/IconSolution.tsx +++ b/src/components/Icon/IconSolution.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconTerminal.tsx b/src/components/Icon/IconTerminal.tsx index 7b3a97a8cb..66dfd47b77 100644 --- a/src/components/Icon/IconTerminal.tsx +++ b/src/components/Icon/IconTerminal.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconThreads.tsx b/src/components/Icon/IconThreads.tsx index 9ea0bafdf3..72ded5201c 100644 --- a/src/components/Icon/IconThreads.tsx +++ b/src/components/Icon/IconThreads.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconTwitter.tsx b/src/components/Icon/IconTwitter.tsx index e84971f4ee..01802c253f 100644 --- a/src/components/Icon/IconTwitter.tsx +++ b/src/components/Icon/IconTwitter.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Icon/IconWarning.tsx b/src/components/Icon/IconWarning.tsx index 83534ec5f1..90b7cd41e6 100644 --- a/src/components/Icon/IconWarning.tsx +++ b/src/components/Icon/IconWarning.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/Footer.tsx b/src/components/Layout/Footer.tsx index 905ae16e98..fb0810eb94 100644 --- a/src/components/Layout/Footer.tsx +++ b/src/components/Layout/Footer.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/HomeContent.js b/src/components/Layout/HomeContent.js index 5c22b431a7..de7685c7bf 100644 --- a/src/components/Layout/HomeContent.js +++ b/src/components/Layout/HomeContent.js @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -247,6 +254,7 @@ export function HomeContent() { <i>framework</i>) </Header> <Para> +<<<<<<< HEAD React adalah sebuah pustaka. React memungkinkan Anda untuk menyatukan komponen-komponen, tetapi tidak menentukan bagaimana cara melakukan <i>routing</i> dan pengambilan data. Untuk @@ -254,6 +262,13 @@ export function HomeContent() { merekomendasikan kerangka kerja <i>full-stack</i> React seperti{' '} <Link href="https://nextjs.org">Next.js</Link> atau{' '} <Link href="https://remix.run">Remix</Link>. +======= + React is a library. It lets you put components together, but it + 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://reactrouter.com">React Router</Link>. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Para> </Center> <FullBleed> @@ -271,8 +286,13 @@ export function HomeContent() { <CTA color="gray" icon="framework" +<<<<<<< HEAD href="/learn/start-a-new-react-project"> Memulai dengan framework +======= + href="/learn/creating-a-react-app"> + Get started with a framework +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </CTA> </div> </Center> @@ -778,9 +798,7 @@ function CommunityGallery() { }, []); return ( - <div - ref={ref} - className="relative flex overflow-x-hidden overflow-y-visible w-auto"> + <div ref={ref} className="relative flex overflow-x-clip w-auto"> <div className="w-full py-12 lg:py-20 whitespace-nowrap flex flex-row animate-marquee lg:animate-large-marquee" style={{ @@ -807,21 +825,26 @@ const CommunityImages = memo(function CommunityImages({isLazy}) { <div key={i} className={cn( - `group flex justify-center px-5 min-w-[50%] lg:min-w-[25%] rounded-2xl relative` + `group flex justify-center px-5 min-w-[50%] lg:min-w-[25%] rounded-2xl` )}> <div className={cn( - 'h-auto relative rounded-2xl overflow-hidden before:-skew-x-12 before:absolute before:inset-0 before:-translate-x-full group-hover:before:animate-[shimmer_1s_forwards] before:bg-gradient-to-r before:from-transparent before:via-white/10 before:to-transparent transition-all ease-in-out duration-300', + 'h-auto rounded-2xl before:rounded-2xl before:absolute before:pointer-events-none before:inset-0 before:transition-opacity before:-z-1 before:shadow-lg lg:before:shadow-2xl before:opacity-0 before:group-hover:opacity-100 transition-transform ease-in-out duration-300', i % 2 === 0 - ? 'rotate-2 group-hover:rotate-[-1deg] group-hover:scale-110 group-hover:shadow-lg lg:group-hover:shadow-2xl' - : 'group-hover:rotate-1 group-hover:scale-110 group-hover:shadow-lg lg:group-hover:shadow-2xl rotate-[-2deg]' + ? 'rotate-2 group-hover:rotate-[-1deg] group-hover:scale-110' + : 'group-hover:rotate-1 group-hover:scale-110 rotate-[-2deg]' )}> - <img - loading={isLazy ? 'lazy' : 'eager'} - src={src} - alt={alt} - className="aspect-[4/3] h-full w-full flex object-cover rounded-2xl bg-gray-10 dark:bg-gray-80" - /> + <div + className={cn( + 'overflow-clip relative before:absolute before:inset-0 before:pointer-events-none before:-translate-x-full group-hover:before:animate-[shimmer_1s_forwards] before:bg-gradient-to-r before:from-transparent before:via-white/10 before:to-transparent transition-transform ease-in-out duration-300' + )}> + <img + loading={isLazy ? 'lazy' : 'eager'} + src={src} + alt={alt} + className="aspect-[4/3] h-full w-full flex object-cover rounded-2xl bg-gray-10 dark:bg-gray-80" + /> + </div> </div> </div> ))} diff --git a/src/components/Layout/Page.tsx b/src/components/Layout/Page.tsx index c3224e5174..aa39fe5fc2 100644 --- a/src/components/Layout/Page.tsx +++ b/src/components/Layout/Page.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -8,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'; @@ -135,7 +142,7 @@ export function Page({ /> </Head> )} - <SocialBanner /> + {/* <SocialBanner /> */} <TopNav section={section} routeTree={routeTree} diff --git a/src/components/Layout/Sidebar/SidebarButton.tsx b/src/components/Layout/Sidebar/SidebarButton.tsx index dc1f29a8d4..744172becb 100644 --- a/src/components/Layout/Sidebar/SidebarButton.tsx +++ b/src/components/Layout/Sidebar/SidebarButton.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/Sidebar/SidebarLink.tsx b/src/components/Layout/Sidebar/SidebarLink.tsx index 2d7c718381..7fd6a341d1 100644 --- a/src/components/Layout/Sidebar/SidebarLink.tsx +++ b/src/components/Layout/Sidebar/SidebarLink.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -17,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; @@ -95,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/Sidebar/SidebarRouteTree.tsx b/src/components/Layout/Sidebar/SidebarRouteTree.tsx index 72003df74f..863355bfdc 100644 --- a/src/components/Layout/Sidebar/SidebarRouteTree.tsx +++ b/src/components/Layout/Sidebar/SidebarRouteTree.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/Sidebar/index.tsx b/src/components/Layout/Sidebar/index.tsx index d0e2915475..69664e6bc7 100644 --- a/src/components/Layout/Sidebar/index.tsx +++ b/src/components/Layout/Sidebar/index.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/SidebarNav/SidebarNav.tsx b/src/components/Layout/SidebarNav/SidebarNav.tsx index 1712709603..678d483c14 100644 --- a/src/components/Layout/SidebarNav/SidebarNav.tsx +++ b/src/components/Layout/SidebarNav/SidebarNav.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -5,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'; @@ -56,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/SidebarNav/index.tsx b/src/components/Layout/SidebarNav/index.tsx index b268bbd294..f9680d803f 100644 --- a/src/components/Layout/SidebarNav/index.tsx +++ b/src/components/Layout/SidebarNav/index.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/Toc.tsx b/src/components/Layout/Toc.tsx index 98d478d508..789f22e199 100644 --- a/src/components/Layout/Toc.tsx +++ b/src/components/Layout/Toc.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/TopNav/BrandMenu.tsx b/src/components/Layout/TopNav/BrandMenu.tsx index 3bd8776f22..218e423ce3 100644 --- a/src/components/Layout/TopNav/BrandMenu.tsx +++ b/src/components/Layout/TopNav/BrandMenu.tsx @@ -1,3 +1,10 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + import * as ContextMenu from '@radix-ui/react-context-menu'; import {IconCopy} from 'components/Icon/IconCopy'; import {IconDownload} from 'components/Icon/IconDownload'; diff --git a/src/components/Layout/TopNav/TopNav.tsx b/src/components/Layout/TopNav/TopNav.tsx index d4fcb7ef2a..56a58a7c9d 100644 --- a/src/components/Layout/TopNav/TopNav.tsx +++ b/src/components/Layout/TopNav/TopNav.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -22,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'; @@ -441,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/Layout/TopNav/index.tsx b/src/components/Layout/TopNav/index.tsx index 8472fb126d..e76fa5ed0d 100644 --- a/src/components/Layout/TopNav/index.tsx +++ b/src/components/Layout/TopNav/index.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/getRouteMeta.tsx b/src/components/Layout/getRouteMeta.tsx index b3d14725d4..5a85a3e21b 100644 --- a/src/components/Layout/getRouteMeta.tsx +++ b/src/components/Layout/getRouteMeta.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Layout/useTocHighlight.tsx b/src/components/Layout/useTocHighlight.tsx index 544396c68b..02385409ff 100644 --- a/src/components/Layout/useTocHighlight.tsx +++ b/src/components/Layout/useTocHighlight.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Logo.tsx b/src/components/Logo.tsx index 8c4f7da4f9..3ea4ba9ac8 100644 --- a/src/components/Logo.tsx +++ b/src/components/Logo.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/BlogCard.tsx b/src/components/MDX/BlogCard.tsx index 1f33630dec..741f4cefd8 100644 --- a/src/components/MDX/BlogCard.tsx +++ b/src/components/MDX/BlogCard.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Challenges/Challenge.tsx b/src/components/MDX/Challenges/Challenge.tsx index 8484ea290b..c247a791ec 100644 --- a/src/components/MDX/Challenges/Challenge.tsx +++ b/src/components/MDX/Challenges/Challenge.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Challenges/Challenges.tsx b/src/components/MDX/Challenges/Challenges.tsx index 37ae161a5a..3946776ab7 100644 --- a/src/components/MDX/Challenges/Challenges.tsx +++ b/src/components/MDX/Challenges/Challenges.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Challenges/Navigation.tsx b/src/components/MDX/Challenges/Navigation.tsx index 736db093c6..0511bd05ad 100644 --- a/src/components/MDX/Challenges/Navigation.tsx +++ b/src/components/MDX/Challenges/Navigation.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -108,7 +115,7 @@ export function Navigation({ onClick={handleScrollLeft} aria-label="Scroll left" className={cn( - 'bg-secondary-button dark:bg-secondary-button-dark h-8 px-2 rounded-l border-gray-20 border-r rtl:rotate-180', + 'bg-secondary-button dark:bg-secondary-button-dark h-8 px-2 rounded-l rtl:rounded-r rtl:rounded-l-none border-gray-20 border-r rtl:border-l rtl:border-r-0', { 'text-primary dark:text-primary-dark': canScrollLeft, 'text-gray-30': !canScrollLeft, @@ -120,7 +127,7 @@ export function Navigation({ onClick={handleScrollRight} aria-label="Scroll right" className={cn( - 'bg-secondary-button dark:bg-secondary-button-dark h-8 px-2 rounded-e rtl:rotate-180', + 'bg-secondary-button dark:bg-secondary-button-dark h-8 px-2 rounded-e', { 'text-primary dark:text-primary-dark': canScrollRight, 'text-gray-30': !canScrollRight, diff --git a/src/components/MDX/Challenges/index.tsx b/src/components/MDX/Challenges/index.tsx index 413fd46112..27e3df1ef0 100644 --- a/src/components/MDX/Challenges/index.tsx +++ b/src/components/MDX/Challenges/index.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/CodeBlock/CodeBlock.tsx b/src/components/MDX/CodeBlock/CodeBlock.tsx index 42165c57d8..3eeac39452 100644 --- a/src/components/MDX/CodeBlock/CodeBlock.tsx +++ b/src/components/MDX/CodeBlock/CodeBlock.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/CodeBlock/index.tsx b/src/components/MDX/CodeBlock/index.tsx index 551c1d1b66..d3ed3a0659 100644 --- a/src/components/MDX/CodeBlock/index.tsx +++ b/src/components/MDX/CodeBlock/index.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/CodeDiagram.tsx b/src/components/MDX/CodeDiagram.tsx index 2a198fc56a..ba18ae973f 100644 --- a/src/components/MDX/CodeDiagram.tsx +++ b/src/components/MDX/CodeDiagram.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/ConsoleBlock.tsx b/src/components/MDX/ConsoleBlock.tsx index 50798e05f1..8b709fd029 100644 --- a/src/components/MDX/ConsoleBlock.tsx +++ b/src/components/MDX/ConsoleBlock.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Diagram.tsx b/src/components/MDX/Diagram.tsx index 649f48dff8..579c86ebec 100644 --- a/src/components/MDX/Diagram.tsx +++ b/src/components/MDX/Diagram.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/DiagramGroup.tsx b/src/components/MDX/DiagramGroup.tsx index 6c5130a3dc..8e3bf46c3f 100644 --- a/src/components/MDX/DiagramGroup.tsx +++ b/src/components/MDX/DiagramGroup.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/ErrorDecoder.tsx b/src/components/MDX/ErrorDecoder.tsx index a9b7455df9..423790198b 100644 --- a/src/components/MDX/ErrorDecoder.tsx +++ b/src/components/MDX/ErrorDecoder.tsx @@ -1,3 +1,10 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + import {useEffect, useState} from 'react'; import {useErrorDecoderParams} from '../ErrorDecoderContext'; import cn from 'classnames'; diff --git a/src/components/MDX/ExpandableCallout.tsx b/src/components/MDX/ExpandableCallout.tsx index 06ae75de40..719a5cc789 100644 --- a/src/components/MDX/ExpandableCallout.tsx +++ b/src/components/MDX/ExpandableCallout.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -17,6 +24,7 @@ type CalloutVariants = | 'wip' | 'canary' | 'experimental' + | 'rc' | 'major' | 'rsc'; @@ -43,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/ExpandableExample.tsx b/src/components/MDX/ExpandableExample.tsx index 8bd99be0b2..2d79bc5b70 100644 --- a/src/components/MDX/ExpandableExample.tsx +++ b/src/components/MDX/ExpandableExample.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Heading.tsx b/src/components/MDX/Heading.tsx index bffa9f3a28..d0d49af776 100644 --- a/src/components/MDX/Heading.tsx +++ b/src/components/MDX/Heading.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/InlineCode.tsx b/src/components/MDX/InlineCode.tsx index 5759a7c0ae..17e4683b99 100644 --- a/src/components/MDX/InlineCode.tsx +++ b/src/components/MDX/InlineCode.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Intro.tsx b/src/components/MDX/Intro.tsx index 0522df678c..b0bee624d5 100644 --- a/src/components/MDX/Intro.tsx +++ b/src/components/MDX/Intro.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/LanguagesContext.tsx b/src/components/MDX/LanguagesContext.tsx index 776a11c0d9..cd9f888167 100644 --- a/src/components/MDX/LanguagesContext.tsx +++ b/src/components/MDX/LanguagesContext.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Link.tsx b/src/components/MDX/Link.tsx index 7bf041e565..8a47c401f2 100644 --- a/src/components/MDX/Link.tsx +++ b/src/components/MDX/Link.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/MDXComponents.tsx b/src/components/MDX/MDXComponents.tsx index 7a50344a4b..1c76dffd15 100644 --- a/src/components/MDX/MDXComponents.tsx +++ b/src/components/MDX/MDXComponents.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -37,6 +44,7 @@ import {finishedTranslations} from 'utils/finishedTranslations'; import ErrorDecoder from './ErrorDecoder'; import {IconCanary} from '../Icon/IconCanary'; +import {IconExperimental} from 'components/Icon/IconExperimental'; function CodeStep({children, step}: {children: any; step: number}) { return ( @@ -98,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> ); @@ -130,7 +142,7 @@ const ExperimentalBadge = ({title}: {title: string}) => ( className={ 'text-base font-display px-1 py-0.5 font-bold bg-gray-10 dark:bg-gray-60 text-gray-60 dark:text-gray-10 rounded' }> - <IconCanary + <IconExperimental size="s" className={'inline me-1 mb-0.5 text-sm text-gray-60 dark:text-gray-10'} /> @@ -525,6 +537,7 @@ export const MDXComponents = { Math, MathI, Note, + RC, Canary, Experimental, ExperimentalBadge, diff --git a/src/components/MDX/PackageImport.tsx b/src/components/MDX/PackageImport.tsx index 5e2da820e5..222353ff57 100644 --- a/src/components/MDX/PackageImport.tsx +++ b/src/components/MDX/PackageImport.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Recap.tsx b/src/components/MDX/Recap.tsx index 97e4ca0fb8..3b81e36b60 100644 --- a/src/components/MDX/Recap.tsx +++ b/src/components/MDX/Recap.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/ClearButton.tsx b/src/components/MDX/Sandpack/ClearButton.tsx new file mode 100644 index 0000000000..be7451ab3f --- /dev/null +++ b/src/components/MDX/Sandpack/ClearButton.tsx @@ -0,0 +1,29 @@ +/** + * 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 * as React from 'react'; +import {IconClose} from '../../Icon/IconClose'; +export interface ClearButtonProps { + onClear: () => void; +} + +export function ClearButton({onClear}: ClearButtonProps) { + return ( + <button + className="text-sm text-primary dark:text-primary-dark inline-flex items-center hover:text-link duration-100 ease-in transition mx-1" + onClick={onClear} + title="Clear all edits and reload sandbox" + type="button"> + <IconClose className="inline mx-1 relative" /> + <span className="hidden md:block">Clear</span> + </button> + ); +} diff --git a/src/components/MDX/Sandpack/Console.tsx b/src/components/MDX/Sandpack/Console.tsx index 355ef2450b..3838447558 100644 --- a/src/components/MDX/Sandpack/Console.tsx +++ b/src/components/MDX/Sandpack/Console.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/CustomPreset.tsx b/src/components/MDX/Sandpack/CustomPreset.tsx index 5a0a4123a2..872b957899 100644 --- a/src/components/MDX/Sandpack/CustomPreset.tsx +++ b/src/components/MDX/Sandpack/CustomPreset.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/DownloadButton.tsx b/src/components/MDX/Sandpack/DownloadButton.tsx index b3ebf8daea..5df59afcde 100644 --- a/src/components/MDX/Sandpack/DownloadButton.tsx +++ b/src/components/MDX/Sandpack/DownloadButton.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/ErrorMessage.tsx b/src/components/MDX/Sandpack/ErrorMessage.tsx index 7c67ee4617..3dbeb113b7 100644 --- a/src/components/MDX/Sandpack/ErrorMessage.tsx +++ b/src/components/MDX/Sandpack/ErrorMessage.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/LoadingOverlay.tsx b/src/components/MDX/Sandpack/LoadingOverlay.tsx index c8d172b6ec..9f6877224a 100644 --- a/src/components/MDX/Sandpack/LoadingOverlay.tsx +++ b/src/components/MDX/Sandpack/LoadingOverlay.tsx @@ -1,3 +1,10 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + import {useState} from 'react'; import { diff --git a/src/components/MDX/Sandpack/NavigationBar.tsx b/src/components/MDX/Sandpack/NavigationBar.tsx index bf2c3186c3..3fe743a2d2 100644 --- a/src/components/MDX/Sandpack/NavigationBar.tsx +++ b/src/components/MDX/Sandpack/NavigationBar.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -17,7 +24,8 @@ import { useSandpackNavigation, } from '@codesandbox/sandpack-react/unstyled'; import {OpenInCodeSandboxButton} from './OpenInCodeSandboxButton'; -import {ResetButton} from './ResetButton'; +import {ReloadButton} from './ReloadButton'; +import {ClearButton} from './ClearButton'; import {DownloadButton} from './DownloadButton'; import {IconChevron} from '../../Icon/IconChevron'; import {Listbox} from '@headlessui/react'; @@ -95,7 +103,7 @@ export function NavigationBar({providedFiles}: {providedFiles: Array<string>}) { // Note: in a real useEvent, onContainerResize would be omitted. }, [isMultiFile, onContainerResize]); - const handleReset = () => { + const handleClear = () => { /** * resetAllFiles must come first, otherwise * the previous content will appear for a second @@ -103,13 +111,13 @@ export function NavigationBar({providedFiles}: {providedFiles: Array<string>}) { * * Plus, it should only prompt if there's any file changes */ - if ( - sandpack.editorState === 'dirty' && - confirm('Reset all your edits too?') - ) { + if (sandpack.editorState === 'dirty' && confirm('Clear all your edits?')) { sandpack.resetAllFiles(); } + refresh(); + }; + const handleReload = () => { refresh(); }; @@ -188,7 +196,8 @@ export function NavigationBar({providedFiles}: {providedFiles: Array<string>}) { className="px-3 flex items-center justify-end text-start" translate="yes"> <DownloadButton providedFiles={providedFiles} /> - <ResetButton onReset={handleReset} /> + <ReloadButton onReload={handleReload} /> + <ClearButton onClear={handleClear} /> <OpenInCodeSandboxButton /> {activeFile.endsWith('.tsx') && ( <OpenInTypeScriptPlaygroundButton diff --git a/src/components/MDX/Sandpack/OpenInCodeSandboxButton.tsx b/src/components/MDX/Sandpack/OpenInCodeSandboxButton.tsx index d0d34f4baa..0ee0a28151 100644 --- a/src/components/MDX/Sandpack/OpenInCodeSandboxButton.tsx +++ b/src/components/MDX/Sandpack/OpenInCodeSandboxButton.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/OpenInTypeScriptPlayground.tsx b/src/components/MDX/Sandpack/OpenInTypeScriptPlayground.tsx index 7284912e34..ca0286530e 100644 --- a/src/components/MDX/Sandpack/OpenInTypeScriptPlayground.tsx +++ b/src/components/MDX/Sandpack/OpenInTypeScriptPlayground.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/Preview.tsx b/src/components/MDX/Sandpack/Preview.tsx index e4fe0afe44..ead9341b6e 100644 --- a/src/components/MDX/Sandpack/Preview.tsx +++ b/src/components/MDX/Sandpack/Preview.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/ReloadButton.tsx b/src/components/MDX/Sandpack/ReloadButton.tsx new file mode 100644 index 0000000000..71a25ea475 --- /dev/null +++ b/src/components/MDX/Sandpack/ReloadButton.tsx @@ -0,0 +1,29 @@ +/** + * 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 * as React from 'react'; +import {IconRestart} from '../../Icon/IconRestart'; +export interface ReloadButtonProps { + onReload: () => void; +} + +export function ReloadButton({onReload}: ReloadButtonProps) { + return ( + <button + className="text-sm text-primary dark:text-primary-dark inline-flex items-center hover:text-link duration-100 ease-in transition mx-1" + onClick={onReload} + title="Keep your edits and reload sandbox" + type="button"> + <IconRestart className="inline mx-1 relative" /> + <span className="hidden md:block">Reload</span> + </button> + ); +} diff --git a/src/components/MDX/Sandpack/ResetButton.tsx b/src/components/MDX/Sandpack/ResetButton.tsx deleted file mode 100644 index 0d1e22c806..0000000000 --- a/src/components/MDX/Sandpack/ResetButton.tsx +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) Facebook, Inc. and its affiliates. - */ - -import * as React from 'react'; -import {IconRestart} from '../../Icon/IconRestart'; -export interface ResetButtonProps { - onReset: () => void; -} - -export function ResetButton({onReset}: ResetButtonProps) { - return ( - <button - className="text-sm text-primary dark:text-primary-dark inline-flex items-center hover:text-link duration-100 ease-in transition mx-1" - onClick={onReset} - title="Reset Sandbox" - type="button"> - <IconRestart className="inline mx-1 relative" /> Reset - </button> - ); -} diff --git a/src/components/MDX/Sandpack/SandpackRoot.tsx b/src/components/MDX/Sandpack/SandpackRoot.tsx index 67f40d0b3b..48d8daee50 100644 --- a/src/components/MDX/Sandpack/SandpackRoot.tsx +++ b/src/components/MDX/Sandpack/SandpackRoot.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/Themes.tsx b/src/components/MDX/Sandpack/Themes.tsx index 3923470ca9..8aa34dc954 100644 --- a/src/components/MDX/Sandpack/Themes.tsx +++ b/src/components/MDX/Sandpack/Themes.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/createFileMap.ts b/src/components/MDX/Sandpack/createFileMap.ts index 193b07be82..049face93e 100644 --- a/src/components/MDX/Sandpack/createFileMap.ts +++ b/src/components/MDX/Sandpack/createFileMap.ts @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -9,6 +16,66 @@ export const AppJSPath = `/src/App.js`; export const StylesCSSPath = `/src/styles.css`; export const SUPPORTED_FILES = [AppJSPath, StylesCSSPath]; +/** + * Tokenize meta attributes while ignoring brace-wrapped metadata (e.g. {expectedErrors: …}). + */ +function splitMeta(meta: string): string[] { + const tokens: string[] = []; + let current = ''; + let depth = 0; + const trimmed = meta.trim(); + + for (let ii = 0; ii < trimmed.length; ii++) { + const char = trimmed[ii]; + + if (char === '{') { + if (depth === 0 && current) { + tokens.push(current); + current = ''; + } + depth += 1; + continue; + } + + if (char === '}') { + if (depth > 0) { + depth -= 1; + } + if (depth === 0) { + current = ''; + } + if (depth < 0) { + throw new Error(`Unexpected closing brace in meta: ${meta}`); + } + continue; + } + + if (depth > 0) { + continue; + } + + if (/\s/.test(char)) { + if (current) { + tokens.push(current); + current = ''; + } + continue; + } + + current += char; + } + + if (current) { + tokens.push(current); + } + + if (depth !== 0) { + throw new Error(`Unclosed brace in meta: ${meta}`); + } + + return tokens; +} + export const createFileMap = (codeSnippets: any) => { return codeSnippets.reduce( (result: Record<string, SandpackFile>, codeSnippet: React.ReactElement) => { @@ -30,12 +97,17 @@ export const createFileMap = (codeSnippets: any) => { let fileActive = false; // if the file tab is shown by default if (props.meta) { - const [name, ...params] = props.meta.split(' '); - filePath = '/' + name; - if (params.includes('hidden')) { + const tokens = splitMeta(props.meta); + const name = tokens.find( + (token) => token.includes('/') || token.includes('.') + ); + if (name) { + filePath = name.startsWith('/') ? name : `/${name}`; + } + if (tokens.includes('hidden')) { fileHidden = true; } - if (params.includes('active')) { + if (tokens.includes('active')) { fileActive = true; } } else { @@ -50,6 +122,18 @@ export const createFileMap = (codeSnippets: any) => { } } + if (!filePath) { + if (props.className === 'language-js') { + filePath = AppJSPath; + } else if (props.className === 'language-css') { + filePath = StylesCSSPath; + } else { + throw new Error( + `Code block is missing a filename: ${props.children}` + ); + } + } + if (result[filePath]) { throw new Error( `File ${filePath} was defined multiple times. Each file snippet should have a unique path name` diff --git a/src/components/MDX/Sandpack/index.tsx b/src/components/MDX/Sandpack/index.tsx index 6755ba8de6..08e7dd6f0b 100644 --- a/src/components/MDX/Sandpack/index.tsx +++ b/src/components/MDX/Sandpack/index.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/Sandpack/runESLint.tsx b/src/components/MDX/Sandpack/runESLint.tsx index 5fea2f1100..667b22d7eb 100644 --- a/src/components/MDX/Sandpack/runESLint.tsx +++ b/src/components/MDX/Sandpack/runESLint.tsx @@ -1,3 +1,10 @@ +/** + * 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. + */ + // @ts-nocheck import {Linter} from 'eslint/lib/linter/linter'; @@ -14,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 dd6fd12bda..fa8c9e4865 100644 --- a/src/components/MDX/Sandpack/template.ts +++ b/src/components/MDX/Sandpack/template.ts @@ -1,3 +1,10 @@ +/** + * 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. + */ + export const template = { '/src/index.js': { hidden: true, @@ -28,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/Sandpack/useSandpackLint.tsx b/src/components/MDX/Sandpack/useSandpackLint.tsx index ec05fbe0d0..479b53ee0d 100644 --- a/src/components/MDX/Sandpack/useSandpackLint.tsx +++ b/src/components/MDX/Sandpack/useSandpackLint.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/SandpackWithHTMLOutput.tsx b/src/components/MDX/SandpackWithHTMLOutput.tsx index 51ce28dc14..51d06beaf1 100644 --- a/src/components/MDX/SandpackWithHTMLOutput.tsx +++ b/src/components/MDX/SandpackWithHTMLOutput.tsx @@ -1,3 +1,10 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + import {Children, memo} from 'react'; import InlineCode from './InlineCode'; import Sandpack from './Sandpack'; @@ -49,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/SimpleCallout.tsx b/src/components/MDX/SimpleCallout.tsx index ae259bcf57..0e124baa74 100644 --- a/src/components/MDX/SimpleCallout.tsx +++ b/src/components/MDX/SimpleCallout.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/TeamMember.tsx b/src/components/MDX/TeamMember.tsx index 444ce00290..d16d5bf64a 100644 --- a/src/components/MDX/TeamMember.tsx +++ b/src/components/MDX/TeamMember.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/TerminalBlock.tsx b/src/components/MDX/TerminalBlock.tsx index 2666d3c08a..ccfc7e79ec 100644 --- a/src/components/MDX/TerminalBlock.tsx +++ b/src/components/MDX/TerminalBlock.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -72,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/MDX/TocContext.tsx b/src/components/MDX/TocContext.tsx index 8aeead370e..924e6e09ee 100644 --- a/src/components/MDX/TocContext.tsx +++ b/src/components/MDX/TocContext.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/MDX/YouWillLearnCard.tsx b/src/components/MDX/YouWillLearnCard.tsx index 4bb7d7c737..03494f52d0 100644 --- a/src/components/MDX/YouWillLearnCard.tsx +++ b/src/components/MDX/YouWillLearnCard.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/PageHeading.tsx b/src/components/PageHeading.tsx index c438a8b082..980f15007d 100644 --- a/src/components/PageHeading.tsx +++ b/src/components/PageHeading.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ @@ -12,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; @@ -39,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=" - Fitur ini tersedia di rilis Eksperimental terbaru React" diff --git a/src/components/Search.tsx b/src/components/Search.tsx index c7401487b7..24b066d70f 100644 --- a/src/components/Search.tsx +++ b/src/components/Search.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/Seo.tsx b/src/components/Seo.tsx index b8a8394b61..9060410202 100644 --- a/src/components/Seo.tsx +++ b/src/components/Seo.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ diff --git a/src/components/SocialBanner.tsx b/src/components/SocialBanner.tsx index cd34ba5409..bf6db15319 100644 --- a/src/components/SocialBanner.tsx +++ b/src/components/SocialBanner.tsx @@ -1,6 +1,8 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ import {useRef, useEffect} from 'react'; diff --git a/src/components/Tag.tsx b/src/components/Tag.tsx index 2e63a81f6b..9a69d179c3 100644 --- a/src/components/Tag.tsx +++ b/src/components/Tag.tsx @@ -1,3 +1,10 @@ +/** + * 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. */ 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 1bc78149d3..df1fd085dd 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 ffe761624b..c3ab47fad2 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*/} @@ -107,7 +99,7 @@ Activity is still under research and our remaining work is to finalize the primi In addition to this update, our team has presented at conferences and made appearances on podcasts to speak more on our work and answer questions. -- [Sathya Gunasekaran](/community/team#sathya-gunasekaran) spoke about the React Compiler at the [React India](https://www.youtube.com/watch?v=kjOacmVsLSE) conference +- [Sathya Gunasekaran](https://github.com/gsathya) spoke about the React Compiler at the [React India](https://www.youtube.com/watch?v=kjOacmVsLSE) conference - [Dan Abramov](/community/team#dan-abramov) gave a talk at [RemixConf](https://www.youtube.com/watch?v=zMf_xeGPn6s) titled β€œReact from Another Dimension” which explores an alternative history of how React Server Components and Actions could have been created 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 7cb7d42ee9..e224640103 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 58e6b24aa4..750c0f3b8e 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> @@ -72,11 +72,11 @@ Or, if you're using Yarn: yarn add -D eslint-plugin-react-compiler@beta </TerminalBlock> -After installation you can enable the linter by [adding it to your ESLint config](/learn/react-compiler#installing-eslint-plugin-react-compiler). Using the linter helps identify Rules of React breakages, making it easier to adopt the compiler when it's fully released. +After installation you can enable the linter by [adding it to your ESLint config](/learn/react-compiler/installation#eslint-integration). Using the linter helps identify Rules of React breakages, making it easier to adopt the compiler when it's fully released. ## Backwards Compatibility {/*backwards-compatibility*/} -React Compiler produces code that depends on runtime APIs added in React 19, but we've since added support for the compiler to also work with React 17 and 18. If you are not on React 19 yet, in the Beta release you can now try out 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](/learn/react-compiler#using-react-compiler-with-react-17-or-18). +React Compiler produces code that depends on runtime APIs added in React 19, but we've since added support for the compiler to also work with React 17 and 18. If you are not on React 19 yet, in the Beta release you can now try out 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/configuration#react-17-18). ## Using React Compiler in libraries {/*using-react-compiler-in-libraries*/} @@ -86,7 +86,7 @@ React Compiler can also be used to compile libraries. Because React Compiler nee Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum `target` and add `react-compiler-runtime` as a direct dependency. The runtime package will use the correct implementation of APIs depending on the application's version, and polyfill the missing APIs if necessary. -[You can find more docs on this here.](/learn/react-compiler#using-the-compiler-on-libraries) +[You can find more docs on this here.](/reference/react-compiler/compiling-libraries) ## Opening up React Compiler Working Group to everyone {/*opening-up-react-compiler-working-group-to-everyone*/} diff --git a/src/content/blog/2024/12/05/react-19.md b/src/content/blog/2024/12/05/react-19.md index 65bf42757a..4e9aad8e82 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 9ced6231c3..6f3e95d811 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 ecbbb87471..0000000000 --- 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@6.0.0-rc.1`. 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@6.0.0-rc.1`} -</TerminalBlock> - -pnpm -<TerminalBlock> -{`pnpm add --save-dev eslint-plugin-react-hooks@6.0.0-rc.1`} -</TerminalBlock> - -yarn -<TerminalBlock> -{`yarn add --dev eslint-plugin-react-hooks@6.0.0-rc.1`} -</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 e4bb25a4aa..9b6095f8b2 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> @@ -2495,7 +2494,7 @@ For example, we can slow down the `default` cross fade animation: </ViewTransition> ``` -And define `slow-fade` in CSS using [view transition classes](/reference/react/ViewTransition#view-transition-classes): +And define `slow-fade` in CSS using [view transition classes](/reference/react/ViewTransition#view-transition-class): ```css ::view-transition-old(.slow-fade) { @@ -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"; @@ -2521,7 +2520,7 @@ export default function App() { const { url } = useRouter(); // Define a default animation of .slow-fade. - // See animations.css for the animation definiton. + // See animations.css for the animation definition. return ( <ViewTransition default="slow-fade"> {url === '/' ? <Home /> : <Details />} @@ -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": { @@ -11465,6 +11464,14 @@ _For more background on how we built View Transitions, see: [#31975](https://git ## Activity {/*activity*/} +<Note> + +**`<Activity />` is now available in React’s Canary channel.** + +[Learn more about React’s release channels here.](/community/versioning-policy#all-release-channels) + +</Note> + In [past](/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022#offscreen) [updates](/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024#offscreen-renamed-to-activity), we shared that we were researching an API to allow components to be visually hidden and deprioritized, preserving UI state with reduced performance costs relative to unmounting or hiding with CSS. We're now ready to share the API and how it works, so you can start testing it in experimental React versions. @@ -11500,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 />} @@ -11517,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'}> @@ -11536,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> @@ -11555,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"; @@ -11630,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 ( @@ -11643,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> @@ -11657,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} /> @@ -11825,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(); @@ -11889,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"; @@ -12040,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(); @@ -12068,7 +12075,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -12833,8 +12840,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -12873,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 */} @@ -12897,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. @@ -12968,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 ( @@ -12981,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> @@ -12995,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} /> @@ -13163,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(); @@ -13227,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"; @@ -13378,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(); @@ -13406,7 +13413,7 @@ export function Router({ children }) { }, }); } - + useEffect(() => { function handlePopState() { // This should not animate because restoration has to be synchronous. @@ -14171,8 +14178,8 @@ root.render( ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "canary", + "react-dom": "canary", "react-scripts": "latest" }, "scripts": { @@ -14212,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*/} @@ -14251,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*/} @@ -14292,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). @@ -14325,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: @@ -14349,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 0000000000..51c30f70a2 --- /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 0000000000..a9b922dbc9 --- /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 0000000000..080f3586ea --- /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 0000000000..8476b02aad --- /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 0000000000..310a841161 --- /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 0000000000..6845e2f2f4 --- /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 a7a8976341..30c4a3ffe3 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 a97f3d5b42..9cd83cffc6 100644 --- a/src/content/community/conferences.md +++ b/src/content/community/conferences.md @@ -10,36 +10,6 @@ Do you know of a local React.js conference? Add it here! (Please keep the list c ## Upcoming Conferences {/*upcoming-conferences*/} -### CityJS London 2025 {/*cityjs-london*/} -April 23 - 25, 2025. In-person in London, UK - -[Website](https://london.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) - -### App.js Conf 2025 {/*appjs-conf-2025*/} -May 28 - 30, 2025. In-person in KrakΓ³w, Poland + remote - -[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf) - -### CityJS Athens 2025 {/*cityjs-athens*/} -May 27 - 31, 2025. In-person in Athens, Greece - -[Website](https://athens.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) - -### React Norway 2025 {/*react-norway-2025*/} -June 13, 2025. In-person in Oslo, Norway + remote (virtual event) - -[Website](https://reactnorway.com/) - [Twitter](https://x.com/ReactNorway) - -### React Summit 2025 {/*react-summit-2025*/} -June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event) - -[Website](https://reactsummit.com/) - [Twitter](https://x.com/reactsummit) - -### React Nexus 2025 {/*react-nexus-2025*/} -July 03 - 05, 2025. In-person in Bangalore, India - -[Website](https://reactnexus.com/) - [Twitter](https://x.com/ReactNexus) - [Bluesky](https://bsky.app/profile/reactnexus.com) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) - ### React Universe Conf 2025 {/*react-universe-conf-2025*/} September 2-4, 2025. WrocΕ‚aw, Poland. @@ -50,6 +20,11 @@ October 2-4, 2025. Alicante, Spain. [Website](https://reactalicante.es/) - [Twitter](https://x.com/ReactAlicante) - [Bluesky](https://bsky.app/profile/reactalicante.es) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w) +### RenderCon Kenya 2025 {/*rendercon-kenya-2025*/} +October 04, 2025. Nairobi, Kenya + +[Website](https://rendercon.org/) - [Twitter](https://twitter.com/renderconke) - [LinkedIn](https://www.linkedin.com/company/renderconke/) - [YouTube](https://www.youtube.com/channel/UC0bCcG8gHUL4njDOpQGcMIA) + ### React Conf 2025 {/*react-conf-2025*/} October 7-8, 2025. Henderson, Nevada, USA and free livestream @@ -70,13 +45,66 @@ 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*/} + +### React Nexus 2025 {/*react-nexus-2025*/} +July 03 - 05, 2025. In-person in Bangalore, India + +[Website](https://reactnexus.com/) - [Twitter](https://x.com/ReactNexus) - [Bluesky](https://bsky.app/profile/reactnexus.com) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) + +### React Summit 2025 {/*react-summit-2025*/} +June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event) + +[Website](https://reactsummit.com/) - [Twitter](https://x.com/reactsummit) + +### React Norway 2025 {/*react-norway-2025*/} +June 13, 2025. In-person in Oslo, Norway + remote (virtual event) + +[Website](https://reactnorway.com/) - [Twitter](https://x.com/ReactNorway) + +### CityJS Athens 2025 {/*cityjs-athens*/} +May 27 - 31, 2025. In-person in Athens, Greece + +[Website](https://athens.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) + +### App.js Conf 2025 {/*appjs-conf-2025*/} +May 28 - 30, 2025. In-person in KrakΓ³w, Poland + remote + +[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf) + +### CityJS London 2025 {/*cityjs-london*/} +April 23 - 25, 2025. In-person in London, UK + +[Website](https://london.cityjsconf.org/) - [Twitter](https://x.com/cityjsconf) - [Bluesky](https://bsky.app/profile/cityjsconf.bsky.social) + ### React Paris 2025 {/*react-paris-2025*/} March 20 - 21, 2025. In-person in Paris, France (hybrid event) -[Website](https://react.paris/) - [Twitter](https://x.com/BeJS_) +[Website](https://react.paris/) - [Twitter](https://x.com/BeJS_) - [YouTube](https://www.youtube.com/playlist?list=PL53Z0yyYnpWitP8Zv01TSEQmKLvuRh_Dj) ### React Native Connection 2025 {/*react-native-connection-2025*/} April 3 (Reanimated Training) + April 4 (Conference), 2025. Paris, France. diff --git a/src/content/community/meetups.md b/src/content/community/meetups.md index b4da5cdffb..78d48093aa 100644 --- a/src/content/community/meetups.md +++ b/src/content/community/meetups.md @@ -58,6 +58,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Manchester](https://www.meetup.com/Manchester-React-User-Group/) * [React.JS Girls London](https://www.meetup.com/ReactJS-Girls-London/) * [React Advanced London](https://guild.host/react-advanced-london) +* [React Native Liverpool](https://www.meetup.com/react-native-liverpool/) * [React Native London](https://guild.host/RNLDN) ## Finland {/*finland*/} @@ -138,7 +139,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Lisbon](https://www.meetup.com/JavaScript-Lisbon/) ## Scotland (UK) {/*scotland-uk*/} -* [Edinburgh](https://www.meetup.com/React-Scotland/) +* [Edinburgh](https://www.meetup.com/react-edinburgh/) ## Spain {/*spain*/} * [Barcelona](https://www.meetup.com/ReactJS-Barcelona/) diff --git a/src/content/community/videos.md b/src/content/community/videos.md index 3fad95786e..1fca603074 100644 --- a/src/content/community/videos.md +++ b/src/content/community/videos.md @@ -8,6 +8,75 @@ Videos dedicated to the discussion of React and the React ecosystem. </Intro> +## React Conf 2024 {/*react-conf-2024*/} + +At React Conf 2024, Meta CTO [Andrew "Boz" Bosworth](https://www.threads.net/@boztank) shared a welcome message to kick off the conference: + +<YouTubeIframe src="https://www.youtube.com/embed/T8TZQ6k4SLE?t=975s" title="Boz and Seth Intro" /> + +### React 19 Keynote {/*react-19-keynote*/} + +In the Day 1 keynote, we shared vision for React starting with React 19 and the React Compiler. Watch the full keynote from [Joe Savona](https://twitter.com/en_JS), [Lauren Tan](https://twitter.com/potetotes), [Andrew Clark](https://twitter.com/acdlite), [Josh Story](https://twitter.com/joshcstory), [Sathya Gunasekaran](https://twitter.com/_gsathya), and [Mofei Zhang](https://twitter.com/zmofei): + + +<YouTubeIframe src="https://www.youtube.com/embed/lyEKhv8-3n0" title="YouTube video player" /> + +### React Unpacked: A Roadmap to React 19 {/*react-unpacked-a-roadmap-to-react-19*/} + +React 19 introduced new features including Actions, `use()`, `useOptimistic` and more. For a deep dive on using new features in React 19, see [Sam Selikoff's](https://twitter.com/samselikoff) talk: + +<YouTubeIframe src="https://www.youtube.com/embed/R0B2HsSM78s" title="React Unpacked: A Roadmap to React 19" /> + +### What's New in React 19 {/*whats-new-in-react-19*/} + +[Lydia Hallie](https://twitter.com/lydiahallie) gave a visual deep dive of React 19's new features: + +<YouTubeIframe src="https://www.youtube.com/embed/AJOGzVygGcY" title="What's New in React 19" /> + +### React 19 Deep Dive: Coordinating HTML {/*react-19-deep-dive-coordinating-html*/} + +[Josh Story](https://twitter.com/joshcstory) provided a deep dive on the document and resource streaming APIs in React 19: + +<YouTubeIframe src="https://www.youtube.com/embed/IBBN-s77YSI" title="React 19 Deep Dive: Coordinating HTML" /> + +### React for Two Computers {/*react-for-two-computers*/} + +[Dan Abramov](https://bsky.app/profile/danabra.mov) imagined an alternate history where React started server-first: + +<YouTubeIframe src="https://www.youtube.com/embed/ozI4V_29fj4" title="React for Two Computers" /> + +### Forget About Memo {/*forget-about-memo*/} + +[Lauren Tan](https://twitter.com/potetotes) gave a talk on using the React Compiler in practice: + +<YouTubeIframe src="https://www.youtube.com/embed/lvhPq5chokM" title="Forget About Memo" /> + +### React Compiler Deep Dive {/*react-compiler-deep-dive*/} + +[Sathya Gunasekaran](https://twitter.com/_gsathya) and [Mofei Zhang](https://twitter.com/zmofei) provided a deep dive on how the React Compiler works: + +<YouTubeIframe src="https://www.youtube.com/embed/uA_PVyZP7AI" title="React Compiler Deep Dive" /> + +### And more... {/*and-more-2024*/} + +**We also heard talks from the community on Server Components:** +* [Enhancing Forms with React Server Components](https://www.youtube.com/embed/0ckOUBiuxVY&t=25280s) by [Aurora Walberg Scharff](https://twitter.com/aurorascharff) +* [And Now You Understand React Server Components](https://www.youtube.com/embed/pOo7x8OiAec) by [Kent C. Dodds](https://twitter.com/kentcdodds) +* [Real-time Server Components](https://www.youtube.com/embed/6sMANTHWtLM) by [Sunil Pai](https://twitter.com/threepointone) + +**Talks from React frameworks using new features:** + +* [Vanilla React](https://www.youtube.com/embed/ZcwA0xt8FlQ) by [Ryan Florence](https://twitter.com/ryanflorence) +* [React Rhythm & Blues](https://www.youtube.com/embed/rs9X5MjvC4s) by [Lee Robinson](https://twitter.com/leeerob) +* [RedwoodJS, now with React Server Components](https://www.youtube.com/embed/sjyY4MTECUU) by [Amy Dutton](https://twitter.com/selfteachme) +* [Introducing Universal React Server Components in Expo Router](https://www.youtube.com/embed/djhEgxQf3Kw) by [Evan Bacon](https://twitter.com/Baconbrix) + +**And Q&As with the React and React Native teams:** +- [React Q&A](https://www.youtube.com/embed/T8TZQ6k4SLE&t=27518s) hosted by [Michael Chan](https://twitter.com/chantastic) +- [React Native Q&A](https://www.youtube.com/embed/0ckOUBiuxVY&t=27935s) hosted by [Jamon Holmgren](https://twitter.com/jamonholmgren) + +You can watch all of the talks at React Conf 2024 at [conf2024.react.dev](https://conf2024.react.dev/talks). + ## React Conf 2021 {/*react-conf-2021*/} ### React 18 Keynote {/*react-18-keynote*/} @@ -16,13 +85,13 @@ In the keynote, we shared our vision for the future of React starting with React Watch the full keynote from [Andrew Clark](https://twitter.com/acdlite), [Juan Tejada](https://twitter.com/_jstejada), [Lauren Tan](https://twitter.com/potetotes), and [Rick Hanlon](https://twitter.com/rickhanlonii) here: -<YouTubeIframe src="https://www.youtube.com/embed/FZ0cG47msEk" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/FZ0cG47msEk" title="React 18 Keynote" /> ### React 18 for Application Developers {/*react-18-for-application-developers*/} For a demo of upgrading to React 18, see [Shruti Kapoor](https://twitter.com/shrutikapoor08)’s talk here: -<YouTubeIframe src="https://www.youtube.com/embed/ytudH8je5ko" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/ytudH8je5ko" title="React 18 for Application Developers" /> ### Streaming Server Rendering with Suspense {/*streaming-server-rendering-with-suspense*/} @@ -32,7 +101,7 @@ Streaming server rendering lets you generate HTML from React components on the s For a deep dive, see [Shaundai Person](https://twitter.com/shaundai)’s talk here: -<YouTubeIframe src="https://www.youtube.com/embed/pj5N-Khihgc" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/pj5N-Khihgc" title="Streaming Server Rendering with Suspense" /> ### The first React working group {/*the-first-react-working-group*/} @@ -40,7 +109,7 @@ For React 18, we created our first Working Group to collaborate with a panel of For an overview of this work, see [Aakansha' Doshi](https://twitter.com/aakansha1216)'s talk: -<YouTubeIframe src="https://www.youtube.com/embed/qn7gRClrC9U" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/qn7gRClrC9U" title="The first React working group" /> ### React Developer Tooling {/*react-developer-tooling*/} @@ -48,19 +117,19 @@ To support the new features in this release, we also announced the newly formed For more information and a demo of new DevTools features, see [Brian Vaughn](https://twitter.com/brian_d_vaughn)’s talk: -<YouTubeIframe src="https://www.youtube.com/embed/oxDfrke8rZg" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/oxDfrke8rZg" title="React Developer Tooling" /> ### React without memo {/*react-without-memo*/} Looking further into the future, [Xuan Huang (ι»„ηŽ„)](https://twitter.com/Huxpro) shared an update from our React Labs research into an auto-memoizing compiler. Check out this talk for more information and a demo of the compiler prototype: -<YouTubeIframe src="https://www.youtube.com/embed/lGEMwh32soc" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/lGEMwh32soc" title="React without memo" /> ### React docs keynote {/*react-docs-keynote*/} [Rachel Nabors](https://twitter.com/rachelnabors) kicked off a section of talks about learning and designing with React with a keynote about our investment in React's new docs ([now shipped as react.dev](/blog/2023/03/16/introducing-react-dev)): -<YouTubeIframe src="https://www.youtube.com/embed/mneDaMYOKP8" title="YouTube video player" /> +<YouTubeIframe src="https://www.youtube.com/embed/mneDaMYOKP8" title="React docs keynote" /> ### And more... {/*and-more*/} diff --git a/src/content/errors/index.md b/src/content/errors/index.md index 25746d25d8..d4fc3927a9 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 2627f6b6b5..e72c6477e4 100644 --- a/src/content/learn/add-react-to-an-existing-project.md +++ b/src/content/learn/add-react-to-an-existing-project.md @@ -20,11 +20,19 @@ Katakanlah Anda memiliki aplikasi web yang sudah ada di `example.com` yang dibua Inilah cara kami menyarankan untuk menyiapkannya: +<<<<<<< HEAD 1. **Buat bagian React dari aplikasi Anda** menggunakan salah satu [*framework* berbasis React](/learn/start-a-new-react-project). 2. **Tentukan `/some-app` sebagai *base path*** dalam konfigurasi *framework* Anda (begini caranya: [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. **Konfigurasi server Anda atau Proxy** sehingga semua permintaan di rute `/some-app/` ditangani oleh aplikasi React Anda. Ini memastikan bagian React dari aplikasi Anda bisa mendapatkan [keuntungan dari praktik terbaik](/learn/start-a-new-react-project#can-i-use-react-without-a-framework) yang dimasukkan ke dalam *framework* tersebut. +======= +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. + +This ensures the React part of your app can [benefit from the best practices](/learn/build-a-react-app-from-scratch#consider-using-a-framework) baked into those frameworks. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Banyak *framework* berbasis React bersifat *full-stack* dan membiarkan aplikasi React Anda memanfaatkan server. Namun, Anda dapat menggunakan pendekatan yang sama meskipun Anda tidak dapat atau tidak ingin menjalankan JavaScript di server. Dalam hal ini, sajikan HTML/CSS/JS ([`next export` output](https://nextjs.org/docs/advanced-features/static-html-export) untuk Next.js, *default* untuk Gatsby) di `/some-app/` sebagai gantinya. @@ -149,7 +157,11 @@ root.render(<NavigationBar />); Perhatikan bagaimana konten HTML asli dari `index.html` dipertahankan, tetapi komponen React `NavigationBar` Anda sekarang muncul di dalam `<nav id="navigation">` HTML Anda. Baca [dokumentasi penggunaan `createRoot`](/reference/react-dom/client/createRoot#rendering-a-page-partially-built-with-react) untuk mempelajari lebih lanjut tentang me-*render* komponen React di dalam halaman HTML yang ada. +<<<<<<< HEAD Saat Anda mengadopsi React dalam proyek yang sudah ada, umumnya dimulai dengan komponen interaktif kecil (seperti tombol), dan kemudian secara bertahap terus "bergerak ke atas" hingga akhirnya seluruh halaman Anda dibuat dengan React. Jika Anda sudah mencapai titik itu, kami sarankan untuk segera bermigrasi ke [React *framework*](/learn/start-a-new-react-project) untuk mendapatkan hasil maksimal dari 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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ## Menggunakan React Native di aplikasi seluler native yang sudah ada {/*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 82ffbcb960..e6f3d9244a 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 @@ Langkah pertama adalah menginstal alat bantu seperti `vite`, `parcel`, atau `rsb [Vite](https://vite.dev/) adalah alat pengembangan yang bertujuan untuk menyediakan pengalaman pengembangan yang lebih cepat dan ramping untuk proyek web modern. <TerminalBlock> -{`npm create vite@latest my-app -- --template react`} +npm create vite@latest my-app -- --template react-ts </TerminalBlock> Vite adalah alat pengembangan *opinionated* dan hadir dengan pengaturan bawaan yang masuk akal. Vite memiliki ekosistem plugin yang kaya untuk mendukung penyegaran cepat, JSX, Babel/SWC, dan fitur umum lainnya. Lihat [plugin React](https://vite.dev/plugins/#vitejs-plugin-react) atau [plugin React SWC](https://vite.dev/plugins/#vitejs-plugin-react-swc) dan [proyek contoh React SSR](https://vite.dev/guide/ssr.html#example-projects) Vite untuk memulai. @@ -46,7 +46,7 @@ Vite sudah digunakan sebagai alat pembangunan di salah satu [*framework* yang ka [Parcel](https://parceljs.org/) menggabungkan pengalaman pengembangan *out-of-the-box* yang hebat dengan arsitektur berskala yang dapat membawa proyek Anda dari baru saja dimulai hingga aplikasi produksi besar-besaran. <TerminalBlock> -{`npm install --save-dev parcel`} +npm install --save-dev parcel </TerminalBlock> Parcel mendukung *fast refresh*, JSX, TypeScript, Flow, dan *styling* secara langsung. Lihat [resep React Parcel](https://parceljs.org/recipes/react/#getting-started) untuk memulai. @@ -56,7 +56,7 @@ Parcel mendukung *fast refresh*, JSX, TypeScript, Flow, dan *styling* secara lan [Rsbuild](https://rsbuild.dev/) adalah alat pengembangan yang didukung Rspack yang menyediakan pengalaman pengembangan yang lancar untuk aplikasi React. Alat ini dilengkapi dengan pengaturan bawaan yang telah disesuaikan dengan cermat dan pengoptimalan kinerja yang siap digunakan. <TerminalBlock> -{`npx create-rsbuild --template react`} +npx create-rsbuild --template react </TerminalBlock> Rsbuild menyertakan dukungan bawaan untuk fitur React seperti *fast refresh*, JSX, TypeScript, dan *styling*. Lihat [panduan React Rsbuild](https://rsbuild.dev/guide/framework/react) untuk memulai. @@ -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) @@ -122,7 +122,11 @@ Untuk petunjuk pemisahan kode, lihat dokumen alat build Anda: ### Meningkatkan Performa Aplikasi {/*improving-application-performance*/} +<<<<<<< HEAD Karena alat *build* yang Anda pilih hanya mendukung aplikasi *single-page* (SPA), Anda perlu menerapkan [pola rendering](https://www.patterns.dev/vanilla/rendering-patterns) lain seperti *server-side rendering* (SSR), *static site generation* (SSG), dan/atau Komponen Server React (RSC). Meskipun Anda tidak memerlukan fitur-fitur ini pada awalnya, di masa mendatang mungkin ada beberapa jalur yang akan menguntungkan SSR, SSG, atau RSC. +======= +Since the build tool you select only supports single page apps (SPAs), you'll need to implement other [rendering patterns](https://www.patterns.dev/vanilla/rendering-patterns) like server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC). Even if you don't need these features at first, in the future there may be some routes that would benefit SSR, SSG or RSC. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 * **Aplikasi *single-page* (SPA)** memuat satu halaman HTML dan memperbarui halaman secara dinamis saat pengguna berinteraksi dengan aplikasi. SPA lebih mudah untuk memulai, tetapi waktu muat awal dapat lebih lambat. SPA adalah arsitektur default untuk sebagian besar alat build. diff --git a/src/content/learn/choosing-the-state-structure.md b/src/content/learn/choosing-the-state-structure.md index c85ccf958f..4785151e3f 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 a798a86f82..9e258f815a 100644 --- a/src/content/learn/creating-a-react-app.md +++ b/src/content/learn/creating-a-react-app.md @@ -63,8 +63,13 @@ Expo dikelola oleh [Expo (perusahaan)](https://expo.dev/about). Membangun aplika Ada beberapa framework baru yang sedang berkembang yang berupaya mewujudkan visi React *full stack* kami: +<<<<<<< HEAD - [TanStack Start (Beta)](https://tanstack.com/): TanStack Start adalah *framework* React *full-stack* yang ditenagai oleh TanStack Router. Ia menyediakan SSR di keseluruhan dokumen, *streaming*, fungsi *server*, *bundling*, dan lebih banyak lagi menggunakan perangkat seperti Nitro dan Vite. - [RedwoodJS](https://redwoodjs.com/): Redwood adalah *framework* React *full stack* dengan berbagai macam *packages* dan konfigurasi yang sudah terpasang secara bawaan yang memudahkan pembangunan aplikasi web *full-stack*. +======= +- [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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 <DeepDive> diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index 668b8a549b..b2673b7cde 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -474,7 +474,7 @@ Dengan hanya benar-benar menulis komponen Anda sebagai fungsi murni, Anda dapat <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [5]}} let guest = 0; function Cup() { diff --git a/src/content/learn/escape-hatches.md b/src/content/learn/escape-hatches.md index 4c90ebf1ee..714fc8e0ef 100644 --- a/src/content/learn/escape-hatches.md +++ b/src/content/learn/escape-hatches.md @@ -201,7 +201,7 @@ Ada dua kasus umum di mana Anda tidak memerlukan *Effects*: Sebagai contoh, Anda tidak perlu menggunakan *Effect* untuk menyesuaikan beberapa *state* berdasarkan *state* lainnya: -```js {5-9} +```js {expectedErrors: {'react-compiler': [8]}} {5-9} function Form() { const [firstName, setFirstName] = useState('Taylor'); const [lastName, setLastName] = useState('Swift'); @@ -312,6 +312,7 @@ Baca **[Siklus hidup *effects* yang reaktif](/learn/lifecycle-of-reactive-effect ## Memisahkan *events* dari *Effects* {/*separating-events-from-effects*/} +<<<<<<< HEAD <Wip> Bagian ini mendeskripsikan sebuah **eksperimen API yang belum dirilis** di versi stabil React. @@ -319,6 +320,9 @@ Bagian ini mendeskripsikan sebuah **eksperimen API yang belum dirilis** di versi </Wip> *Event handlers* hanya berjalan ulang ketika Anda melakukan interaksi yang sama lagi. Tidak seperti *event handlers*, *Effects* menyinkronkan ulang jika nilai apapun yang mereka baca, seperti *props* atau *state*, berbeda dari saat *render* terakhir. Kadang, Anda ingin campuran kedua perilaku tersebut: sebuah *Effect* yang berjalan ulang sebagai respon terhadap beberapa nilai tetapi tidak pada nilai lainnya. +======= +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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Semua kode di dalam *Effects* adalah *reactive.* *Effects* tersebut akan berjalan lagi jika beberapa nilai *reactive* yang dibacanya telah berubah karena *render* ulang. Misalkan, *Effect* ini akan menghubungkan kembali ke *chat* jika `roomId` atau `theme` telah berubah: @@ -455,8 +459,8 @@ Ini tidak ideal. Anda ingin menghubungkan kembali ke *chat* jika hanya `roomId` ```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 +475,7 @@ Ini tidak ideal. Anda ingin menghubungkan kembali ke *chat* jika hanya `roomId` ```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/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md index db36b552ea..96f2f89365 100644 --- a/src/content/learn/keeping-components-pure.md +++ b/src/content/learn/keeping-components-pure.md @@ -93,7 +93,7 @@ Ini contoh komponen yang tidak mengikuti aturan tersebut: <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [5]}} let guest = 0; function Cup() { @@ -380,7 +380,7 @@ Kode yang bermasalah ada di `Profile.js`. Pastikan Anda membaca seluruh kode ter <Sandpack> -```js src/Profile.js +```js {expectedErrors: {'react-compiler': [7]}} src/Profile.js import Panel from './Panel.js'; import { getImageUrl } from './utils.js'; @@ -602,7 +602,7 @@ export default function StoryTray({ stories }) { } ``` -```js src/App.js hidden +```js {expectedErrors: {'react-compiler': [16]}} src/App.js hidden import { useState, useEffect } from 'react'; import StoryTray from './StoryTray.js'; @@ -698,7 +698,7 @@ export default function StoryTray({ stories }) { } ``` -```js src/App.js hidden +```js {expectedErrors: {'react-compiler': [16]}} src/App.js hidden import { useState, useEffect } from 'react'; import StoryTray from './StoryTray.js'; @@ -790,7 +790,7 @@ export default function StoryTray({ stories }) { } ``` -```js src/App.js hidden +```js {expectedErrors: {'react-compiler': [16]}} src/App.js hidden import { useState, useEffect } from 'react'; import StoryTray from './StoryTray.js'; diff --git a/src/content/learn/lifecycle-of-reactive-effects.md b/src/content/learn/lifecycle-of-reactive-effects.md index 3dc9a75f02..72a2e77559 100644 --- a/src/content/learn/lifecycle-of-reactive-effects.md +++ b/src/content/learn/lifecycle-of-reactive-effects.md @@ -1131,7 +1131,7 @@ If you see a linter rule being suppressed, remove the suppression! That's where <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [16]}} import { useState, useEffect } from 'react'; export default function App() { @@ -1374,7 +1374,7 @@ export default function App() { } ``` -```js src/ChatRoom.js active +```js {expectedErrors: {'react-compiler': [8]}} src/ChatRoom.js active import { useState, useEffect } from 'react'; export default function ChatRoom({ roomId, createConnection }) { diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 66ed56751e..893da4124b 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -211,7 +211,11 @@ Ini dikarenakan **Hooks hanya dapat dipanggil di tingkat atas komponen Anda.** A Satu cara yang memungkinkan adalah mendapatkan *ref* tunggal dari elemen *parent*, lalu gunakan metode manipulasi DOM seperti [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) untuk "menemukan" masing-masing *child node*. Namun, hal ini beresiko kacau jika struktur DOM Anda berubah. +<<<<<<< HEAD Solusi lainnya adalah dengan **mengoper fungsi pada atribut `ref`.** hal ini dinamakan [`ref` callback.](/reference/react-dom/components/common#ref-callback) React akan memanggil *ref callback* Anda dengan *simpul DOM* saat menyiapkan *ref*, dan dengan `null` saat menghapusnya. hal ini memungkinkan anda mengatur *Array* Anda sendiri atau sebuah [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), dan mengakses *ref* dengan indeks atau sejenis ID. +======= +Another solution is to **pass a function to the `ref` attribute.** This is called a [`ref` callback.](/reference/react-dom/components/common#ref-callback) React will call your ref callback with the DOM node when it's time to set the ref, and call the cleanup function returned from the callback when it's time to clear it. This lets you maintain your own array or a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), and access any ref by its index or some kind of ID. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Contoh di bawah menunjukan bagaimana Anda dapat menggunakan pendekatan ini untuk menggulir simpul di dalam daftar yang panjang: @@ -247,13 +251,13 @@ export default function CatFriends() { <nav> <button onClick={() => scrollToCat(catList[0])}>Neo</button> <button onClick={() => scrollToCat(catList[5])}>Millie</button> - <button onClick={() => scrollToCat(catList[9])}>Bella</button> + <button onClick={() => scrollToCat(catList[8])}>Bella</button> </nav> <div> <ul> {catList.map((cat) => ( <li - key={cat} + key={cat.id} ref={(node) => { const map = getMap(); map.set(cat, node); @@ -263,7 +267,7 @@ export default function CatFriends() { }; }} > - <img src={cat} /> + <img src={cat.imageUrl} /> </li> ))} </ul> @@ -273,11 +277,22 @@ export default function CatFriends() { } function setupCatList() { - const catList = []; - for (let i = 0; i < 10; i++) { - catList.push("https://loremflickr.com/320/240/cat?lock=" + i); + const catCount = 10; + const catList = new Array(catCount) + for (let i = 0; i < catCount; i++) { + let imageUrl = ''; + if (i < 5) { + imageUrl = "https://placecats.com/neo/320/240"; + } else if (i < 8) { + imageUrl = "https://placecats.com/millie/320/240"; + } else { + imageUrl = "https://placecats.com/bella/320/240"; + } + catList[i] = { + id: i, + imageUrl, + }; } - return catList; } @@ -876,12 +891,30 @@ export default function CatFriends() { ); } -const catList = []; -for (let i = 0; i < 10; i++) { - catList.push({ +const catCount = 10; +const catList = new Array(catCount); +for (let i = 0; i < catCount; i++) { + const bucket = Math.floor(Math.random() * catCount) % 2; + let imageUrl = ''; + switch (bucket) { + case 0: { + imageUrl = "https://placecats.com/neo/250/200"; + break; + } + case 1: { + imageUrl = "https://placecats.com/millie/250/200"; + break; + } + case 2: + default: { + imageUrl = "https://placecats.com/bella/250/200"; + break; + } + } + catList[i] = { id: i, - imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i - }); + imageUrl, + }; } ``` @@ -961,7 +994,7 @@ export default function CatFriends() { behavior: 'smooth', block: 'nearest', inline: 'center' - }); + }); }}> Next </button> @@ -993,12 +1026,30 @@ export default function CatFriends() { ); } -const catList = []; -for (let i = 0; i < 10; i++) { - catList.push({ +const catCount = 10; +const catList = new Array(catCount); +for (let i = 0; i < catCount; i++) { + const bucket = Math.floor(Math.random() * catCount) % 2; + let imageUrl = ''; + switch (bucket) { + case 0: { + imageUrl = "https://placecats.com/neo/250/200"; + break; + } + case 1: { + imageUrl = "https://placecats.com/millie/250/200"; + break; + } + case 2: + default: { + imageUrl = "https://placecats.com/bella/250/200"; + break; + } + } + catList[i] = { id: i, - imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i - }); + imageUrl, + }; } ``` diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md index 1df8c0e229..e5cd8596ba 100644 --- a/src/content/learn/preserving-and-resetting-state.md +++ b/src/content/learn/preserving-and-resetting-state.md @@ -704,7 +704,7 @@ Di sini, fungsi komponen `MyTextField` didefinisikan *di dalam* `MyComponent`: <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [7]}} import { useState } from 'react'; export default function MyComponent() { diff --git a/src/content/learn/react-compiler/debugging.md b/src/content/learn/react-compiler/debugging.md new file mode 100644 index 0000000000..1883125a6a --- /dev/null +++ b/src/content/learn/react-compiler/debugging.md @@ -0,0 +1,93 @@ +--- +title: Debugging and Troubleshooting +--- + +<Intro> +This guide helps you identify and fix issues when using React Compiler. Learn how to debug compilation problems and resolve common issues. +</Intro> + +<YouWillLearn> + +* The difference between compiler errors and runtime issues +* Common patterns that break compilation +* Step-by-step debugging workflow + +</YouWillLearn> + +## Understanding Compiler Behavior {/*understanding-compiler-behavior*/} + +React Compiler is designed to handle code that follows the [Rules of React](/reference/rules). When it encounters code that might break these rules, it safely skips optimization rather than risk changing your app's behavior. + +### Compiler Errors vs Runtime Issues {/*compiler-errors-vs-runtime-issues*/} + +**Compiler errors** occur at build time and prevent your code from compiling. These are rare because the compiler is designed to skip problematic code rather than fail. + +**Runtime issues** occur when compiled code behaves differently than expected. Most of the time, if you encounter an issue with React Compiler, it's a runtime issue. This typically happens when your code violates the Rules of React in subtle ways that the compiler couldn't detect, and the compiler mistakenly compiled a component it should have skipped. + +When debugging runtime issues, focus your efforts on finding Rules of React violations in the affected components that were not detected by the ESLint rule. The compiler relies on your code following these rules, and when they're broken in ways it can't detect, that's when runtime problems occur. + + +## Common Breaking Patterns {/*common-breaking-patterns*/} + +One of the main ways React Compiler can break your app is if your code was written to rely on memoization for correctness. This means your app depends on specific values being memoized to work properly. Since the compiler may memoize differently than your manual approach, this can lead to unexpected behavior like effects over-firing, infinite loops, or missing updates. + +Common scenarios where this occurs: + +- **Effects that rely on referential equality** - When effects depend on objects or arrays maintaining the same reference across renders +- **Dependency arrays that need stable references** - When unstable dependencies cause effects to fire too often or create infinite loops +- **Conditional logic based on reference checks** - When code uses referential equality checks for caching or optimization + +## Debugging Workflow {/*debugging-workflow*/} + +Follow these steps when you encounter issues: + +### Compiler Build Errors {/*compiler-build-errors*/} + +If you encounter a compiler error that unexpectedly breaks your build, this is likely a bug in the compiler. Report it to the [facebook/react](https://github.com/facebook/react/issues) repository with: +- The error message +- The code that caused the error +- Your React and compiler versions + +### Runtime Issues {/*runtime-issues*/} + +For runtime behavior issues: + +### 1. Temporarily Disable Compilation {/*temporarily-disable-compilation*/} + +Use `"use no memo"` to isolate whether an issue is compiler-related: + +```js +function ProblematicComponent() { + "use no memo"; // Skip compilation for this component + // ... rest of component +} +``` + +If the issue disappears, it's likely related to a Rules of React violation. + +You can also try removing manual memoization (useMemo, useCallback, memo) from the problematic component to verify that your app works correctly without any memoization. If the bug still occurs when all memoization is removed, you have a Rules of React violation that needs to be fixed. + +### 2. Fix Issues Step by Step {/*fix-issues-step-by-step*/} + +1. Identify the root cause (often memoization-for-correctness) +2. Test after each fix +3. Remove `"use no memo"` once fixed +4. Verify the component shows the ✨ badge in React DevTools + +## Reporting Compiler Bugs {/*reporting-compiler-bugs*/} + +If you believe you've found a compiler bug: + +1. **Verify it's not a Rules of React violation** - Check with ESLint +2. **Create a minimal reproduction** - Isolate the issue in a small example +3. **Test without the compiler** - Confirm the issue only occurs with compilation +4. **File an [issue](https://github.com/facebook/react/issues/new?template=compiler_bug_report.yml)**: + - React and compiler versions + - Minimal reproduction code + - Expected vs actual behavior + - Any error messages + +## Next Steps {/*next-steps*/} + +- Review the [Rules of React](/reference/rules) to prevent issues +- Check the [incremental adoption guide](/learn/react-compiler/incremental-adoption) for gradual rollout strategies \ No newline at end of file diff --git a/src/content/learn/react-compiler/incremental-adoption.md b/src/content/learn/react-compiler/incremental-adoption.md new file mode 100644 index 0000000000..56d9320346 --- /dev/null +++ b/src/content/learn/react-compiler/incremental-adoption.md @@ -0,0 +1,225 @@ +--- +title: Incremental Adoption +--- + +<Intro> +React Compiler can be adopted incrementally, allowing you to try it on specific parts of your codebase first. This guide shows you how to gradually roll out the compiler in existing projects. +</Intro> + +<YouWillLearn> + +* Why incremental adoption is recommended +* Using Babel overrides for directory-based adoption +* Using the "use memo" directive for opt-in compilation +* Using the "use no memo" directive to exclude components +* Runtime feature flags with gating +* Monitoring your adoption progress + +</YouWillLearn> + +## Why Incremental Adoption? {/*why-incremental-adoption*/} + +React Compiler is designed to optimize your entire codebase automatically, but you don't have to adopt it all at once. Incremental adoption gives you control over the rollout process, letting you test the compiler on small parts of your app before expanding to the rest. + +Starting small helps you build confidence in the compiler's optimizations. You can verify that your app behaves correctly with compiled code, measure performance improvements, and identify any edge cases specific to your codebase. This approach is especially valuable for production applications where stability is critical. + +Incremental adoption also makes it easier to address any Rules of React violations the compiler might find. Instead of fixing violations across your entire codebase at once, you can tackle them systematically as you expand compiler coverage. This keeps the migration manageable and reduces the risk of introducing bugs. + +By controlling which parts of your code get compiled, you can also run A/B tests to measure the real-world impact of the compiler's optimizations. This data helps you make informed decisions about full adoption and demonstrates the value to your team. + +## Approaches to Incremental Adoption {/*approaches-to-incremental-adoption*/} + +There are three main approaches to adopt React Compiler incrementally: + +1. **Babel overrides** - Apply the compiler to specific directories +2. **Opt-in with "use memo"** - Only compile components that explicitly opt in +3. **Runtime gating** - Control compilation with feature flags + +All approaches allow you to test the compiler on specific parts of your application before full rollout. + +## Directory-Based Adoption with Babel Overrides {/*directory-based-adoption*/} + +Babel's `overrides` option lets you apply different plugins to different parts of your codebase. This is ideal for gradually adopting React Compiler directory by directory. + +### Basic Configuration {/*basic-configuration*/} + +Start by applying the compiler to a specific directory: + +```js +// babel.config.js +module.exports = { + plugins: [ + // Global plugins that apply to all files + ], + overrides: [ + { + test: './src/modern/**/*.{js,jsx,ts,tsx}', + plugins: [ + 'babel-plugin-react-compiler' + ] + } + ] +}; +``` + +### Expanding Coverage {/*expanding-coverage*/} + +As you gain confidence, add more directories: + +```js +// babel.config.js +module.exports = { + plugins: [ + // Global plugins + ], + overrides: [ + { + test: ['./src/modern/**/*.{js,jsx,ts,tsx}', './src/features/**/*.{js,jsx,ts,tsx}'], + plugins: [ + 'babel-plugin-react-compiler' + ] + }, + { + test: './src/legacy/**/*.{js,jsx,ts,tsx}', + plugins: [ + // Different plugins for legacy code + ] + } + ] +}; +``` + +### With Compiler Options {/*with-compiler-options*/} + +You can also configure compiler options per override: + +```js +// babel.config.js +module.exports = { + plugins: [], + overrides: [ + { + test: './src/experimental/**/*.{js,jsx,ts,tsx}', + plugins: [ + ['babel-plugin-react-compiler', { + // options ... + }] + ] + }, + { + test: './src/production/**/*.{js,jsx,ts,tsx}', + plugins: [ + ['babel-plugin-react-compiler', { + // options ... + }] + ] + } + ] +}; +``` + + +## Opt-in Mode with "use memo" {/*opt-in-mode-with-use-memo*/} + +For maximum control, you can use `compilationMode: 'annotation'` to only compile components and hooks that explicitly opt in with the `"use memo"` directive. + +<Note> +This approach gives you fine-grained control over individual components and hooks. It's useful when you want to test the compiler on specific components without affecting entire directories. +</Note> + +### Annotation Mode Configuration {/*annotation-mode-configuration*/} + +```js +// babel.config.js +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + compilationMode: 'annotation', + }], + ], +}; +``` + +### Using the Directive {/*using-the-directive*/} + +Add `"use memo"` at the beginning of functions you want to compile: + +```js +function TodoList({ todos }) { + "use memo"; // Opt this component into compilation + + const sortedTodos = todos.slice().sort(); + + return ( + <ul> + {sortedTodos.map(todo => ( + <TodoItem key={todo.id} todo={todo} /> + ))} + </ul> + ); +} + +function useSortedData(data) { + "use memo"; // Opt this hook into compilation + + return data.slice().sort(); +} +``` + +With `compilationMode: 'annotation'`, you must: +- Add `"use memo"` to every component you want optimized +- Add `"use memo"` to every custom hook +- Remember to add it to new components + +This gives you precise control over which components are compiled while you evaluate the compiler's impact. + +## Runtime Feature Flags with Gating {/*runtime-feature-flags-with-gating*/} + +The `gating` option enables you to control compilation at runtime using feature flags. This is useful for running A/B tests or gradually rolling out the compiler based on user segments. + +### How Gating Works {/*how-gating-works*/} + +The compiler wraps optimized code in a runtime check. If the gate returns `true`, the optimized version runs. Otherwise, the original code runs. + +### Gating Configuration {/*gating-configuration*/} + +```js +// babel.config.js +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + gating: { + source: 'ReactCompilerFeatureFlags', + importSpecifierName: 'isCompilerEnabled', + }, + }], + ], +}; +``` + +### Implementing the Feature Flag {/*implementing-the-feature-flag*/} + +Create a module that exports your gating function: + +```js +// ReactCompilerFeatureFlags.js +export function isCompilerEnabled() { + // Use your feature flag system + return getFeatureFlag('react-compiler-enabled'); +} +``` + +## Troubleshooting Adoption {/*troubleshooting-adoption*/} + +If you encounter issues during adoption: + +1. Use `"use no memo"` to temporarily exclude problematic components +2. Check the [debugging guide](/learn/react-compiler/debugging) for common issues +3. Fix Rules of React violations identified by the ESLint plugin +4. Consider using `compilationMode: 'annotation'` for more gradual adoption + +## Next Steps {/*next-steps*/} + +- Read the [configuration guide](/reference/react-compiler/configuration) for more options +- Learn about [debugging techniques](/learn/react-compiler/debugging) +- Check the [API reference](/reference/react-compiler/configuration) for all compiler options \ No newline at end of file diff --git a/src/content/learn/react-compiler/index.md b/src/content/learn/react-compiler/index.md new file mode 100644 index 0000000000..480187ed5e --- /dev/null +++ b/src/content/learn/react-compiler/index.md @@ -0,0 +1,33 @@ +--- +title: React Compiler +--- + +## Introduction {/*introduction*/} + +Learn [what React Compiler does](/learn/react-compiler/introduction) and how it automatically optimizes your React application by handling memoization for you, eliminating the need for manual `useMemo`, `useCallback`, and `React.memo`. + +## Installation {/*installation*/} + +Get started with [installing React Compiler](/learn/react-compiler/installation) and learn how to configure it with your build tools. + + +## Incremental Adoption {/*incremental-adoption*/} + +Learn [strategies for gradually adopting React Compiler](/learn/react-compiler/incremental-adoption) in your existing codebase if you're not ready to enable it everywhere yet. + +## Debugging and Troubleshooting {/*debugging-and-troubleshooting*/} + +When things don't work as expected, use our [debugging guide](/learn/react-compiler/debugging) to understand the difference between compiler errors and runtime issues, identify common breaking patterns, and follow a systematic debugging workflow. + +## Configuration and Reference {/*configuration-and-reference*/} + +For detailed configuration options and API reference: + +- [Configuration Options](/reference/react-compiler/configuration) - All compiler configuration options including React version compatibility +- [Directives](/reference/react-compiler/directives) - Function-level compilation control +- [Compiling Libraries](/reference/react-compiler/compiling-libraries) - Shipping pre-compiled libraries + +## Additional resources {/*additional-resources*/} + +In addition to these docs, we recommend checking the [React Compiler Working Group](https://github.com/reactwg/react-compiler) for additional information and discussion about the compiler. + diff --git a/src/content/learn/react-compiler/installation.md b/src/content/learn/react-compiler/installation.md new file mode 100644 index 0000000000..6cce34c6b6 --- /dev/null +++ b/src/content/learn/react-compiler/installation.md @@ -0,0 +1,245 @@ +--- +title: Installation +--- + +<Intro> +This guide will help you install and configure React Compiler in your React application. +</Intro> + +<YouWillLearn> + +* How to install React Compiler +* Basic configuration for different build tools +* How to verify your setup is working + +</YouWillLearn> + +## Prerequisites {/*prerequisites*/} + +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). + +## Installation {/*installation*/} + +Install React Compiler as a `devDependency`: + +<TerminalBlock> +npm install -D babel-plugin-react-compiler@latest +</TerminalBlock> + +Or with Yarn: + +<TerminalBlock> +yarn add -D babel-plugin-react-compiler@latest +</TerminalBlock> + +Or with pnpm: + +<TerminalBlock> +pnpm install -D babel-plugin-react-compiler@latest +</TerminalBlock> + +## Basic Setup {/*basic-setup*/} + +React Compiler is designed to work by default without any configuration. However, if you need to configure it in special circumstances (for example, to target React versions below 19), refer to the [compiler options reference](/reference/react-compiler/configuration). + +The setup process depends on your build tool. React Compiler includes a Babel plugin that integrates with your build pipeline. + +<Pitfall> +React Compiler must run **first** in your Babel plugin pipeline. The compiler needs the original source information for proper analysis, so it must process your code before other transformations. +</Pitfall> + +### Babel {/*babel*/} + +Create or update your `babel.config.js`: + +```js {3} +module.exports = { + plugins: [ + 'babel-plugin-react-compiler', // must run first! + // ... other plugins + ], + // ... other config +}; +``` + +### Vite {/*vite*/} + +If you use Vite, you can add the plugin to vite-plugin-react: + +```js {3,9} +// vite.config.js +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [ + react({ + babel: { + plugins: ['babel-plugin-react-compiler'], + }, + }), + ], +}); +``` + +Alternatively, if you prefer a separate Babel plugin for Vite: + +<TerminalBlock> +npm install -D vite-plugin-babel +</TerminalBlock> + +```js {2,11} +// vite.config.js +import babel from 'vite-plugin-babel'; +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [ + react(), + babel({ + babelConfig: { + plugins: ['babel-plugin-react-compiler'], + }, + }), + ], +}); +``` + +### Next.js {/*usage-with-nextjs*/} + +Please refer to the [Next.js docs](https://nextjs.org/docs/app/api-reference/next-config-js/reactCompiler) for more information. + +### React Router {/*usage-with-react-router*/} +Install `vite-plugin-babel`, and add the compiler's Babel plugin to it: + +<TerminalBlock> +npm install vite-plugin-babel +</TerminalBlock> + +```js {3-4,16} +// vite.config.js +import { defineConfig } from "vite"; +import babel from "vite-plugin-babel"; +import { reactRouter } from "@react-router/dev/vite"; + +const ReactCompilerConfig = { /* ... */ }; + +export default defineConfig({ + plugins: [ + reactRouter(), + babel({ + filter: /\.[jt]sx?$/, + babelConfig: { + presets: ["@babel/preset-typescript"], // if you use TypeScript + plugins: [ + ["babel-plugin-react-compiler", ReactCompilerConfig], + ], + }, + }), + ], +}); +``` + +### Webpack {/*usage-with-webpack*/} + +A community webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack). + +### Expo {/*usage-with-expo*/} + +Please refer to [Expo's docs](https://docs.expo.dev/guides/react-compiler/) to enable and use the React Compiler in Expo apps. + +### Metro (React Native) {/*usage-with-react-native-metro*/} + +React Native uses Babel via Metro, so refer to the [Usage with Babel](#babel) section for installation instructions. + +### Rspack {/*usage-with-rspack*/} + +Please refer to [Rspack's docs](https://rspack.dev/guide/tech/react#react-compiler) to enable and use the React Compiler in Rspack apps. + +### Rsbuild {/*usage-with-rsbuild*/} + +Please refer to [Rsbuild's docs](https://rsbuild.dev/guide/framework/react#react-compiler) to enable and use the React Compiler in Rsbuild apps. + + +## ESLint Integration {/*eslint-integration*/} + +React Compiler includes an ESLint rule that helps identify code that can't be optimized. When the ESLint rule reports an error, it means the compiler will skip optimizing that specific component or hook. This is safe: the compiler will continue optimizing other parts of your codebase. You don't need to fix all violations immediately. Address them at your own pace to gradually increase the number of optimized components. + +Install the ESLint plugin: + +<TerminalBlock> +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 rules are available in the `recommended-latest` preset. + +The ESLint rule will: +- Identify violations of the [Rules of React](/reference/rules) +- Show which components can't be optimized +- Provide helpful error messages for fixing issues + +## Verify Your Setup {/*verify-your-setup*/} + +After installation, verify that React Compiler is working correctly. + +### Check React DevTools {/*check-react-devtools*/} + +Components optimized by React Compiler will show a "Memo ✨" badge in React DevTools: + +1. Install the [React Developer Tools](/learn/react-developer-tools) browser extension +2. Open your app in development mode +3. Open React DevTools +4. Look for the ✨ emoji next to component names + +If the compiler is working: +- Components will show a "Memo ✨" badge in React DevTools +- Expensive calculations will be automatically memoized +- No manual `useMemo` is required + +### Check Build Output {/*check-build-output*/} + +You can also verify the compiler is running by checking your build output. The compiled code will include automatic memoization logic that the compiler adds automatically. + +```js +import { c as _c } from "react/compiler-runtime"; +export default function MyApp() { + const $ = _c(1); + let t0; + if ($[0] === Symbol.for("react.memo_cache_sentinel")) { + t0 = <div>Hello World</div>; + $[0] = t0; + } else { + t0 = $[0]; + } + return t0; +} + +``` + +## Troubleshooting {/*troubleshooting*/} + +### Opting out specific components {/*opting-out-specific-components*/} + +If a component is causing issues after compilation, you can temporarily opt it out using the `"use no memo"` directive: + +```js +function ProblematicComponent() { + "use no memo"; + // Component code here +} +``` + +This tells the compiler to skip optimization for this specific component. You should fix the underlying issue and remove the directive once resolved. + +For more troubleshooting help, see the [debugging guide](/learn/react-compiler/debugging). + +## Next Steps {/*next-steps*/} + +Now that you have React Compiler installed, learn more about: + +- [React version compatibility](/reference/react-compiler/target) for React 17 and 18 +- [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 diff --git a/src/content/learn/react-compiler/introduction.md b/src/content/learn/react-compiler/introduction.md new file mode 100644 index 0000000000..ff5d6eae48 --- /dev/null +++ b/src/content/learn/react-compiler/introduction.md @@ -0,0 +1,191 @@ +--- +title: Introduction +--- + +<Intro> +React Compiler is a new build-time tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it. +</Intro> + +<YouWillLearn> + +* What React Compiler does +* Getting started with the compiler +* Incremental adoption strategies +* Debugging and troubleshooting when things go wrong +* Using the compiler on your React library + +</YouWillLearn> + +## 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. + +### Before React Compiler {/*before-react-compiler*/} + +Without the compiler, you need to manually memoize components and values to optimize re-renders: + +```js +import { useMemo, useCallback, memo } from 'react'; + +const ExpensiveComponent = memo(function ExpensiveComponent({ data, onClick }) { + const processedData = useMemo(() => { + return expensiveProcessing(data); + }, [data]); + + const handleClick = useCallback((item) => { + onClick(item.id); + }, [onClick]); + + return ( + <div> + {processedData.map(item => ( + <Item key={item.id} onClick={() => handleClick(item)} /> + ))} + </div> + ); +}); +``` + + +<Note> + +This manual memoization has a subtle bug that breaks memoization: + +```js [[2, 1, "() => handleClick(item)"]] +<Item key={item.id} onClick={() => handleClick(item)} /> +``` + +Even though `handleClick` is wrapped in `useCallback`, the arrow function `() => handleClick(item)` creates a new function every time the component renders. This means that `Item` will always receive a new `onClick` prop, breaking memoization. + +React Compiler is able to optimize this correctly with or without the arrow function, ensuring that `Item` only re-renders when `props.onClick` changes. + +</Note> + +### After React Compiler {/*after-react-compiler*/} + +With React Compiler, you write the same code without manual memoization: + +```js +function ExpensiveComponent({ data, onClick }) { + const processedData = expensiveProcessing(data); + + const handleClick = (item) => { + onClick(item.id); + }; + + return ( + <div> + {processedData.map(item => ( + <Item key={item.id} onClick={() => handleClick(item)} /> + ))} + </div> + ); +} +``` + +_[See this example in the React Compiler Playground](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAogB4AOCmYeAbggMIQC2Fh1OAFMEQCYBDHAIA0RQowA2eOAGsiAXwCURYAB1iROITA4iFGBERgwCPgBEhAogF4iCStVoMACoeO1MAcy6DhSgG4NDSItHT0ACwFMPkkmaTlbIi48HAQWFRsAPlUQ0PFMKRlZFLSWADo8PkC8hSDMPJgEHFhiLjzQgB4+eiyO-OADIwQTM0thcpYBClL02xz2zXz8zoBJMqJZBABPG2BU9Mq+BQKiuT2uTJyomLizkoOMk4B6PqX8pSUFfs7nnro3qEapgFCAFEA)_ + +React Compiler automatically applies the optimal memoization, ensuring your app only re-renders when necessary. + +<DeepDive> +#### What kind of memoization does React Compiler add? {/*what-kind-of-memoization-does-react-compiler-add*/} + +React Compiler's automatic memoization is primarily focused on **improving update performance** (re-rendering existing components), so it focuses on these two use cases: + +1. **Skipping cascading re-rendering of components** + * Re-rendering `<Parent />` causes many components in its component tree to re-render, even though only `<Parent />` has changed +1. **Skipping expensive calculations from outside of React** + * For example, calling `expensivelyProcessAReallyLargeArrayOfObjects()` inside of your component or hook that needs that data + +#### Optimizing Re-renders {/*optimizing-re-renders*/} + +React lets you express your UI as a function of their current state (more concretely: their props, state, and context). In its current implementation, when a component's state changes, React will re-render that component _and all of its children_ β€” unless you have applied some form of manual memoization with `useMemo()`, `useCallback()`, or `React.memo()`. For example, in the following example, `<MessageButton>` will re-render whenever `<FriendList>`'s state changes: + +```javascript +function FriendList({ friends }) { + const onlineCount = useFriendOnlineCount(); + if (friends.length === 0) { + return <NoFriends />; + } + return ( + <div> + <span>{onlineCount} online</span> + {friends.map((friend) => ( + <FriendListCard key={friend.id} friend={friend} /> + ))} + <MessageButton /> + </div> + ); +} +``` +[_See this example in the React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAYjHgpgCYAyeYOAFMEWuZVWEQL4CURwADrEicQgyKEANnkwIAwtEw4iAXiJQwCMhWoB5TDLmKsTXgG5hRInjRFGbXZwB0UygHMcACzWr1ABn4hEWsYBBxYYgAeADkIHQ4uAHoAPksRbisiMIiYYkYs6yiqPAA3FMLrIiiwAAcAQ0wU4GlZBSUcbklDNqikusaKkKrgR0TnAFt62sYHdmp+VRT7SqrqhOo6Bnl6mCoiAGsEAE9VUfmqZzwqLrHqM7ubolTVol5eTOGigFkEMDB6u4EAAhKA4HCEZ5DNZ9ErlLIWYTcEDcIA) + +React Compiler automatically applies the equivalent of manual memoization, ensuring that only the relevant parts of an app re-render as state changes, which is sometimes referred to as "fine-grained reactivity". In the above example, React Compiler determines that the return value of `<FriendListCard />` can be reused even as `friends` changes, and can avoid recreating this JSX _and_ avoid re-rendering `<MessageButton>` as the count changes. + +#### Expensive calculations also get memoized {/*expensive-calculations-also-get-memoized*/} + +React Compiler can also automatically memoize expensive calculations used during rendering: + +```js +// **Not** memoized by React Compiler, since this is not a component or hook +function expensivelyProcessAReallyLargeArrayOfObjects() { /* ... */ } + +// Memoized by React Compiler since this is a component +function TableContainer({ items }) { + // This function call would be memoized: + const data = expensivelyProcessAReallyLargeArrayOfObjects(items); + // ... +} +``` +[_See this example in the React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAejQAgFTYHIQAuumAtgqRAJYBeCAJpgEYCemASggIZyGYDCEUgAcqAGwQwANJjBUAdokyEAFlTCZ1meUUxdMcIcIjyE8vhBiYVECAGsAOvIBmURYSonMCAB7CzcgBuCGIsAAowEIhgYACCnFxioQAyXDAA5gixMDBcLADyzvlMAFYIvGAAFACUmMCYaNiYAHStOFgAvk5OGJgAshTUdIysHNy8AkbikrIKSqpaWvqGIiZmhE6u7p7ymAAqXEwSguZcCpKV9VSEFBodtcBOmAYmYHz0XIT6ALzefgFUYKhCJRBAxeLcJIsVIZLI5PKFYplCqVa63aoAbm6u0wMAQhFguwAPPRAQA+YAfL4dIloUmBMlODogDpAA) + +However, if `expensivelyProcessAReallyLargeArrayOfObjects` is truly an expensive function, you may want to consider implementing its own memoization outside of React, because: + +- React Compiler only memoizes React components and hooks, not every function +- React Compiler's memoization is not shared across multiple components or hooks + +So if `expensivelyProcessAReallyLargeArrayOfObjects` was used in many different components, even if the same exact items were passed down, that expensive calculation would be run repeatedly. We recommend [profiling](reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive) first to see if it really is that expensive before making code more complicated. +</DeepDive> + +## Should I try out the compiler? {/*should-i-try-out-the-compiler*/} + +We encourage everyone to start using React Compiler. While the compiler is still an optional addition to React today, in the future some features may require the compiler in order to fully work. + +### Is it safe to use? {/*is-it-safe-to-use*/} + +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*/} + +React Compiler can be installed across [several build tools](/learn/react-compiler/installation) such as Babel, Vite, Metro, and Rsbuild. + +React Compiler is primarily a light Babel plugin wrapper around the core compiler, which was designed to be decoupled from Babel itself. While the initial stable version of the compiler will remain primarily a Babel plugin, we are working with the swc and [oxc](https://github.com/oxc-project/oxc/issues/10048) teams to build first class support for React Compiler so you won't have to add Babel back to your build pipelines in the future. + +Next.js users can enable the swc-invoked React Compiler by using [v15.3.1](https://github.com/vercel/next.js/releases/tag/v15.3.1) and up. + +## 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. + +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. + +## Try React Compiler {/*try-react-compiler*/} + +This section will help you get started with React Compiler and understand how to use it effectively in your projects. + +* **[Installation](/learn/react-compiler/installation)** - Install React Compiler and configure it for your build tools +* **[React Version Compatibility](/reference/react-compiler/target)** - Support for React 17, 18, and 19 +* **[Configuration](/reference/react-compiler/configuration)** - Customize the compiler for your specific needs +* **[Incremental Adoption](/learn/react-compiler/incremental-adoption)** - Strategies for gradually rolling out the compiler in existing codebases +* **[Debugging and Troubleshooting](/learn/react-compiler/debugging)** - Identify and fix issues when using the compiler +* **[Compiling Libraries](/reference/react-compiler/compiling-libraries)** - Best practices for shipping compiled code +* **[API Reference](/reference/react-compiler/configuration)** - Detailed documentation of all configuration options + +## Additional resources {/*additional-resources*/} + +In addition to these docs, we recommend checking the [React Compiler Working Group](https://github.com/reactwg/react-compiler) for additional information and discussion about the compiler. + diff --git a/src/content/learn/referencing-values-with-refs.md b/src/content/learn/referencing-values-with-refs.md index dfdb3d54c1..21d1e29582 100644 --- a/src/content/learn/referencing-values-with-refs.md +++ b/src/content/learn/referencing-values-with-refs.md @@ -210,7 +210,7 @@ Jika Anda mencoba mengimplementasikan ini dengan menggunakan *ref*, React tidak <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [13]}} import { useRef } from 'react'; export default function Counter() { @@ -313,7 +313,7 @@ Variabel biasa seperti `let timeoutID` tidak "bertahan" antara *render* ulang ka <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [10]}} import { useState } from 'react'; export default function Chat() { @@ -418,7 +418,7 @@ Tombol ini seharusnya beralih antara menunjukkan "Nyala" dan "Mati". Namun, sela <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [10]}} import { useRef } from 'react'; export default function Toggle() { diff --git a/src/content/learn/removing-effect-dependencies.md b/src/content/learn/removing-effect-dependencies.md index 9c5c37d49d..e891d2ea93 100644 --- a/src/content/learn/removing-effect-dependencies.md +++ b/src/content/learn/removing-effect-dependencies.md @@ -304,7 +304,7 @@ Menekan *linter* menyebabkan bug yang sangat tidak intuitif yang sulit ditemukan <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [14]}} import { useState, useEffect } from 'react'; export default function Timer() { @@ -609,6 +609,7 @@ function ChatRoom({ roomId }) { ### Apakah Anda ingin membaca nilai tanpa "bereaksi" terhadap perubahannya? {/*do-you-want-to-read-a-value-without-reacting-to-its-changes*/} +<<<<<<< HEAD <Wip> Bagian ini menjelaskan **API experimental yang belum dirilis** dalam versi stabil React. @@ -616,6 +617,9 @@ Bagian ini menjelaskan **API experimental yang belum dirilis** dalam versi stabi </Wip> Misalkan Anda ingin memainkan bunyi saat pengguna menerima pesan baru kecuali `isMuted` bernilai `true`: +======= +Suppose that you want to play a sound when the user receives a new message unless `isMuted` is `true`: +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ```js {3,10-12} function ChatRoom({ roomId }) { @@ -794,7 +798,7 @@ Penting untuk mendeklarasikannya sebagai dependensi, Hal ini memastikan, misalny <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [10]}} import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; @@ -1259,25 +1263,9 @@ Apakah ada baris kode di dalam *Effect* yang tidak boleh reaktif? Bagaimana cara <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 +1374,10 @@ html, body { min-height: 300px; } <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); @@ -1826,8 +1798,8 @@ Fungsi lain dari fungsi ini hanya ada untuk mengoper beberapa *state* ke metode ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -1908,7 +1880,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(() => { @@ -2121,8 +2093,8 @@ Hasilnya, obrolan akan tersambung kembali hanya jika ada sesuatu yang berarti (` ```json package.json hidden { "dependencies": { - "react": "experimental", - "react-dom": "experimental", + "react": "latest", + "react-dom": "latest", "react-scripts": "latest", "toastify-js": "1.12.0" }, @@ -2190,7 +2162,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/responding-to-events.md b/src/content/learn/responding-to-events.md index f3034acf7d..ab3f88a1e7 100644 --- a/src/content/learn/responding-to-events.md +++ b/src/content/learn/responding-to-events.md @@ -546,7 +546,7 @@ Mengeklik tombol ini seharusnya mengganti latar belakang halaman dari putih ke h <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [5, 7]}} export default function LightSwitch() { function handleClick() { let bodyStyle = document.body.style; diff --git a/src/content/learn/reusing-logic-with-custom-hooks.md b/src/content/learn/reusing-logic-with-custom-hooks.md index 716b528936..4f1dc5eda2 100644 --- a/src/content/learn/reusing-logic-with-custom-hooks.md +++ b/src/content/learn/reusing-logic-with-custom-hooks.md @@ -836,6 +836,7 @@ Setiap kali komponen `ChatRoom` Anda di-*render* ulang, komponen `roomId` dan `s ### Passing event handlers to custom Hooks {/*passing-event-handlers-to-custom-hooks*/} +<<<<<<< HEAD <Wip> Bagian ini menjelaskan **API eksperimental yang belum dirilis** di versi stabil React. @@ -843,6 +844,9 @@ Bagian ini menjelaskan **API eksperimental yang belum dirilis** di versi stabil </Wip> Saat Anda mulai menggunakan `useChatRoom` di lebih banyak komponen, Anda mungkin ingin membiarkan komponen menyesuaikan perilakunya. Sebagai contoh, saat ini, logika tentang apa yang harus dilakukan ketika sebuah pesan datang di-hardcode di dalam Hook: +======= +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: +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ```js {9-11} export function useChatRoom({ serverUrl, roomId }) { @@ -984,7 +988,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 }) { @@ -1069,8 +1073,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" }, @@ -1418,10 +1422,36 @@ Mirip dengan [sistem desain,](https://uxdesign.cc/everything-you-need-to-know-ab #### Akankah React akan menyediakan solusi bawaan untuk pengambilan data? {/*will-react-provide-any-built-in-solution-for-data-fetching*/} +<<<<<<< HEAD Kami masih mengerjakan detailnya, tetapi kami berharap di masa mendatang, Anda akan menulis pengambilan data seperti ini: ```js {1,4,6} import { use } from 'react'; // Belum tersedia! +======= +Today, with the [`use`](/reference/react/use#streaming-data-from-server-to-client) API, data can be read in render by passing a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to `use`: + +```js {1,4,11} +import { use, Suspense } from "react"; + +function Message({ messagePromise }) { + const messageContent = use(messagePromise); + return <p>Here is the message: {messageContent}</p>; +} + +export function MessageContainer({ messagePromise }) { + return ( + <Suspense fallback={<p>βŒ›Downloading message...</p>}> + <Message messagePromise={messagePromise} /> + </Suspense> + ); +} +``` + +We're still working out the details, but we expect that in the future, you'll write data fetching like this: + +```js {1,4,6} +import { use } from 'react'; +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 function ShippingForm({ country }) { const cities = use(fetch(`/api/cities?country=${country}`)); @@ -1646,7 +1676,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); @@ -1696,22 +1726,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> Namun, Anda tidak *harus* melakukan itu. Seperti halnya fungsi biasa, pada akhirnya Anda yang memutuskan di mana harus menggambar batas antara berbagai bagian kode Anda. Anda juga bisa mengambil pendekatan yang sangat berbeda. Alih-alih mempertahankan logika dalam Effect, Anda dapat memindahkan sebagian besar logika imperatif ke dalam JavaScript [class:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) @@ -2185,22 +2199,6 @@ Sepertinya custom Hook `useInterval` Anda menerima sebuah event listener sebagai <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'; @@ -2232,7 +2230,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(() => { @@ -2256,22 +2254,6 @@ Dengan perubahan ini, kedua interval akan berfungsi seperti yang diharapkan dan <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'; @@ -2304,7 +2286,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/scaling-up-with-reducer-and-context.md b/src/content/learn/scaling-up-with-reducer-and-context.md index df04abf96c..6c1d857a4b 100644 --- a/src/content/learn/scaling-up-with-reducer-and-context.md +++ b/src/content/learn/scaling-up-with-reducer-and-context.md @@ -685,7 +685,11 @@ Sekarang Anda tidak perlu lagi meneruskan daftar tugas atau *event handler* ke b </TasksContext> ``` +<<<<<<< HEAD Sebaliknya, komponen mana pun yang memerlukan daftar tugas dapat membacanya dari `TaskContext`: +======= +Instead, any component that needs the task list can read it from the `TasksContext`: +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ```js {2} export default function TaskList() { diff --git a/src/content/learn/separating-events-from-effects.md b/src/content/learn/separating-events-from-effects.md index 03223183b1..5f6ce4ee8d 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: @@ -711,7 +699,7 @@ Here, `url` inside `onVisit` corresponds to the *latest* `url` (which could have In the existing codebases, you may sometimes see the lint rule suppressed like this: -```js {7-9} +```js {expectedErrors: {'react-compiler': [8]}} {7-9} function Page({ url }) { const { items } = useContext(ShoppingCartContext); const numberOfItems = items.length; @@ -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. @@ -735,7 +723,7 @@ Can you see why? <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [16]}} import { useState, useEffect } from 'react'; export default function App() { @@ -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,24 +939,7 @@ 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 +```js {expectedErrors: {'react-compiler': [14]}} import { useState, useEffect } from 'react'; export default function Timer() { @@ -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/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md index 9ea78bdc20..3e3777c02e 100644 --- a/src/content/learn/state-a-components-memory.md +++ b/src/content/learn/state-a-components-memory.md @@ -23,7 +23,7 @@ Di bawah adalah komponen yang merender sebuah gambar pahatan. Menekan tombol "Se <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [7]}} import { sculptureList } from './data.js'; export default function Gallery() { @@ -1232,7 +1232,7 @@ Saat Anda mengetik di dalam kolom masukan, tidak ada yang muncul. Kolom masukkan <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [6]}} export default function Form() { let firstName = ''; let lastName = ''; @@ -1340,7 +1340,7 @@ Apakah ada batasan mengenai *di mana* Hooks bisa dipanggil? Apakah komponen ini <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [9]}} import { useState } from 'react'; export default function FeedbackForm() { diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 7e0e6ebc49..909b47ea1b 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -95,7 +95,7 @@ Anda mungkin tergoda untuk mencoba memanggil `play()` atau `pause()` saat pe-*re <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [7, 9]}} import { useState, useRef, useEffect } from 'react'; function VideoPlayer({ src, isPlaying }) { @@ -619,7 +619,11 @@ Kesalahan umum untuk mencegah *Effect* berjalan dua kali dalam pengembangan adal Hal ini membuat Anda hanya melihat `"βœ… Menghubungkan..."` sekali dalam pengembangan, tetapi hal itu tidak memperbaiki bug. +<<<<<<< HEAD Saat pengguna keluar, koneksi masih belum ditutup dan saat mereka kembali, koneksi baru dibuat. Saat pengguna keluar dari aplikasi, koneksi akan terus menumpuk, sama seperti sebelum "perbaikan". +======= +When the user navigates away, the connection still isn't closed and when they navigate back, a new connection is created. As the user navigates across the app, the connections would keep piling up, the same as it would before the "fix". +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Untuk memperbaiki bug, tidak cukup hanya menjalankan Efek sekali. Efek harus berfungsi setelah dipasang ulang, yang berarti koneksi perlu dibersihkan seperti dalam solusi di atas. @@ -734,8 +738,13 @@ Menulis panggilan `fetch` di dalam *Effects* adalah [cara populer untuk mengambi Daftar kelemahan ini tidak spesifik untuk React. Ini berlaku untuk mengambil data saat pemasangan komponen dengan pustaka apa pun. Seperti halnya dengan *routing*, pengambilan data bukanlah hal yang sepele untuk dilakukan dengan baik, jadi kami merekomendasikan pendekatan berikut ini: +<<<<<<< HEAD - **Jika Anda menggunakan [kerangka kerja (*framework*)](/learn/start-a-new-react-project#production-grade-react-frameworks), gunakan mekanisme pengambilan data yang sudah ada di dalamnya.** Kerangka kerja React modern memiliki mekanisme pengambilan data terintegrasi yang efisien dan tidak mengalami kendala di atas. - **Jika tidak, pertimbangkan untuk menggunakan atau membangun *cache* sisi klien.** Solusi sumber terbuka (*open source*) yang populer termasuk [React Query](https://tanstack.com/query/latest), [useSWR](https://swr.vercel.app/), dan [React Router 6.4+.](https://beta.reactrouter.com/en/main/start/overview) Anda juga dapat membuat solusi sendiri, dalam hal ini Anda dapat menggunakan *Effects* di dalamnya, tetapi menambahkan logika untuk menduplikasi *request*, menyimpan respons dalam *cache*, dan menghindari *waterfall* jaringan (dengan melakukan pramuat data atau mengangkat kebutuhan data ke *route*). +======= +- **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). +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Anda dapat terus mengambil data secara langsung di *Effects* jika tidak ada satu pun dari pendekatan ini yang cocok untuk Anda. @@ -1006,8 +1015,13 @@ import { useEffect, useRef } from 'react'; export default function MyInput({ value, onChange }) { const ref = useRef(null); +<<<<<<< HEAD // TODO: Ini tidak bekerja. Perbaiki. // ref.current.focus() +======= + // TODO: This doesn't quite work. Fix it. + // ref.current.focus() +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 return ( <input @@ -1470,7 +1484,8 @@ Komponen ini menampilkan biografi orang yang dipilih. Komponen ini memuat biogra <Sandpack> -```js src/App.js +{/* not the most efficient, but this validation is enabled in the linter only, so it's fine to ignore it here since we know what we're doing */} +```js {expectedErrors: {'react-compiler': [9]}} src/App.js import { useState, useEffect } from 'react'; import { fetchBio } from './api.js'; @@ -1543,7 +1558,8 @@ Untuk memperbaiki *race condition* ini, tambahkan fungsi pembersihan: <Sandpack> -```js src/App.js +{/* not the most efficient, but this validation is enabled in the linter only, so it's fine to ignore it here since we know what we're doing */} +```js {expectedErrors: {'react-compiler': [9]}} src/App.js import { useState, useEffect } from 'react'; import { fetchBio } from './api.js'; @@ -1607,4 +1623,3 @@ Selain mengabaikan hasil panggilan API yang sudah usang, Anda juga dapat menggun </Solution> </Challenges> - diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md index f428572732..97e945a787 100644 --- a/src/content/learn/thinking-in-react.md +++ b/src/content/learn/thinking-in-react.md @@ -37,9 +37,15 @@ Mulailah dengan menggambar kotak-kotak di sekitar setiap komponen dan subkompone Tergantung pada latar belakang Anda, Anda dapat berpikir untuk membagi desain menjadi beberapa komponen dengan cara yang berbeda: +<<<<<<< HEAD * **Pemrograman**--gunakan teknik yang sama untuk memutuskan apakah Anda harus membuat fungsi atau objek baru. Salah satu teknik tersebut adalah [*single responsibility principle*](https://en.wikipedia.org/wiki/Single_responsibility_principle), yaitu sebuah komponen idealnya hanya melakukan satu hal. Jika komponen tersebut berkembang, maka harus dipecah menjadi subkomponen yang lebih kecil. * **CSS**--pertimbangkan untuk apa Anda akan membuat *class selector*. (Namun, komponen tidak terlalu terperinci.) * **Desain**--pertimbangkan bagaimana Anda akan mengatur *layer* desain. +======= +* **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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Jika JSON Anda terstruktur dengan baik, Anda akan sering menemukan bahwa JSON tersebut secara alami memetakan struktur komponen UI Anda. Hal ini karena UI dan model data sering kali memiliki arsitektur informasi yang sama--atau, bentuk yang sama. Pisahkan UI Anda menjadi beberapa komponen, di mana setiap komponen cocok dengan satu bagian dari model data Anda. diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md index 5496ee37c1..6f258a8fef 100644 --- a/src/content/learn/tutorial-tic-tac-toe.md +++ b/src/content/learn/tutorial-tic-tac-toe.md @@ -283,9 +283,15 @@ Di CodeSandbox Anda akan melihat tiga bagian utama: ![CodeSandbox dengan kode awal](../images/tutorial/react-starter-code-codesandbox.png) +<<<<<<< HEAD 1. Bagian _Files_ dengan daftar file seperti `App.js`, `index.js`, `styles.css`, dan sebuah folder bernama `public` 1. _Editor kode_ di mana Anda akan melihat kode sumber dari berkas yang Anda pilih 1. Bagian _browser_ di mana Anda akan melihat bagaimana kode yang Anda tulis akan ditampilkan +======= +1. The _Files_ section with a list of files like `App.js`, `index.js`, `styles.css` in `src` folder and a folder called `public` +1. The _code editor_ where you'll see the source code of your selected file +1. The _browser_ section where you'll see how the code you've written will be displayed +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 File `App.js` juga sudah terpilih di bagian _Files_. Isi dari file tersebut di dalam _code editor_ seharusnya: diff --git a/src/content/learn/typescript.md b/src/content/learn/typescript.md index e846b6cc2f..067ba0dc13 100644 --- a/src/content/learn/typescript.md +++ b/src/content/learn/typescript.md @@ -11,16 +11,27 @@ TypeScript adalah salah satu cara populer untuk menambahkan definisi *type* ke d <YouWillLearn> +<<<<<<< HEAD * [TypeScript dengan Komponen React](/learn/typescript#typescript-with-react-components) * [Contoh menambahkan *type* dalam Hooks](/learn/typescript#example-hooks) * [*Types* umum dari `@types/react`](/learn/typescript/#useful-types) * [Tempat pembelajaran lebih lanjut](/learn/typescript/#further-learning) +======= +* [TypeScript with React Components](/learn/typescript#typescript-with-react-components) +* [Examples of typing with Hooks](/learn/typescript#example-hooks) +* [Common types from `@types/react`](/learn/typescript#useful-types) +* [Further learning locations](/learn/typescript#further-learning) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </YouWillLearn> ## Pemasangan {/*installation*/} +<<<<<<< HEAD Semua [kerangka kerja React tingkat produksi](/learn/start-a-new-react-project#production-grade-react-frameworks) menawarkan dukungan untuk menggunakan TypeScript. Ikuti panduan khusus kerangka kerja tersebut untuk pemasangan: +======= +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: +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 - [Next.js](https://nextjs.org/docs/app/building-your-application/configuring/typescript) - [Remix](https://remix.run/docs/en/1.19.2/guides/typescript) @@ -32,14 +43,20 @@ Semua [kerangka kerja React tingkat produksi](/learn/start-a-new-react-project#p Untuk memasang versi terbaru definisi *type* React: <TerminalBlock> -npm install @types/react @types/react-dom +npm install --save-dev @types/react @types/react-dom </TerminalBlock> Opsi *compiler* berikut perlu disetel dalam `tsconfig.json` Anda: +<<<<<<< HEAD 1. `dom` harus disertakan dalam [`lib`](https://www.typescriptlang.org/tsconfig/#lib) (Catatan: Jika tidak ada opsi `lib` yang disetel, `dom` disetel secara bawaan). 1. [`jsx`](https://www.typescriptlang.org/tsconfig/#jsx) harus desetel ke salah satu opsi yang valid. `preserve` seharusnya cukup untuk sebagian besar aplikasi. Jika Anda menerbitkan pustaka (*library*), lihat [dokumentasi `jsx`](https://www.typescriptlang.org/tsconfig/#jsx) untuk mengetahui opsi yang harus dipilih. +======= +1. `dom` must be included in [`lib`](https://www.typescriptlang.org/tsconfig/#lib) (Note: If no `lib` option is specified, `dom` is included by default). +2. [`jsx`](https://www.typescriptlang.org/tsconfig/#jsx) must be set to one of the valid options. `preserve` should suffice for most applications. + If you're publishing a library, consult the [`jsx` documentation](https://www.typescriptlang.org/tsconfig/#jsx) on what value to choose. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ## TypeScript dengan Komponen React {/*typescript-with-react-components*/} @@ -124,7 +141,11 @@ export default App = AppTSX; ## Contoh Hooks {/*example-hooks*/} +<<<<<<< HEAD Definisi *type* dari `@types/react` menyertakan *type* untuk Hooks bawaan, sehingga Anda dapat menggunakannya dalam komponen tanpa pengaturan tambahan apa pun. Definisi tersebut dibuat untuk memperhitungkan kode yang Anda tulis dalam komponen, sehingga Anda akan memperoleh [*type* yang disimpulkan](https://www.typescriptlang.org/docs/handbook/type-inference.html) sering kali dan idealnya tidak perlu menangani hal-hal sepele dalam menyediakan *type* sendiri. +======= +The type definitions from `@types/react` include types for the built-in Hooks, so you can use them in your components without any additional setup. They are built to take into account the code you write in your component, so you will get [inferred types](https://www.typescriptlang.org/docs/handbook/type-inference.html) a lot of the time and ideally do not need to handle the minutiae of providing the types. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Namun, kita dapat melihat beberapa contoh tentang cara menyediakan *type* untuk Hooks. @@ -139,8 +160,13 @@ const [enabled, setEnabled] = useState(false); Ini akan menetapkan *type* `boolean` ke `enabled`, dan `setEnabled` akan menjadi fungsi yang menerima argumen `boolean`, atau fungsi yang mengembalikan `boolean`. Jika Anda ingin secara eksplisit memberikan *type* untuk *state*, Anda dapat melakukannya dengan memberikan argumen *type* ke panggilan `useState`: +<<<<<<< HEAD ```ts // Menyetel type ke "boolean" secara eksplisit +======= +```ts +// Explicitly set the type to "boolean" +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 const [enabled, setEnabled] = useState<boolean>(false); ``` @@ -174,7 +200,7 @@ const [requestState, setRequestState] = useState<RequestState>({ status: 'idle' import {useReducer} from 'react'; interface State { - count: number + count: number }; type CounterAction = @@ -284,7 +310,11 @@ export default App = AppTSX; </Sandpack> +<<<<<<< HEAD Teknik ini berfungsi saat Anda memiliki nilai bawaan yang masuk akal - tetapi terkadang ada kasus saat Anda tidak memilikinya, dan dalam kasus tersebut `null` dapat terasa masuk akal sebagai nilai bawaan. Namun, untuk memungkinkan sistem *type* memahami kode Anda, Anda perlu secara eksplisit menetapkan `ContextShape | null` pada `createContext`. +======= +This technique works when you have a default value which makes sense - but there are occasionally cases when you do not, and in those cases `null` can feel reasonable as a default value. However, to allow the type-system to understand your code, you need to explicitly set `ContextShape | null` on the `createContext`. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Hal ini menyebabkan masalah yang mengharuskan Anda menghilangkan `| ​​null` dalam *type* untuk *consumer* *Context*. Rekomendasi kami adalah agar Hook melakukan pemeriksaan *runtime* untuk keberadaannya dan memunculkan kesalahan saat tidak ada: @@ -329,7 +359,17 @@ function MyComponent() { ### `useMemo` {/*typing-usememo*/} +<<<<<<< HEAD Hook [`useMemo`](/reference/react/useMemo) akan membuat/mengakses ulang nilai yang tersimpan dari pemanggilan fungsi, dan menjalankan ulang fungsi hanya saat dependensi yang diteruskan sebagai parameter ke-2 diubah. Hasil pemanggilan Hook disimpulkan dari nilai yang dikembalikan dari fungsi di parameter pertama. Anda dapat lebih eksplisit dengan memberikan argumen *type* ke Hook. +======= +<Note> + +[React Compiler](/learn/react-compiler) automatically memoizes values and functions, reducing the need for manual `useMemo` calls. You can use the compiler to handle memoization automatically. + +</Note> + +The [`useMemo`](/reference/react/useMemo) Hooks will create/re-access a memorized value from a function call, re-running the function only when dependencies passed as the 2nd parameter are changed. The result of calling the Hook is inferred from the return value from the function in the first parameter. You can be more explicit by providing a type argument to the Hook. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ```ts // Type dari visibleTodos disimpulkan dari nilai kembalian filterTodos @@ -339,7 +379,17 @@ const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]); ### `useCallback` {/*typing-usecallback*/} +<<<<<<< HEAD [`useCallback`](/reference/react/useCallback) menyediakan referensi stabil ke suatu fungsi selama dependensi yang dimasukkan ke parameter kedua sama. Seperti `useMemo`, *type* fungsi disimpulkan dari nilai kembalian fungsi di parameter pertama, dan Anda dapat lebih eksplisit dengan memberikan argumen *type* ke Hook. +======= +<Note> + +[React Compiler](/learn/react-compiler) automatically memoizes values and functions, reducing the need for manual `useCallback` calls. You can use the compiler to handle memoization automatically. + +</Note> + +The [`useCallback`](/reference/react/useCallback) provide a stable reference to a function as long as the dependencies passed into the second parameter are the same. Like `useMemo`, the function's type is inferred from the return value of the function in the first parameter, and you can be more explicit by providing a type argument to the Hook. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ```ts @@ -350,7 +400,11 @@ const handleClick = useCallback(() => { Saat bekerja dalam mode *strict* TypeScript, `useCallback` mengharuskan penambahan *type* untuk parameter dalam *callback* Anda. Hal ini karena *type* dari *callback* disimpulkan dari nilai pengembalian fungsi, dan tanpa parameter, *type* tersebut tidak dapat dipahami sepenuhnya. +<<<<<<< HEAD Bergantung pada preferensi gaya kode Anda, Anda dapat menggunakan fungsi `*EventHandler` dari *type* React untuk menyediakan *type* bagi *event handler* pada saat yang sama saat mendefinisikan *callback*: +======= +Depending on your code-style preferences, you could use the `*EventHandler` functions from the React types to provide the type for the event handler at the same time as defining the callback: +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 ```ts import { useState, useCallback } from 'react'; @@ -361,7 +415,7 @@ export default function Form() { const handleChange = useCallback<React.ChangeEventHandler<HTMLInputElement>>((event) => { setValue(event.currentTarget.value); }, [setValue]) - + return ( <> <input value={value} onChange={handleChange} /> @@ -433,7 +487,11 @@ interface ModalRendererProps { } ``` +<<<<<<< HEAD Perlu diingat, bahwa Anda tidak dapat menggunakan TypeScript untuk menjelaskan bahwa anak dari komponen adalah tipe elemen JSX tertentu, jadi Anda tidak dapat menggunakan sistem *type* untuk menjelaskan komponen yang hanya menerima anak `<li>`. +======= +Note, that you cannot use TypeScript to describe that the children are a certain type of JSX elements, so you cannot use the type-system to describe a component which only accepts `<li>` children. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Anda dapat melihat contoh `React.ReactNode` dan `React.ReactElement` dengan pemeriksa *type* di [*playground* TypeScript ini](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSB6CxYmAOmXRgDkIATJOdNJMGAZzgwAFpxAR+8YADswAVwGkZMJFEzpOjDKw4AFHGEEBvUnDhphwADZsi0gFw0mDWjqQBuUgF9yaCNMlENzgAXjgACjADfkctFnYkfQhDAEpQgD44AB42YAA3dKMo5P46C2tbJGkvLIpcgt9-QLi3AEEwMFCItJDMrPTTbIQ3dKywdIB5aU4kKyQQKpha8drhhIGzLLWODbNs3b3s8YAxKBQAcwXpAThMaGWDvbH0gFloGbmrgQfBzYpd1YjQZbEYARkB6zMwO2SHSAAlZlYIBCdtCRkZpHIrFYahQYQD8UYYFA5EhcfjyGYqHAXnJAsIUHlOOUbHYhMIIHJzsI0Qk4P9SLUBuRqXEXEwAKKfRZcNA8PiCfxWACecAAUgBlAAacFm80W-CU11U6h4TgwUv11yShjgJjMLMqDnN9Dilq+nh8pD8AXgCHdMrCkWisVoAet0R6fXqhWKhjKllZVVxMcavpd4Zg7U6Qaj+2hmdG4zeRF10uu-Aeq0LBfLMEe-V+T2L7zLVu+FBWLdLeq+lc7DYFf39deFVOotMCACNOCh1dq219a+30uC8YWoZsRyuEdjkevR8uvoVMdjyTWt4WiSSydXD4NqZP4AymeZE072ZzuUeZQKheQgA). 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 aeb70ee9c4..b22ec28f58 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,11 @@ React, dan banyak library antarmuka pengguna (UI) lainnya, memodelkan antarmuka ## UI Anda sebagai pohon {/*your-ui-as-a-tree*/} +<<<<<<< HEAD Pohon adalah model hubungan antara setiap bagian (*item*) dan UI yang sering direpresentasikan dengan menggunakan struktur pohon. Sebagai contoh, Peramban (*browser*) menggunakan struktur pohon untuk memodelkan HTML ([DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction)) dan CSS ([CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model)). Platform seluler (*mobile*) juga menggunakan pohon untuk merepresentasikan hierarki tampilan mereka. +======= +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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 <Diagram name="preserving_state_dom_tree" height={193} width={864} alt="Diagram dengan tiga bagian yang disusun secara horizontal. Pada bagian pertama, terdapat tiga persegi panjang yang ditumpuk secara vertikal, dengan label 'Komponen A', 'Komponen B', dan 'Komponen C'. Transisi ke panel berikutnya adalah sebuah panah dengan logo React di bagian atas yang berlabel 'React'. Bagian tengah berisi sebuah pohon komponen, dengan akar berlabel 'A' dan dua komponen anak berlabel 'B' dan 'C'. Bagian selanjutnya ditransisikan lagi menggunakan panah dengan logo React di bagian atas berlabel 'React DOM'. Bagian ketiga dan terakhir adalah *wireframe* dari sebuah peramban, yang berisi sebuah pohon dengan 8 *node*, yang hanya memiliki sebuah bagian yang disorot (mengindikasikan subpohon dari bagian tengah)."> diff --git a/src/content/learn/updating-objects-in-state.md b/src/content/learn/updating-objects-in-state.md index 430779a463..14f3ebf0fe 100644 --- a/src/content/learn/updating-objects-in-state.md +++ b/src/content/learn/updating-objects-in-state.md @@ -56,7 +56,7 @@ Berikut adalah contoh kode yang menampung objek di dalam *state* untuk mereprese <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [11]}} import { useState } from 'react'; export default function MovingDot() { @@ -209,7 +209,7 @@ Bidang isian berikut tidak bekerja karena *handler* `onChange` mengubah *state*: <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [11, 15, 19]}} import { useState } from 'react'; export default function Form() { @@ -831,7 +831,7 @@ Tugas Anda adalah memperbaiki semua kesalahan tersebut. Saat Anda memperbaikinya <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [11]}} import { useState } from 'react'; export default function Scoreboard() { @@ -988,7 +988,7 @@ Jika sesuatu berubah secara tidak terduga, maka ada mutasi. Cari mutasi di `App. <Sandpack> -```js src/App.js +```js {expectedErrors: {'react-compiler': [17]}} src/App.js import { useState } from 'react'; import Background from './Background.js'; import Box from './Box.js'; @@ -1293,7 +1293,7 @@ Berikut adalah contoh bermasalah yang sama dengan tantangan sebelumnya. Kali ini <Sandpack> -```js src/App.js +```js {expectedErrors: {'react-compiler': [18]}} src/App.js import { useState } from 'react'; import { useImmer } from 'use-immer'; import Background from './Background.js'; 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 5342a27eda..13bbfb7614 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,11 @@ Ada dua kasus umum di mana Anda tidak memerlukan *Effects*: * **Anda tidak memerlukan *Effects* untuk melakukan transformasi data untuk *rendering*.** Sebagai contoh, katakanlah Anda ingin melakukan *filter* terhadap sebuah daftar sebelum menampiklannya. Anda mungkin merasa tergoda untuk menulis *Effect* yang memperbarui variabel *state* ketika daftar berubah. Akan tetapi, hal ini tidak efisien. Ketika Anda memperbarui *state*, React akan memanggil fungsi komponen Anda terlebih dahulu untuk menghitung apa yang seharusnya ada di layar. Kemudian React akan ["*commit*"](/learn/render-and-commit) perubahan ini ke DOM, memperbarui layar. Kemudian React akan menjalankan *Effect* Anda. Jika *Effect* Anda *juga* segera memperbarui state, ini akan mengulang seluruh proses dari awal! Untuk menghindari *render pass* yang tidak perlu, ubah semua data pada tingkat teratas komponen Anda. Kode tersebut akan secara otomatis dijalankan ulang setiap kali *props* atau *state* anda berubah. * **Anda tidak memerlukan Efek untuk menangani *event* dari pengguna.** Sebagai contoh, katakanlah Anda ingin mengirim *request* POST `/api/buy` dan menampilkan notifikasi ketika pengguna membeli produk. Di *event handler* klik tombol Beli, Anda tahu persis apa yang terjadi. Pada saat *Effect* berjalan, Anda tidak tahu *apa* yang dilakukan pengguna (misalnya, tombol mana yang diklik). Inilah sebabnya mengapa Anda biasanya akan menangani *event* pengguna di *event handler* yang sesuai. +<<<<<<< HEAD Anda *memang* membutuhkan Effect untuk [melakukan sinkronisasi](/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events) dengan sistem eksternal. dengan sistem eksternal. Sebagai contoh, Anda dapat menulis sebuah *Effect* yang membuat *widget* jQuery tetap tersinkronisasi dengan *state* React. Anda juga dapat mengambil data dengan *Effect*: sebagai contoh, Anda dapat menyinkronkan hasil pencarian dengan kueri pencarian saat ini. Perlu diingat bahwa [kerangka kerja (*framework*)](/learn/start-a-new-react-project#production-grade-react-frameworks) modern menyediakan mekanisme pengambilan data bawaan yang lebih efisien daripada menulis *Effect* secara langsung di dalam komponen Anda. +======= +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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Untuk membantu Anda mendapatkan intuisi yang tepat, mari kita lihat beberapa contoh konkret yang umum! @@ -34,7 +38,7 @@ Untuk membantu Anda mendapatkan intuisi yang tepat, mari kita lihat beberapa con Katakanlah Anda memiliki komponen dengan dua variabel *state*: `firstName` dan `lastName`. Anda ingin mendapatkan `fullName` dengan menggabungkan keduanya. Selain itu, Anda ingin `fullName` diperbarui setiap kali `firstName` atau `lastName` berubah. Naluri pertama Anda mungkin menambahkan variabel *state* `fullName` dan memperbaruinya di *Effect*: -```js {5-9} +```js {expectedErrors: {'react-compiler': [8]}} {5-9} function Form() { const [firstName, setFirstName] = useState('Taylor'); const [lastName, setLastName] = useState('Swift'); @@ -66,7 +70,7 @@ function Form() { Komponen ini menghitung `visibleTodos` dengan mengambil `todos` yang diterimanya berdasarkan *props* dan memfilternya berdasarkan prop `filter`. Anda mungkin tergoda untuk menyimpan hasilnya dalam keadaan dan memperbaruinya dari *Effect*: -```js {4-8} +```js {expectedErrors: {'react-compiler': [7]}} {4-8} function TodoList({ todos, filter }) { const [newTodo, setNewTodo] = useState(''); @@ -95,6 +99,12 @@ Biasanya, kode ini baik-baik saja! Namun mungkin `getFilteredTodos()` lambat ata Anda dapat melakukan *cache* (atau ["memoisasi"](https://en.wikipedia.org/wiki/Memoization)) perhitungan yang mahal dengan membungkusnya dalam Hook [`useMemo`](/reference/react/useMemo): +<Note> + +[React Compiler](/learn/react-compiler) can automatically memoize expensive calculations for you, eliminating the need for manual `useMemo` in many cases. + +</Note> + ```js {5-8} import { useMemo, useState } from 'react'; @@ -159,7 +169,7 @@ Perhatikan juga bahwa mengukur kinerja dalam mode pengembangan tidak akan member Komponen `ProfilePage` ini menerima *prop* `userId`. Halaman tersebut berisi *input* komentar, dan Anda menggunakan variabel *state* `comment` untuk menyimpan nilainya. Suatu hari, Anda melihat masalah: saat Anda bernavigasi dari satu profil ke profil lainnya, *state* `comment` tidak disetel ulang. Akibatnya, Anda dapat dengan mudah mengirim komentar ke profil pengguna yang salah secara tidak sengaja. Untuk memperbaiki masalah ini, Anda ingin menghapus variabel *state* `comment` setiap kali `userId` berubah: -```js {4-7} +```js {expectedErrors: {'react-compiler': [6]}} {4-7} export default function ProfilePage({ userId }) { const [comment, setComment] = useState(''); @@ -202,7 +212,7 @@ Terkadang, Anda mungkin ingin menyetel ulang atau menyesuaikan sebagian *state* Komponen `List` ini menerima *list* `item` sebagai *prop*, dan mempertahankan item yang dipilih dalam variabel *state* `selection`. Anda ingin menyetel ulang `selection` ke `null` setiap kali prop `items` menerima senarai yang berbeda: -```js {5-8} +```js {expectedErrors: {'react-compiler': [7]}} {5-8} function List({ items }) { const [isReverse, setIsReverse] = useState(false); const [selection, setSelection] = useState(null); @@ -431,7 +441,7 @@ function Game() { // βœ… Hitung keseluruhan state selanjutnya dalam event handler setCard(nextCard); if (nextCard.gold) { - if (goldCardCount <= 3) { + if (goldCardCount < 3) { setGoldCardCount(goldCardCount + 1); } else { setGoldCardCount(0); @@ -750,7 +760,11 @@ function SearchResults({ query }) { Hal ini memastikan bahwa saat *Effect* Anda mengambil data, semua respons kecuali yang terakhir diminta akan diabaikan. +<<<<<<< HEAD Menangani *race condition* bukan satu-satunya kesulitan dalam mengimplementasikan pengambilan data. Anda mungkin juga ingin memikirkan tentang *cache* terhadap respons (sehingga pengguna dapat mengeklik Kembali dan langsung melihat layar sebelumnya), cara mengambil data di server (sehingga HTML awal yang di-*render* oleh server berisi konten yang diambil, bukan *spinner*), dan cara menghindari air terjun jaringan (*network waterfalls*) (sehingga komponen anak dapat mengambil data tanpa menunggu induknya). +======= +**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.** +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 **Masalah ini berlaku untuk semua perpustakaan UI, bukan hanya React. Menyelesaikannya bukanlah hal yang sepele, itulah sebabnya [kerangka kerja](/learn/start-a-new-react-project#production-grade-react-frameworks) modern menyediakan mekanisme pengambilan data bawaan yang lebih efisien daripada mengambil data di *Effect*.** @@ -815,7 +829,7 @@ Sederhanakan komponen ini dengan menghapus semua *state* dan *Effect* yang tidak <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [12, 16, 20]}} import { useState, useEffect } from 'react'; import { initialTodos, createTodo } from './todos.js'; @@ -1018,7 +1032,7 @@ Salah satu solusinya adalah menambahkan panggilan `useMemo` untuk menyimpan *cac <Sandpack> -```js +```js {expectedErrors: {'react-compiler': [11]}} import { useState, useEffect } from 'react'; import { initialTodos, createTodo, getVisibleTodos } from './todos.js'; @@ -1359,7 +1373,7 @@ export default function ContactList({ } ``` -```js src/EditContact.js active +```js {expectedErrors: {'react-compiler': [8, 9]}} src/EditContact.js active import { useState, useEffect } from 'react'; export default function EditContact({ savedContact, onSave }) { diff --git a/src/content/learn/your-first-component.md b/src/content/learn/your-first-component.md index 839ee9669c..fecc1723ca 100644 --- a/src/content/learn/your-first-component.md +++ b/src/content/learn/your-first-component.md @@ -215,7 +215,11 @@ Aplikasi React Anda dimulai dari suatu komponen "*root*". Biasanya, itu dibuat s Sebagian besar aplikasi React menggunakan komponen sampai ke bawah. Ini berarti Anda tidak akan hanya menggunakan komponen untuk bagian-bagian yang dapat digunakan kembali seperti tombol, tetapi juga bagian-bagian yang lebih besar seperti *sidebar*, daftar, dan juga, halaman lengkap! Komponen adalah sebuah cara yang praktis untuk mengorganisir kode UI dan *markup*, bahkan jika beberapa darinya hanya digunakan sekali. +<<<<<<< HEAD [*Framework-framework* berbasis React](/learn/start-a-new-react-project) mengambil ini selangkah lebih jauh. Daripada menggunakan sebuah *file* HTML yang kosong dan membiarkan React untuk "mengambil alih" dalam mengelola halamannya dengan JavaScript, mereka *juga* membuat HTML-nya secara otomatis dari komponen-komponen React Anda. Ini memungkinkan aplikasi Anda menampilkan beberapa konten sebelum kode JavaScript dimuat. +======= +[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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Namun, banyak *website* hanya menggunakan React untuk [menambahkan interaktivitas kepada halaman HTML yang sudah ada.](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page) Mereka memiliki banya komponen *root* daripada satu untuk seluruh halaman. Anda dapat menggunakan React sebanyaknya-banyaknyaβ€”atau sesedikit mungkinβ€”sesuai dengan yang dibutuhkan. 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 0000000000..dc2912da21 --- /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 new file mode 100644 index 0000000000..b3a16bc370 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/index.md @@ -0,0 +1,40 @@ +--- +title: eslint-plugin-react-hooks +version: rc +--- + +<Intro> + +`eslint-plugin-react-hooks` provides ESLint rules to enforce the [Rules of React](/reference/rules). + +</Intro> + +This plugin helps you catch violations of React's rules at build time, ensuring your components and hooks follow React's rules for correctness and performance. The lints cover both fundamental React patterns (exhaustive-deps and rules-of-hooks) and issues flagged by React Compiler. React Compiler diagnostics are automatically surfaced by this ESLint plugin, and can be used even if your app hasn't adopted the compiler yet. + +<Note> +When the compiler reports a diagnostic, it means that the compiler was able to statically detect a pattern that is not supported or breaks the Rules of React. When it detects this, it **automatically** skips over those components and hooks, while keeping the rest of your app compiled. This ensures optimal coverage of safe optimizations that won't break your app. + +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> + +## Recommended Rules {/*recommended*/} + +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 +* [`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 +* [`incompatible-library`](/reference/eslint-plugin-react-hooks/lints/incompatible-library) - Validates against usage of libraries which are incompatible with memoization +* [`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 +* [`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 +* [`unsupported-syntax`](/reference/eslint-plugin-react-hooks/lints/unsupported-syntax) - Validates against syntax that React Compiler does not support +* [`use-memo`](/reference/eslint-plugin-react-hooks/lints/use-memo) - Validates usage of the `useMemo` hook without a return value \ No newline at end of file diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/component-hook-factories.md b/src/content/reference/eslint-plugin-react-hooks/lints/component-hook-factories.md new file mode 100644 index 0000000000..537903abdd --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/component-hook-factories.md @@ -0,0 +1,102 @@ +--- +title: component-hook-factories +--- + +<Intro> + +Validates against higher order functions defining nested components or hooks. Components and hooks should be defined at the module level. + +</Intro> + +## Rule Details {/*rule-details*/} + +Defining components or hooks inside other functions creates new instances on every call. React treats each as a completely different component, destroying and recreating the entire component tree, losing all state, and causing performance problems. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js {expectedErrors: {'react-compiler': [14]}} +// ❌ Factory function creating components +function createComponent(defaultValue) { + return function Component() { + // ... + }; +} + +// ❌ Component defined inside component +function Parent() { + function Child() { + // ... + } + + return <Child />; +} + +// ❌ Hook factory function +function createCustomHook(endpoint) { + return function useData() { + // ... + }; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Component defined at module level +function Component({ defaultValue }) { + // ... +} + +// βœ… Custom hook at module level +function useData(endpoint) { + // ... +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I need dynamic component behavior {/*dynamic-behavior*/} + +You might think you need a factory to create customized components: + +```js +// ❌ Wrong: Factory pattern +function makeButton(color) { + return function Button({children}) { + return ( + <button style={{backgroundColor: color}}> + {children} + </button> + ); + }; +} + +const RedButton = makeButton('red'); +const BlueButton = makeButton('blue'); +``` + +Pass [JSX as children](/learn/passing-props-to-a-component#passing-jsx-as-children) instead: + +```js +// βœ… Better: Pass JSX as children +function Button({color, children}) { + return ( + <button style={{backgroundColor: color}}> + {children} + </button> + ); +} + +function App() { + return ( + <> + <Button color="red">Red</Button> + <Button color="blue">Blue</Button> + </> + ); +} +``` diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/config.md b/src/content/reference/eslint-plugin-react-hooks/lints/config.md new file mode 100644 index 0000000000..719e08412e --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/config.md @@ -0,0 +1,90 @@ +--- +title: config +--- + +<Intro> + +Validates the compiler [configuration options](/reference/react-compiler/configuration). + +</Intro> + +## Rule Details {/*rule-details*/} + +React Compiler accepts various [configuration options](/reference/react-compiler/configuration) to control its behavior. This rule validates that your configuration uses correct option names and value types, preventing silent failures from typos or incorrect settings. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Unknown option name +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + compileMode: 'all' // Typo: should be compilationMode + }] + ] +}; + +// ❌ Invalid option value +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + compilationMode: 'everything' // Invalid: use 'all' or 'infer' + }] + ] +}; +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Valid compiler configuration +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + compilationMode: 'infer', + panicThreshold: 'critical_errors' + }] + ] +}; +``` + +## Troubleshooting {/*troubleshooting*/} + +### Configuration not working as expected {/*config-not-working*/} + +Your compiler configuration might have typos or incorrect values: + +```js +// ❌ Wrong: Common configuration mistakes +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + // Typo in option name + compilationMod: 'all', + // Wrong value type + panicThreshold: true, + // Unknown option + optimizationLevel: 'max' + }] + ] +}; +``` + +Check the [configuration documentation](/reference/react-compiler/configuration) for valid options: + +```js +// βœ… Better: Valid configuration +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + compilationMode: 'all', // or 'infer' + panicThreshold: 'none', // or 'critical_errors', 'all_errors' + // Only use documented options + }] + ] +}; +``` diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/error-boundaries.md b/src/content/reference/eslint-plugin-react-hooks/lints/error-boundaries.md new file mode 100644 index 0000000000..830098e5be --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/error-boundaries.md @@ -0,0 +1,72 @@ +--- +title: error-boundaries +--- + +<Intro> + +Validates usage of Error Boundaries instead of try/catch for errors in child components. + +</Intro> + +## Rule Details {/*rule-details*/} + +Try/catch blocks can't catch errors that happen during React's rendering process. Errors thrown in rendering methods or hooks bubble up through the component tree. Only [Error Boundaries](/reference/react/Component#catching-rendering-errors-with-an-error-boundary) can catch these errors. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js {expectedErrors: {'react-compiler': [4]}} +// ❌ Try/catch won't catch render errors +function Parent() { + try { + return <ChildComponent />; // If this throws, catch won't help + } catch (error) { + return <div>Error occurred</div>; + } +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Using error boundary +function Parent() { + return ( + <ErrorBoundary> + <ChildComponent /> + </ErrorBoundary> + ); +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### Why is the linter telling me not to wrap `use` in `try`/`catch`? {/*why-is-the-linter-telling-me-not-to-wrap-use-in-trycatch*/} + +The `use` hook doesn't throw errors in the traditional sense, it suspends component execution. When `use` encounters a pending promise, it suspends the component and lets React show a fallback. Only Suspense and Error Boundaries can handle these cases. The linter warns against `try`/`catch` around `use` to prevent confusion as the `catch` block would never run. + +```js {expectedErrors: {'react-compiler': [5]}} +// ❌ Try/catch around `use` hook +function Component({promise}) { + try { + const data = use(promise); // Won't catch - `use` suspends, not throws + return <div>{data}</div>; + } catch (error) { + return <div>Failed to load</div>; // Unreachable + } +} + +// βœ… Error boundary catches `use` errors +function App() { + return ( + <ErrorBoundary fallback={<div>Failed to load</div>}> + <Suspense fallback={<div>Loading...</div>}> + <DataComponent promise={fetchData()} /> + </Suspense> + </ErrorBoundary> + ); +} +``` \ No newline at end of file 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 new file mode 100644 index 0000000000..daa7db6a81 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/exhaustive-deps.md @@ -0,0 +1,169 @@ +--- +title: exhaustive-deps +--- + +<Intro> + +Validates that dependency arrays for React hooks contain all necessary dependencies. + +</Intro> + +## Rule Details {/*rule-details*/} + +React hooks like `useEffect`, `useMemo`, and `useCallback` accept dependency arrays. When a value referenced inside these hooks isn't included in the dependency array, React won't re-run the effect or recalculate the value when that dependency changes. This causes stale closures where the hook uses outdated values. + +## Common Violations {/*common-violations*/} + +This error often happens when you try to "trick" React about dependencies to control when an effect runs. Effects should synchronize your component with external systems. The dependency array tells React which values the effect uses, so React knows when to re-synchronize. + +If you find yourself fighting with the linter, you likely need to restructure your code. See [Removing Effect Dependencies](/learn/removing-effect-dependencies) to learn how. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Missing dependency +useEffect(() => { + console.log(count); +}, []); // Missing 'count' + +// ❌ Missing prop +useEffect(() => { + fetchUser(userId); +}, []); // Missing 'userId' + +// ❌ Incomplete dependencies +useMemo(() => { + return items.sort(sortOrder); +}, [items]); // Missing 'sortOrder' +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… All dependencies included +useEffect(() => { + console.log(count); +}, [count]); + +// βœ… All dependencies included +useEffect(() => { + fetchUser(userId); +}, [userId]); +``` + +## Troubleshooting {/*troubleshooting*/} + +### Adding a function dependency causes infinite loops {/*function-dependency-loops*/} + +You have an effect, but you're creating a new function on every render: + +```js +// ❌ Causes infinite loop +const logItems = () => { + console.log(items); +}; + +useEffect(() => { + logItems(); +}, [logItems]); // Infinite loop! +``` + +In most cases, you don't need the effect. Call the function where the action happens instead: + +```js +// βœ… Call it from the event handler +const logItems = () => { + console.log(items); +}; + +return <button onClick={logItems}>Log</button>; + +// βœ… Or derive during render if there's no side effect +items.forEach(item => { + console.log(item); +}); +``` + +If you genuinely need the effect (for example, to subscribe to something external), make the dependency stable: + +```js +// βœ… useCallback keeps the function reference stable +const logItems = useCallback(() => { + console.log(items); +}, [items]); + +useEffect(() => { + logItems(); +}, [logItems]); + +// βœ… Or move the logic straight into the effect +useEffect(() => { + console.log(items); +}, [items]); +``` + +### Running an effect only once {/*effect-on-mount*/} + +You want to run an effect once on mount, but the linter complains about missing dependencies: + +```js +// ❌ Missing dependency +useEffect(() => { + sendAnalytics(userId); +}, []); // Missing 'userId' +``` + +Either include the dependency (recommended) or use a ref if you truly need to run once: + +```js +// βœ… Include dependency +useEffect(() => { + sendAnalytics(userId); +}, [userId]); + +// βœ… Or use a ref guard inside an effect +const sent = useRef(false); + +useEffect(() => { + if (sent.current) { + return; + } + + sent.current = true; + sendAnalytics(userId); +}, [userId]); +``` + +## 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 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 +{ + "rules": { + "react-hooks/exhaustive-deps": ["warn", { + "additionalHooks": "(useMyCustomHook|useAnotherHook)" + }] + } +} +``` + +- `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/gating.md b/src/content/reference/eslint-plugin-react-hooks/lints/gating.md new file mode 100644 index 0000000000..3bd662a86e --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/gating.md @@ -0,0 +1,72 @@ +--- +title: gating +--- + +<Intro> + +Validates configuration of [gating mode](/reference/react-compiler/gating). + +</Intro> + +## Rule Details {/*rule-details*/} + +Gating mode lets you gradually adopt React Compiler by marking specific components for optimization. This rule ensures your gating configuration is valid so the compiler knows which components to process. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Missing required fields +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + gating: { + importSpecifierName: '__experimental_useCompiler' + // Missing 'source' field + } + }] + ] +}; + +// ❌ Invalid gating type +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + gating: '__experimental_useCompiler' // Should be object + }] + ] +}; +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Complete gating configuration +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + gating: { + importSpecifierName: 'isCompilerEnabled', // exported function name + source: 'featureFlags' // module name + } + }] + ] +}; + +// featureFlags.js +export function isCompilerEnabled() { + // ... +} + +// βœ… No gating (compile everything) +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + // No gating field - compiles all components + }] + ] +}; +``` diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/globals.md b/src/content/reference/eslint-plugin-react-hooks/lints/globals.md new file mode 100644 index 0000000000..fe0cbe0080 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/globals.md @@ -0,0 +1,84 @@ +--- +title: globals +--- + +<Intro> + +Validates against assignment/mutation of globals during render, part of ensuring that [side effects must run outside of render](/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render). + +</Intro> + +## Rule Details {/*rule-details*/} + +Global variables exist outside React's control. When you modify them during render, you break React's assumption that rendering is pure. This can cause components to behave differently in development vs production, break Fast Refresh, and make your app impossible to optimize with features like React Compiler. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Global counter +let renderCount = 0; +function Component() { + renderCount++; // Mutating global + return <div>Count: {renderCount}</div>; +} + +// ❌ Modifying window properties +function Component({userId}) { + window.currentUser = userId; // Global mutation + return <div>User: {userId}</div>; +} + +// ❌ Global array push +const events = []; +function Component({event}) { + events.push(event); // Mutating global array + return <div>Events: {events.length}</div>; +} + +// ❌ Cache manipulation +const cache = {}; +function Component({id}) { + if (!cache[id]) { + cache[id] = fetchData(id); // Modifying cache during render + } + return <div>{cache[id]}</div>; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Use state for counters +function Component() { + const [clickCount, setClickCount] = useState(0); + + const handleClick = () => { + setClickCount(c => c + 1); + }; + + return ( + <button onClick={handleClick}> + Clicked: {clickCount} times + </button> + ); +} + +// βœ… Use context for global values +function Component() { + const user = useContext(UserContext); + return <div>User: {user.id}</div>; +} + +// βœ… Synchronize external state with React +function Component({title}) { + useEffect(() => { + document.title = title; // OK in effect + }, [title]); + + return <div>Page: {title}</div>; +} +``` diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/immutability.md b/src/content/reference/eslint-plugin-react-hooks/lints/immutability.md new file mode 100644 index 0000000000..2314cde064 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/immutability.md @@ -0,0 +1,161 @@ +--- +title: immutability +--- + +<Intro> + +Validates against mutating props, state, and other values that [are immutable](/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable). + +</Intro> + +## Rule Details {/*rule-details*/} + +A component’s props and state are immutable snapshots. Never mutate them directly. Instead, pass new props down, and use the setter function from `useState`. + +## Common Violations {/*common-violations*/} + +### Invalid {/*invalid*/} + +```js +// ❌ Array push mutation +function Component() { + const [items, setItems] = useState([1, 2, 3]); + + const addItem = () => { + items.push(4); // Mutating! + setItems(items); // Same reference, no re-render + }; +} + +// ❌ Object property assignment +function Component() { + const [user, setUser] = useState({name: 'Alice'}); + + const updateName = () => { + user.name = 'Bob'; // Mutating! + setUser(user); // Same reference + }; +} + +// ❌ Sort without spreading +function Component() { + const [items, setItems] = useState([3, 1, 2]); + + const sortItems = () => { + setItems(items.sort()); // sort mutates! + }; +} +``` + +### Valid {/*valid*/} + +```js +// βœ… Create new array +function Component() { + const [items, setItems] = useState([1, 2, 3]); + + const addItem = () => { + setItems([...items, 4]); // New array + }; +} + +// βœ… Create new object +function Component() { + const [user, setUser] = useState({name: 'Alice'}); + + const updateName = () => { + setUser({...user, name: 'Bob'}); // New object + }; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I need to add items to an array {/*add-items-array*/} + +Mutating arrays with methods like `push()` won't trigger re-renders: + +```js +// ❌ Wrong: Mutating the array +function TodoList() { + const [todos, setTodos] = useState([]); + + const addTodo = (id, text) => { + todos.push({id, text}); + setTodos(todos); // Same array reference! + }; + + return ( + <ul> + {todos.map(todo => <li key={todo.id}>{todo.text}</li>)} + </ul> + ); +} +``` + +Create a new array instead: + +```js +// βœ… Better: Create a new array +function TodoList() { + const [todos, setTodos] = useState([]); + + const addTodo = (id, text) => { + setTodos([...todos, {id, text}]); + // Or: setTodos(todos => [...todos, {id: Date.now(), text}]) + }; + + return ( + <ul> + {todos.map(todo => <li key={todo.id}>{todo.text}</li>)} + </ul> + ); +} +``` + +### I need to update nested objects {/*update-nested-objects*/} + +Mutating nested properties doesn't trigger re-renders: + +```js +// ❌ Wrong: Mutating nested object +function UserProfile() { + const [user, setUser] = useState({ + name: 'Alice', + settings: { + theme: 'light', + notifications: true + } + }); + + const toggleTheme = () => { + user.settings.theme = 'dark'; // Mutation! + setUser(user); // Same object reference + }; +} +``` + +Spread at each level that needs updating: + +```js +// βœ… Better: Create new objects at each level +function UserProfile() { + const [user, setUser] = useState({ + name: 'Alice', + settings: { + theme: 'light', + notifications: true + } + }); + + const toggleTheme = () => { + setUser({ + ...user, + settings: { + ...user.settings, + theme: 'dark' + } + }); + }; +} +``` \ No newline at end of file diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/incompatible-library.md b/src/content/reference/eslint-plugin-react-hooks/lints/incompatible-library.md new file mode 100644 index 0000000000..e057e1978d --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/incompatible-library.md @@ -0,0 +1,138 @@ +--- +title: incompatible-library +--- + +<Intro> + +Validates against usage of libraries which are incompatible with memoization (manual or automatic). + +</Intro> + +<Note> + +These libraries were designed before React's memoization rules were fully documented. They made the correct choices at the time to optimize for ergonomic ways to keep components just the right amount of reactive as app state changes. While these legacy patterns worked, we have since discovered that it's incompatible with React's programming model. We will continue working with library authors to migrate these libraries to use patterns that follow the Rules of React. + +</Note> + +## Rule Details {/*rule-details*/} + +Some libraries use patterns that aren't supported by React. When the linter detects usages of these APIs from a [known list](https://github.com/facebook/react/blob/main/compiler/packages/babel-plugin-react-compiler/src/HIR/DefaultModuleTypeProvider.ts), it flags them under this rule. This means that React Compiler can automatically skip over components that use these incompatible APIs, in order to avoid breaking your app. + +```js +// Example of how memoization breaks with these libraries +function Form() { + const { watch } = useForm(); + + // ❌ This value will never update, even when 'name' field changes + const name = useMemo(() => watch('name'), [watch]); + + return <div>Name: {name}</div>; // UI appears "frozen" +} +``` + +React Compiler automatically memoizes values following the Rules of React. If something breaks with manual `useMemo`, it will also break the compiler's automatic optimization. This rule helps identify these problematic patterns. + +<DeepDive> + +#### Designing APIs that follow the Rules of React {/*designing-apis-that-follow-the-rules-of-react*/} + +One question to think about when designing a library API or hook is whether calling the API can be safely memoized with `useMemo`. If it can't, then both manual and React Compiler memoizations will break your user's code. + +For example, one such incompatible pattern is "interior mutability". Interior mutability is when an object or function keeps its own hidden state that changes over time, even though the reference to it stays the same. Think of it like a box that looks the same on the outside but secretly rearranges its contents. React can't tell anything changed because it only checks if you gave it a different box, not what's inside. This breaks memoization, since React relies on the outer object (or function) changing if part of its value has changed. + +As a rule of thumb, when designing React APIs, think about whether `useMemo` would break it: + +```js +function Component() { + const { someFunction } = useLibrary(); + // it should always be safe to memoize functions like this + const result = useMemo(() => someFunction(), [someFunction]); +} +``` + +Instead, design APIs that return immutable state and use explicit update functions: + +```js +// βœ… Good: Return immutable state that changes reference when updated +function Component() { + const { field, updateField } = useLibrary(); + // this is always safe to memo + const greeting = useMemo(() => `Hello, ${field.name}!`, [field.name]); + + return ( + <div> + <input + value={field.name} + onChange={(e) => updateField('name', e.target.value)} + /> + <p>{greeting}</p> + </div> + ); +} +``` + +</DeepDive> + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ react-hook-form `watch` +function Component() { + const {watch} = useForm(); + const value = watch('field'); // Interior mutability + return <div>{value}</div>; +} + +// ❌ TanStack Table `useReactTable` +function Component({data}) { + const table = useReactTable({ + data, + columns, + getCoreRowModel: getCoreRowModel(), + }); + // table instance uses interior mutability + return <Table table={table} />; +} +``` + +<Pitfall> + +#### MobX {/*mobx*/} + +MobX patterns like `observer` also break memoization assumptions, but the linter does not yet detect them. If you rely on MobX and find that your app doesn't work with React Compiler, you may need to use the `"use no memo" directive`. + +```js +// ❌ MobX `observer` +const Component = observer(() => { + const [timer] = useState(() => new Timer()); + return <span>Seconds passed: {timer.secondsPassed}</span>; +}); +``` + +</Pitfall> + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… For react-hook-form, use `useWatch`: +function Component() { + const {register, control} = useForm(); + const watchedValue = useWatch({ + control, + name: 'field' + }); + + return ( + <> + <input {...register('field')} /> + <div>Current value: {watchedValue}</div> + </> + ); +} +``` + +Some other libraries do not yet have alternative APIs that are compatible with React's memoization model. If the linter doesn't automatically skip over your components or hooks that call these APIs, please [file an issue](https://github.com/facebook/react/issues) so we can add it to the linter. diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/preserve-manual-memoization.md b/src/content/reference/eslint-plugin-react-hooks/lints/preserve-manual-memoization.md new file mode 100644 index 0000000000..93b582b1e1 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/preserve-manual-memoization.md @@ -0,0 +1,93 @@ +--- +title: preserve-manual-memoization +--- + +<Intro> + +Validates that existing manual memoization is preserved by the compiler. React Compiler will only compile components and hooks if its inference [matches or exceeds the existing manual memoization](/learn/react-compiler/introduction#what-should-i-do-about-usememo-usecallback-and-reactmemo). + +</Intro> + +## Rule Details {/*rule-details*/} + +React Compiler preserves your existing `useMemo`, `useCallback`, and `React.memo` calls. If you've manually memoized something, the compiler assumes you had a good reason and won't remove it. However, incomplete dependencies prevent the compiler from understanding your code's data flow and applying further optimizations. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Missing dependencies in useMemo +function Component({ data, filter }) { + const filtered = useMemo( + () => data.filter(filter), + [data] // Missing 'filter' dependency + ); + + return <List items={filtered} />; +} + +// ❌ Missing dependencies in useCallback +function Component({ onUpdate, value }) { + const handleClick = useCallback(() => { + onUpdate(value); + }, [onUpdate]); // Missing 'value' + + return <button onClick={handleClick}>Update</button>; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Complete dependencies +function Component({ data, filter }) { + const filtered = useMemo( + () => data.filter(filter), + [data, filter] // All dependencies included + ); + + return <List items={filtered} />; +} + +// βœ… Or let the compiler handle it +function Component({ data, filter }) { + // No manual memoization needed + const filtered = data.filter(filter); + return <List items={filtered} />; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### Should I remove my manual memoization? {/*remove-manual-memoization*/} + +You might wonder if React Compiler makes manual memoization unnecessary: + +```js +// Do I still need this? +function Component({items, sortBy}) { + const sorted = useMemo(() => { + return [...items].sort((a, b) => { + return a[sortBy] - b[sortBy]; + }); + }, [items, sortBy]); + + return <List items={sorted} />; +} +``` + +You can safely remove it if using React Compiler: + +```js +// βœ… Better: Let the compiler optimize +function Component({items, sortBy}) { + const sorted = [...items].sort((a, b) => { + return a[sortBy] - b[sortBy]; + }); + + return <List items={sorted} />; +} +``` \ No newline at end of file diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/purity.md b/src/content/reference/eslint-plugin-react-hooks/lints/purity.md new file mode 100644 index 0000000000..af8aacc612 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/purity.md @@ -0,0 +1,83 @@ +--- +title: purity +--- + +<Intro> + +Validates that [components/hooks are pure](/reference/rules/components-and-hooks-must-be-pure) by checking that they do not call known-impure functions. + +</Intro> + +## Rule Details {/*rule-details*/} + +React components must be pure functions - given the same props, they should always return the same JSX. When components use functions like `Math.random()` or `Date.now()` during render, they produce different output each time, breaking React's assumptions and causing bugs like hydration mismatches, incorrect memoization, and unpredictable behavior. + +## Common Violations {/*common-violations*/} + +In general, any API that returns a different value for the same inputs violates this rule. Usual examples include: + +- `Math.random()` +- `Date.now()` / `new Date()` +- `crypto.randomUUID()` +- `performance.now()` + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Math.random() in render +function Component() { + const id = Math.random(); // Different every render + return <div key={id}>Content</div>; +} + +// ❌ Date.now() for values +function Component() { + const timestamp = Date.now(); // Changes every render + return <div>Created at: {timestamp}</div>; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Stable IDs from initial state +function Component() { + const [id] = useState(() => crypto.randomUUID()); + return <div key={id}>Content</div>; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I need to show the current time {/*current-time*/} + +Calling `Date.now()` during render makes your component impure: + +```js {expectedErrors: {'react-compiler': [3]}} +// ❌ Wrong: Time changes every render +function Clock() { + return <div>Current time: {Date.now()}</div>; +} +``` + +Instead, [move the impure function outside of render](/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent): + +```js +function Clock() { + const [time, setTime] = useState(() => Date.now()); + + useEffect(() => { + const interval = setInterval(() => { + setTime(Date.now()); + }, 1000); + + return () => clearInterval(interval); + }, []); + + return <div>Current time: {time}</div>; +} +``` \ No newline at end of file diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/refs.md b/src/content/reference/eslint-plugin-react-hooks/lints/refs.md new file mode 100644 index 0000000000..3108fdd89d --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/refs.md @@ -0,0 +1,115 @@ +--- +title: refs +--- + +<Intro> + +Validates correct usage of refs, not reading/writing during render. See the "pitfalls" section in [`useRef()` usage](/reference/react/useRef#usage). + +</Intro> + +## Rule Details {/*rule-details*/} + +Refs hold values that aren't used for rendering. Unlike state, changing a ref doesn't trigger a re-render. Reading or writing `ref.current` during render breaks React's expectations. Refs might not be initialized when you try to read them, and their values can be stale or inconsistent. + +## How It Detects Refs {/*how-it-detects-refs*/} + +The lint only applies these rules to values it knows are refs. A value is inferred as a ref when the compiler sees any of the following patterns: + +- Returned from `useRef()` or `React.createRef()`. + + ```js + const scrollRef = useRef(null); + ``` + +- An identifier named `ref` or ending in `Ref` that reads from or writes to `.current`. + + ```js + buttonRef.current = node; + ``` + +- Passed through a JSX `ref` prop (for example `<div ref={someRef} />`). + + ```jsx + <input ref={inputRef} /> + ``` + +Once something is marked as a ref, that inference follows the value through assignments, destructuring, or helper calls. This lets the lint surface violations even when `ref.current` is accessed inside another function that received the ref as an argument. + +## Common Violations {/*common-violations*/} + +- Reading `ref.current` during render +- Updating `refs` during render +- Using `refs` for values that should be state + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Reading ref during render +function Component() { + const ref = useRef(0); + const value = ref.current; // Don't read during render + return <div>{value}</div>; +} + +// ❌ Modifying ref during render +function Component({value}) { + const ref = useRef(null); + ref.current = value; // Don't modify during render + return <div />; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Read ref in effects/handlers +function Component() { + const ref = useRef(null); + + useEffect(() => { + if (ref.current) { + console.log(ref.current.offsetWidth); // OK in effect + } + }); + + return <div ref={ref} />; +} + +// βœ… Use state for UI values +function Component() { + const [count, setCount] = useState(0); + + return ( + <button onClick={() => setCount(count + 1)}> + {count} + </button> + ); +} + +// βœ… Lazy initialization of ref value +function Component() { + const ref = useRef(null); + + // Initialize only once on first use + if (ref.current === null) { + ref.current = expensiveComputation(); // OK - lazy initialization + } + + const handleClick = () => { + console.log(ref.current); // Use the initialized value + }; + + return <button onClick={handleClick}>Click</button>; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### The lint flagged my plain object with `.current` {/*plain-object-current*/} + +The name heuristic intentionally treats `ref.current` and `fooRef.current` as real refs. If you're modeling a custom container object, pick a different name (for example, `box`) or move the mutable value into state. Renaming avoids the lint because the compiler stops inferring it as a ref. 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 new file mode 100644 index 0000000000..a364ab67fe --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md @@ -0,0 +1,179 @@ +--- +title: rules-of-hooks +--- + +<Intro> + +Validates that components and hooks follow the [Rules of Hooks](/reference/rules/rules-of-hooks). + +</Intro> + +## Rule Details {/*rule-details*/} + +React relies on the order in which hooks are called to correctly preserve state between renders. Each time your component renders, React expects the exact same hooks to be called in the exact same order. When hooks are called conditionally or in loops, React loses track of which state corresponds to which hook call, leading to bugs like state mismatches and "Rendered fewer/more hooks than expected" errors. + +## Common Violations {/*common-violations*/} + +These patterns violate the Rules of Hooks: + +- **Hooks in conditions** (`if`/`else`, ternary, `&&`/`||`) +- **Hooks in loops** (`for`, `while`, `do-while`) +- **Hooks after early returns** +- **Hooks in callbacks/event handlers** +- **Hooks in async functions** +- **Hooks in class methods** +- **Hooks at module level** + +<Note> + +### `use` hook {/*use-hook*/} + +The `use` hook is different from other React hooks. You can call it conditionally and in loops: + +```js +// βœ… `use` can be conditional +if (shouldFetch) { + const data = use(fetchPromise); +} + +// βœ… `use` can be in loops +for (const promise of promises) { + results.push(use(promise)); +} +``` + +However, `use` still has restrictions: +- Can't be wrapped in try/catch +- Must be called inside a component or hook + +Learn more: [`use` API Reference](/reference/react/use) + +</Note> + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Hook in condition +if (isLoggedIn) { + const [user, setUser] = useState(null); +} + +// ❌ Hook after early return +if (!data) return <Loading />; +const [processed, setProcessed] = useState(data); + +// ❌ Hook in callback +<button onClick={() => { + const [clicked, setClicked] = useState(false); +}}/> + +// ❌ `use` in try/catch +try { + const data = use(promise); +} catch (e) { + // error handling +} + +// ❌ Hook at module level +const globalState = useState(0); // Outside component +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +function Component({ isSpecial, shouldFetch, fetchPromise }) { + // βœ… Hooks at top level + const [count, setCount] = useState(0); + const [name, setName] = useState(''); + + if (!isSpecial) { + return null; + } + + if (shouldFetch) { + // βœ… `use` can be conditional + const data = use(fetchPromise); + return <div>{data}</div>; + } + + return <div>{name}: {count}</div>; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I want to fetch data based on some condition {/*conditional-data-fetching*/} + +You're trying to conditionally call useEffect: + +```js +// ❌ Conditional hook +if (isLoggedIn) { + useEffect(() => { + fetchUserData(); + }, []); +} +``` + +Call the hook unconditionally, check condition inside: + +```js +// βœ… Condition inside hook +useEffect(() => { + if (isLoggedIn) { + fetchUserData(); + } +}, [isLoggedIn]); +``` + +<Note> + +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) + +</Note> + +### I need different state for different scenarios {/*conditional-state-initialization*/} + +You're trying to conditionally initialize state: + +```js +// ❌ Conditional state +if (userType === 'admin') { + const [permissions, setPermissions] = useState(adminPerms); +} else { + const [permissions, setPermissions] = useState(userPerms); +} +``` + +Always call useState, conditionally set the initial value: + +```js +// βœ… Conditional initial value +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 new file mode 100644 index 0000000000..64fa5c655a --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-effect.md @@ -0,0 +1,93 @@ +--- +title: set-state-in-effect +--- + +<Intro> + +Validates against calling setState synchronously in an effect, which can lead to re-renders that degrade performance. + +</Intro> + +## Rule Details {/*rule-details*/} + +Setting state immediately inside an effect forces React to restart the entire render cycle. When you update state in an effect, React must re-render your component, apply changes to the DOM, and then run effects again. This creates an extra render pass that could have been avoided by transforming data directly during render or deriving state from props. Transform data at the top level of your component instead. This code will naturally re-run when props or state change without triggering additional render cycles. + +Synchronous `setState` calls in effects trigger immediate re-renders before the browser can paint, causing performance issues and visual jank. React has to render twice: once to apply the state update, then again after effects run. This double rendering is wasteful when the same result could be achieved with a single render. + +In many cases, you may also not need an effect at all. Please see [You Might Not Need an Effect](/learn/you-might-not-need-an-effect) for more information. + +## Common Violations {/*common-violations*/} + +This rule catches several patterns where synchronous setState is used unnecessarily: + +- Setting loading state synchronously +- Deriving state from props in effects +- Transforming data in effects instead of render + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Synchronous setState in effect +function Component({data}) { + const [items, setItems] = useState([]); + + useEffect(() => { + setItems(data); // Extra render, use initial state instead + }, [data]); +} + +// ❌ Setting loading state synchronously +function Component() { + const [loading, setLoading] = useState(false); + + useEffect(() => { + setLoading(true); // Synchronous, causes extra render + fetchData().then(() => setLoading(false)); + }, []); +} + +// ❌ Transforming data in effect +function Component({rawData}) { + const [processed, setProcessed] = useState([]); + + useEffect(() => { + setProcessed(rawData.map(transform)); // Should derive in render + }, [rawData]); +} + +// ❌ Deriving state from props +function Component({selectedId, items}) { + const [selected, setSelected] = useState(null); + + useEffect(() => { + setSelected(items.find(i => i.id === selectedId)); + }, [selectedId, items]); +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… setState in an effect is fine if the value comes from a ref +function Tooltip() { + const ref = useRef(null); + const [tooltipHeight, setTooltipHeight] = useState(0); + + useLayoutEffect(() => { + const { height } = ref.current.getBoundingClientRect(); + setTooltipHeight(height); + }, []); +} + +// βœ… Calculate during render +function Component({selectedId, items}) { + const selected = items.find(i => i.id === selectedId); + return <div>{selected?.name}</div>; +} +``` + +**When something can be calculated from the existing props or state, don't put it in state.** Instead, calculate it during rendering. This makes your code faster, simpler, and less error-prone. Learn more in [You Might Not Need an Effect](/learn/you-might-not-need-an-effect). 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 new file mode 100644 index 0000000000..7517d5f928 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-render.md @@ -0,0 +1,110 @@ +--- +title: set-state-in-render +--- + +<Intro> + +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 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]}} +// ❌ Unconditional setState directly in render +function Component({value}) { + const [count, setCount] = useState(0); + setCount(value); // Infinite loop! + return <div>{count}</div>; +} +``` + +### Valid {/*valid*/} + +```js +// βœ… Derive during render +function Component({items}) { + const sorted = [...items].sort(); // Just calculate it in render + return <ul>{sorted.map(/*...*/)}</ul>; +} + +// βœ… Set state in event handler +function Component() { + const [count, setCount] = useState(0); + return ( + <button onClick={() => setCount(count + 1)}> + {count} + </button> + ); +} + +// βœ… Derive from props instead of setting state +function Component({user}) { + const name = user?.name || ''; + 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*/} + +### I want to sync state to a prop {/*clamp-state-to-prop*/} + +A common problem is trying to "fix" state after it renders. Suppose you want to keep a counter from exceeding a `max` prop: + +```js +// ❌ Wrong: clamps during render +function Counter({max}) { + const [count, setCount] = useState(0); + + if (count > max) { + setCount(max); + } + + return ( + <button onClick={() => setCount(count + 1)}> + {count} + </button> + ); +} +``` + +As soon as `count` exceeds `max`, an infinite loop is triggered. + +Instead, it's often better to move this logic to the event (the place where the state is first set). For example, you can enforce the maximum at the moment you update state: + +```js +// βœ… Clamp when updating +function Counter({max}) { + const [count, setCount] = useState(0); + + const increment = () => { + setCount(current => Math.min(current + 1, max)); + }; + + return <button onClick={increment}>{count}</button>; +} +``` + +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 new file mode 100644 index 0000000000..bd52f07037 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/static-components.md @@ -0,0 +1,103 @@ +--- +title: static-components +--- + +<Intro> + +Validates that components are static, not recreated every render. Components that are recreated dynamically can reset state and trigger excessive re-rendering. + +</Intro> + +## Rule Details {/*rule-details*/} + +Components defined inside other components are recreated on every render. React sees each as a brand new component type, unmounting the old one and mounting the new one, destroying all state and DOM nodes in the process. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Component defined inside component +function Parent() { + const ChildComponent = () => { // New component every render! + const [count, setCount] = useState(0); + return <button onClick={() => setCount(count + 1)}>{count}</button>; + }; + + return <ChildComponent />; // State resets every render +} + +// ❌ Dynamic component creation +function Parent({type}) { + const Component = type === 'button' + ? () => <button>Click</button> + : () => <div>Text</div>; + + return <Component />; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Components at module level +const ButtonComponent = () => <button>Click</button>; +const TextComponent = () => <div>Text</div>; + +function Parent({type}) { + const Component = type === 'button' + ? ButtonComponent // Reference existing component + : TextComponent; + + return <Component />; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I need to render different components conditionally {/*conditional-components*/} + +You might define components inside to access local state: + +```js {expectedErrors: {'react-compiler': [13]}} +// ❌ Wrong: Inner component to access parent state +function Parent() { + const [theme, setTheme] = useState('light'); + + function ThemedButton() { // Recreated every render! + return ( + <button className={theme}> + Click me + </button> + ); + } + + return <ThemedButton />; +} +``` + +Pass data as props instead: + +```js +// βœ… Better: Pass props to static component +function ThemedButton({theme}) { + return ( + <button className={theme}> + Click me + </button> + ); +} + +function Parent() { + const [theme, setTheme] = useState('light'); + return <ThemedButton theme={theme} />; +} +``` + +<Note> + +If you find yourself wanting to define components inside other components to access local variables, that's a sign you should be passing props instead. This makes components more reusable and testable. + +</Note> \ No newline at end of file diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/unsupported-syntax.md b/src/content/reference/eslint-plugin-react-hooks/lints/unsupported-syntax.md new file mode 100644 index 0000000000..a3eefcdb24 --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/unsupported-syntax.md @@ -0,0 +1,102 @@ +--- +title: unsupported-syntax +--- + +<Intro> + +Validates against syntax that React Compiler does not support. If you need to, you can still use this syntax outside of React, such as in a standalone utility function. + +</Intro> + +## Rule Details {/*rule-details*/} + +React Compiler needs to statically analyze your code to apply optimizations. Features like `eval` and `with` make it impossible to statically understand what the code does at compile time, so the compiler can't optimize components that use them. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js +// ❌ Using eval in component +function Component({ code }) { + const result = eval(code); // Can't be analyzed + return <div>{result}</div>; +} + +// ❌ Using with statement +function Component() { + with (Math) { // Changes scope dynamically + return <div>{sin(PI / 2)}</div>; + } +} + +// ❌ Dynamic property access with eval +function Component({propName}) { + const value = eval(`props.${propName}`); + return <div>{value}</div>; +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Use normal property access +function Component({propName, props}) { + const value = props[propName]; // Analyzable + return <div>{value}</div>; +} + +// βœ… Use standard Math methods +function Component() { + return <div>{Math.sin(Math.PI / 2)}</div>; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I need to evaluate dynamic code {/*evaluate-dynamic-code*/} + +You might need to evaluate user-provided code: + +```js {expectedErrors: {'react-compiler': [3]}} +// ❌ Wrong: eval in component +function Calculator({expression}) { + const result = eval(expression); // Unsafe and unoptimizable + return <div>Result: {result}</div>; +} +``` + +Use a safe expression parser instead: + +```js +// βœ… Better: Use a safe parser +import {evaluate} from 'mathjs'; // or similar library + +function Calculator({expression}) { + const [result, setResult] = useState(null); + + const calculate = () => { + try { + // Safe mathematical expression evaluation + setResult(evaluate(expression)); + } catch (error) { + setResult('Invalid expression'); + } + }; + + return ( + <div> + <button onClick={calculate}>Calculate</button> + {result && <div>Result: {result}</div>} + </div> + ); +} +``` + +<Note> + +Never use `eval` with user input - it's a security risk. Use dedicated parsing libraries for specific use cases like mathematical expressions, JSON parsing, or template evaluation. + +</Note> \ No newline at end of file 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 new file mode 100644 index 0000000000..a5a77e5f6e --- /dev/null +++ b/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md @@ -0,0 +1,94 @@ +--- +title: use-memo +--- + +<Intro> + +Validates that the `useMemo` hook is used with a return value. See [`useMemo` docs](/reference/react/useMemo) for more information. + +</Intro> + +## Rule Details {/*rule-details*/} + +`useMemo` is for computing and caching expensive values, not for side effects. Without a return value, `useMemo` returns `undefined`, which defeats its purpose and likely indicates you're using the wrong hook. + +### Invalid {/*invalid*/} + +Examples of incorrect code for this rule: + +```js {expectedErrors: {'react-compiler': [3]}} +// ❌ No return value +function Component({ data }) { + const processed = useMemo(() => { + data.forEach(item => console.log(item)); + // Missing return! + }, [data]); + + return <div>{processed}</div>; // Always undefined +} +``` + +### Valid {/*valid*/} + +Examples of correct code for this rule: + +```js +// βœ… Returns computed value +function Component({ data }) { + const processed = useMemo(() => { + return data.map(item => item * 2); + }, [data]); + + return <div>{processed}</div>; +} +``` + +## Troubleshooting {/*troubleshooting*/} + +### I need to run side effects when dependencies change {/*side-effects*/} + +You might try to use `useMemo` for side effects: + +{/* TODO(@poteto) fix compiler validation to check for unassigned useMemos */} +```js {expectedErrors: {'react-compiler': [4]}} +// ❌ Wrong: Side effects in useMemo +function Component({user}) { + // No return value, just side effect + useMemo(() => { + analytics.track('UserViewed', {userId: user.id}); + }, [user.id]); + + // Not assigned to a variable + useMemo(() => { + return analytics.track('UserViewed', {userId: user.id}); + }, [user.id]); +} +``` + +If the side effect needs to happen in response to user interaction, it's best to colocate the side effect with the event: + +```js +// βœ… Good: Side effects in event handlers +function Component({user}) { + const handleClick = () => { + analytics.track('ButtonClicked', {userId: user.id}); + // Other click logic... + }; + + return <button onClick={handleClick}>Click me</button>; +} +``` + +If the side effect sychronizes React state with some external state (or vice versa), use `useEffect`: + +```js +// βœ… Good: Synchronization in useEffect +function Component({theme}) { + useEffect(() => { + localStorage.setItem('preferredTheme', theme); + document.body.className = theme; + }, [theme]); + + return <div>Current theme: {theme}</div>; +} +``` diff --git a/src/content/reference/react-compiler/compilationMode.md b/src/content/reference/react-compiler/compilationMode.md new file mode 100644 index 0000000000..5513d1c6a6 --- /dev/null +++ b/src/content/reference/react-compiler/compilationMode.md @@ -0,0 +1,201 @@ +--- +title: compilationMode +--- + +<Intro> + +The `compilationMode` option controls how the React Compiler selects which functions to compile. + +</Intro> + +```js +{ + compilationMode: 'infer' // or 'annotation', 'syntax', 'all' +} +``` + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `compilationMode` {/*compilationmode*/} + +Controls the strategy for determining which functions the React Compiler will optimize. + +#### Type {/*type*/} + +``` +'infer' | 'syntax' | 'annotation' | 'all' +``` + +#### Default value {/*default-value*/} + +`'infer'` + +#### Options {/*options*/} + +- **`'infer'`** (default): The compiler uses intelligent heuristics to identify React components and hooks: + - Functions explicitly annotated with `"use memo"` directive + - Functions that are named like components (PascalCase) or hooks (`use` prefix) AND create JSX and/or call other hooks + +- **`'annotation'`**: Only compile functions explicitly marked with the `"use memo"` directive. Ideal for incremental adoption. + +- **`'syntax'`**: Only compile components and hooks that use Flow's [component](https://flow.org/en/docs/react/component-syntax/) and [hook](https://flow.org/en/docs/react/hook-syntax/) syntax. + +- **`'all'`**: Compile all top-level functions. Not recommended as it may compile non-React functions. + +#### Caveats {/*caveats*/} + +- The `'infer'` mode requires functions to follow React naming conventions to be detected +- Using `'all'` mode may negatively impact performance by compiling utility functions +- The `'syntax'` mode requires Flow and won't work with TypeScript +- Regardless of mode, functions with `"use no memo"` directive are always skipped + +--- + +## Usage {/*usage*/} + +### Default inference mode {/*default-inference-mode*/} + +The default `'infer'` mode works well for most codebases that follow React conventions: + +```js +{ + compilationMode: 'infer' +} +``` + +With this mode, these functions will be compiled: + +```js +// βœ… Compiled: Named like a component + returns JSX +function Button(props) { + return <button>{props.label}</button>; +} + +// βœ… Compiled: Named like a hook + calls hooks +function useCounter() { + const [count, setCount] = useState(0); + return [count, setCount]; +} + +// βœ… Compiled: Explicit directive +function expensiveCalculation(data) { + "use memo"; + return data.reduce(/* ... */); +} + +// ❌ Not compiled: Not a component/hook pattern +function calculateTotal(items) { + return items.reduce((a, b) => a + b, 0); +} +``` + +### Incremental adoption with annotation mode {/*incremental-adoption*/} + +For gradual migration, use `'annotation'` mode to only compile marked functions: + +```js +{ + compilationMode: 'annotation' +} +``` + +Then explicitly mark functions to compile: + +```js +// Only this function will be compiled +function ExpensiveList(props) { + "use memo"; + return ( + <ul> + {props.items.map(item => ( + <li key={item.id}>{item.name}</li> + ))} + </ul> + ); +} + +// This won't be compiled without the directive +function NormalComponent(props) { + return <div>{props.content}</div>; +} +``` + +### Using Flow syntax mode {/*flow-syntax-mode*/} + +If your codebase uses Flow instead of TypeScript: + +```js +{ + compilationMode: 'syntax' +} +``` + +Then use Flow's component syntax: + +```js +// Compiled: Flow component syntax +component Button(label: string) { + return <button>{label}</button>; +} + +// Compiled: Flow hook syntax +hook useCounter(initial: number) { + const [count, setCount] = useState(initial); + return [count, setCount]; +} + +// Not compiled: Regular function syntax +function helper(data) { + return process(data); +} +``` + +### Opting out specific functions {/*opting-out*/} + +Regardless of compilation mode, use `"use no memo"` to skip compilation: + +```js +function ComponentWithSideEffects() { + "use no memo"; // Prevent compilation + + // This component has side effects that shouldn't be memoized + logToAnalytics('component_rendered'); + + return <div>Content</div>; +} +``` + +--- + +## Troubleshooting {/*troubleshooting*/} + +### Component not being compiled in infer mode {/*component-not-compiled-infer*/} + +In `'infer'` mode, ensure your component follows React conventions: + +```js +// ❌ Won't be compiled: lowercase name +function button(props) { + return <button>{props.label}</button>; +} + +// βœ… Will be compiled: PascalCase name +function Button(props) { + return <button>{props.label}</button>; +} + +// ❌ Won't be compiled: doesn't create JSX or call hooks +function useData() { + return window.localStorage.getItem('data'); +} + +// βœ… Will be compiled: calls a hook +function useData() { + const [data] = useState(() => window.localStorage.getItem('data')); + return data; +} +``` diff --git a/src/content/reference/react-compiler/compiling-libraries.md b/src/content/reference/react-compiler/compiling-libraries.md new file mode 100644 index 0000000000..ec0a7581ea --- /dev/null +++ b/src/content/reference/react-compiler/compiling-libraries.md @@ -0,0 +1,106 @@ +--- +title: Compiling Libraries +--- + +<Intro> +This guide helps library authors understand how to use React Compiler to ship optimized library code to their users. +</Intro> + +<InlineToc /> + +## Why Ship Compiled Code? {/*why-ship-compiled-code*/} + +As a library author, you can compile your library code before publishing to npm. This provides several benefits: + +- **Performance improvements for all users** - Your library users get optimized code even if they aren't using React Compiler yet +- **No configuration required by users** - The optimizations work out of the box +- **Consistent behavior** - All users get the same optimized version regardless of their build setup + +## Setting Up Compilation {/*setting-up-compilation*/} + +Add React Compiler to your library's build process: + +<TerminalBlock> +npm install -D babel-plugin-react-compiler@latest +</TerminalBlock> + +Configure your build tool to compile your library. For example, with Babel: + +```js +// babel.config.js +module.exports = { + plugins: [ + 'babel-plugin-react-compiler', + ], + // ... other config +}; +``` + +## Backwards Compatibility {/*backwards-compatibility*/} + +If your library supports React versions below 19, you'll need additional configuration: + +### 1. Install the runtime package {/*install-runtime-package*/} + +We recommend installing react-compiler-runtime as a direct dependency: + +<TerminalBlock> +npm install react-compiler-runtime@latest +</TerminalBlock> + +```json +{ + "dependencies": { + "react-compiler-runtime": "^1.0.0" + }, + "peerDependencies": { + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + } +} +``` + +### 2. Configure the target version {/*configure-target-version*/} + +Set the minimum React version your library supports: + +```js +{ + target: '17', // Minimum supported React version +} +``` + +## Testing Strategy {/*testing-strategy*/} + +Test your library both with and without compilation to ensure compatibility. Run your existing test suite against the compiled code, and also create a separate test configuration that bypasses the compiler. This helps catch any issues that might arise from the compilation process and ensures your library works correctly in all scenarios. + +## Troubleshooting {/*troubleshooting*/} + +### Library doesn't work with older React versions {/*library-doesnt-work-with-older-react-versions*/} + +If your compiled library throws errors in React 17 or 18: + +1. Verify you've installed `react-compiler-runtime` as a dependency +2. Check that your `target` configuration matches your minimum supported React version +3. Ensure the runtime package is included in your published bundle + +### Compilation conflicts with other Babel plugins {/*compilation-conflicts-with-other-babel-plugins*/} + +Some Babel plugins may conflict with React Compiler: + +1. Place `babel-plugin-react-compiler` early in your plugin list +2. Disable conflicting optimizations in other plugins +3. Test your build output thoroughly + +### Runtime module not found {/*runtime-module-not-found*/} + +If users see "Cannot find module 'react-compiler-runtime'": + +1. Ensure the runtime is listed in `dependencies`, not `devDependencies` +2. Check that your bundler includes the runtime in the output +3. Verify the package is published to npm with your library + +## Next Steps {/*next-steps*/} + +- Learn about [debugging techniques](/learn/react-compiler/debugging) for compiled code +- Check the [configuration options](/reference/react-compiler/configuration) for all compiler options +- Explore [compilation modes](/reference/react-compiler/compilationMode) for selective optimization \ No newline at end of file diff --git a/src/content/reference/react-compiler/configuration.md b/src/content/reference/react-compiler/configuration.md new file mode 100644 index 0000000000..ec9b27e6f5 --- /dev/null +++ b/src/content/reference/react-compiler/configuration.md @@ -0,0 +1,151 @@ +--- +title: Configuration +--- + +<Intro> + +This page lists all configuration options available in React Compiler. + +</Intro> + +<Note> + +For most apps, the default options should work out of the box. If you have a special need, you can use these advanced options. + +</Note> + +```js +// babel.config.js +module.exports = { + plugins: [ + [ + 'babel-plugin-react-compiler', { + // compiler options + } + ] + ] +}; +``` + +--- + +## Compilation Control {/*compilation-control*/} + +These options control *what* the compiler optimizes and *how* it selects components and hooks to compile. + +* [`compilationMode`](/reference/react-compiler/compilationMode) controls the strategy for selecting functions to compile (e.g., all functions, only annotated ones, or intelligent detection). + +```js +{ + compilationMode: 'annotation' // Only compile "use memo" functions +} +``` + +--- + +## Version Compatibility {/*version-compatibility*/} + +React version configuration ensures the compiler generates code compatible with your React version. + +[`target`](/reference/react-compiler/target) specifies which React version you're using (17, 18, or 19). + +```js +// For React 18 projects +{ + target: '18' // Also requires react-compiler-runtime package +} +``` + +--- + +## Error Handling {/*error-handling*/} + +These options control how the compiler responds to code that doesn't follow the [Rules of React](/reference/rules). + +[`panicThreshold`](/reference/react-compiler/panicThreshold) determines whether to fail the build or skip problematic components. + +```js +// Recommended for production +{ + panicThreshold: 'none' // Skip components with errors instead of failing the build +} +``` + +--- + +## Debugging {/*debugging*/} + +Logging and analysis options help you understand what the compiler is doing. + +[`logger`](/reference/react-compiler/logger) provides custom logging for compilation events. + +```js +{ + logger: { + logEvent(filename, event) { + if (event.kind === 'CompileSuccess') { + console.log('Compiled:', filename); + } + } + } +} +``` + +--- + +## Feature Flags {/*feature-flags*/} + +Conditional compilation lets you control when optimized code is used. + +[`gating`](/reference/react-compiler/gating) enables runtime feature flags for A/B testing or gradual rollouts. + +```js +{ + gating: { + source: 'my-feature-flags', + importSpecifierName: 'isCompilerEnabled' + } +} +``` + +--- + +## Common Configuration Patterns {/*common-patterns*/} + +### Default configuration {/*default-configuration*/} + +For most React 19 applications, the compiler works without configuration: + +```js +// babel.config.js +module.exports = { + plugins: [ + 'babel-plugin-react-compiler' + ] +}; +``` + +### React 17/18 projects {/*react-17-18*/} + +Older React versions need the runtime package and target configuration: + +```bash +npm install react-compiler-runtime@latest +``` + +```js +{ + target: '18' // or '17' +} +``` + +### Incremental adoption {/*incremental-adoption*/} + +Start with specific directories and expand gradually: + +```js +{ + compilationMode: 'annotation' // Only compile "use memo" functions +} +``` + diff --git a/src/content/reference/react-compiler/directives.md b/src/content/reference/react-compiler/directives.md new file mode 100644 index 0000000000..705d0f6209 --- /dev/null +++ b/src/content/reference/react-compiler/directives.md @@ -0,0 +1,198 @@ +--- +title: Directives +--- + +<Intro> +React Compiler directives are special string literals that control whether specific functions are compiled. +</Intro> + +```js +function MyComponent() { + "use memo"; // Opt this component into compilation + return <div>{/* ... */}</div>; +} +``` + +<InlineToc /> + +--- + +## Overview {/*overview*/} + +React Compiler directives provide fine-grained control over which functions are optimized by the compiler. They are string literals placed at the beginning of a function body or at the top of a module. + +### Available directives {/*available-directives*/} + +* **[`"use memo"`](/reference/react-compiler/directives/use-memo)** - Opts a function into compilation +* **[`"use no memo"`](/reference/react-compiler/directives/use-no-memo)** - Opts a function out of compilation + +### Quick comparison {/*quick-comparison*/} + +| Directive | Purpose | When to use | +|-----------|---------|-------------| +| [`"use memo"`](/reference/react-compiler/directives/use-memo) | Force compilation | When using `annotation` mode or to override `infer` mode heuristics | +| [`"use no memo"`](/reference/react-compiler/directives/use-no-memo) | Prevent compilation | Debugging issues or working with incompatible code | + +--- + +## Usage {/*usage*/} + +### Function-level directives {/*function-level*/} + +Place directives at the beginning of a function to control its compilation: + +```js +// Opt into compilation +function OptimizedComponent() { + "use memo"; + return <div>This will be optimized</div>; +} + +// Opt out of compilation +function UnoptimizedComponent() { + "use no memo"; + return <div>This won't be optimized</div>; +} +``` + +### Module-level directives {/*module-level*/} + +Place directives at the top of a file to affect all functions in that module: + +```js +// At the very top of the file +"use memo"; + +// All functions in this file will be compiled +function Component1() { + return <div>Compiled</div>; +} + +function Component2() { + return <div>Also compiled</div>; +} + +// Can be overridden at function level +function Component3() { + "use no memo"; // This overrides the module directive + return <div>Not compiled</div>; +} +``` + +### Compilation modes interaction {/*compilation-modes*/} + +Directives behave differently depending on your [`compilationMode`](/reference/react-compiler/compilationMode): + +* **`annotation` mode**: Only functions with `"use memo"` are compiled +* **`infer` mode**: Compiler decides what to compile, directives override decisions +* **`all` mode**: Everything is compiled, `"use no memo"` can exclude specific functions + +--- + +## Best practices {/*best-practices*/} + +### Use directives sparingly {/*use-sparingly*/} + +Directives are escape hatches. Prefer configuring the compiler at the project level: + +```js +// βœ… Good - project-wide configuration +{ + plugins: [ + ['babel-plugin-react-compiler', { + compilationMode: 'infer' + }] + ] +} + +// ⚠️ Use directives only when needed +function SpecialCase() { + "use no memo"; // Document why this is needed + // ... +} +``` + +### Document directive usage {/*document-usage*/} + +Always explain why a directive is used: + +```js +// βœ… Good - clear explanation +function DataGrid() { + "use no memo"; // TODO: Remove after fixing issue with dynamic row heights (JIRA-123) + // Complex grid implementation +} + +// ❌ Bad - no explanation +function Mystery() { + "use no memo"; + // ... +} +``` + +### Plan for removal {/*plan-removal*/} + +Opt-out directives should be temporary: + +1. Add the directive with a TODO comment +2. Create a tracking issue +3. Fix the underlying problem +4. Remove the directive + +```js +function TemporaryWorkaround() { + "use no memo"; // TODO: Remove after upgrading ThirdPartyLib to v2.0 + return <ThirdPartyComponent />; +} +``` + +--- + +## Common patterns {/*common-patterns*/} + +### Gradual adoption {/*gradual-adoption*/} + +When adopting the React Compiler in a large codebase: + +```js +// Start with annotation mode +{ + compilationMode: 'annotation' +} + +// Opt in stable components +function StableComponent() { + "use memo"; + // Well-tested component +} + +// Later, switch to infer mode and opt out problematic ones +function ProblematicComponent() { + "use no memo"; // Fix issues before removing + // ... +} +``` + + +--- + +## Troubleshooting {/*troubleshooting*/} + +For specific issues with directives, see the troubleshooting sections in: + +* [`"use memo"` troubleshooting](/reference/react-compiler/directives/use-memo#troubleshooting) +* [`"use no memo"` troubleshooting](/reference/react-compiler/directives/use-no-memo#troubleshooting) + +### Common issues {/*common-issues*/} + +1. **Directive ignored**: Check placement (must be first) and spelling +2. **Compilation still happens**: Check `ignoreUseNoForget` setting +3. **Module directive not working**: Ensure it's before all imports + +--- + +## See also {/*see-also*/} + +* [`compilationMode`](/reference/react-compiler/compilationMode) - Configure how the compiler chooses what to optimize +* [`Configuration`](/reference/react-compiler/configuration) - Full compiler configuration options +* [React Compiler documentation](https://react.dev/learn/react-compiler) - Getting started guide \ No newline at end of file diff --git a/src/content/reference/react-compiler/directives/use-memo.md b/src/content/reference/react-compiler/directives/use-memo.md new file mode 100644 index 0000000000..431862682f --- /dev/null +++ b/src/content/reference/react-compiler/directives/use-memo.md @@ -0,0 +1,157 @@ +--- +title: "use memo" +titleForTitleTag: "'use memo' directive" +--- + +<Intro> + +`"use memo"` marks a function for React Compiler optimization. + +</Intro> + +<Note> + +In most cases, you don't need `"use memo"`. It's primarily needed in `annotation` mode where you must explicitly mark functions for optimization. In `infer` mode, the compiler automatically detects components and hooks by their naming patterns (PascalCase for components, `use` prefix for hooks). If a component or hook isn't being compiled in `infer` mode, you should fix its naming convention rather than forcing compilation with `"use memo"`. + +</Note> + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `"use memo"` {/*use-memo*/} + +Add `"use memo"` at the beginning of a function to mark it for React Compiler optimization. + +```js {1} +function MyComponent() { + "use memo"; + // ... +} +``` + +When a function contains `"use memo"`, the React Compiler will analyze and optimize it during build time. The compiler will automatically memoize values and components to prevent unnecessary re-computations and re-renders. + +#### Caveats {/*caveats*/} + +* `"use memo"` must be at the very beginning of a function body, before any imports or other code (comments are OK). +* The directive must be written with double or single quotes, not backticks. +* The directive must exactly match `"use memo"`. +* Only the first directive in a function is processed; additional directives are ignored. +* The effect of the directive depends on your [`compilationMode`](/reference/react-compiler/compilationMode) setting. + +### How `"use memo"` marks functions for optimization {/*how-use-memo-marks*/} + +In a React app that uses the React Compiler, functions are analyzed at build time to determine if they can be optimized. By default, the compiler automatically infers which components to memoize, but this can depend on your [`compilationMode`](/reference/react-compiler/compilationMode) setting if you've set it. + +`"use memo"` explicitly marks a function for optimization, overriding the default behavior: + +* In `annotation` mode: Only functions with `"use memo"` are optimized +* In `infer` mode: The compiler uses heuristics, but `"use memo"` forces optimization +* In `all` mode: Everything is optimized by default, making `"use memo"` redundant + +The directive creates a clear boundary in your codebase between optimized and non-optimized code, giving you fine-grained control over the compilation process. + +### When to use `"use memo"` {/*when-to-use*/} + +You should consider using `"use memo"` when: + +#### You're using annotation mode {/*annotation-mode-use*/} +In `compilationMode: 'annotation'`, the directive is required for any function you want optimized: + +```js +// βœ… This component will be optimized +function OptimizedList() { + "use memo"; + // ... +} + +// ❌ This component won't be optimized +function SimpleWrapper() { + // ... +} +``` + +#### You're gradually adopting React Compiler {/*gradual-adoption*/} +Start with `annotation` mode and selectively optimize stable components: + +```js +// Start by optimizing leaf components +function Button({ onClick, children }) { + "use memo"; + // ... +} + +// Gradually move up the tree as you verify behavior +function ButtonGroup({ buttons }) { + "use memo"; + // ... +} +``` + +--- + +## Usage {/*usage*/} + +### Working with different compilation modes {/*compilation-modes*/} + +The behavior of `"use memo"` changes based on your compiler configuration: + +```js +// babel.config.js +module.exports = { + plugins: [ + ['babel-plugin-react-compiler', { + compilationMode: 'annotation' // or 'infer' or 'all' + }] + ] +}; +``` + +#### Annotation mode {/*annotation-mode-example*/} +```js +// βœ… Optimized with "use memo" +function ProductCard({ product }) { + "use memo"; + // ... +} + +// ❌ Not optimized (no directive) +function ProductList({ products }) { + // ... +} +``` + +#### Infer mode (default) {/*infer-mode-example*/} +```js +// Automatically memoized because this is named like a Component +function ComplexDashboard({ data }) { + // ... +} + +// Skipped: Is not named like a Component +function simpleDisplay({ text }) { + // ... +} +``` + +In `infer` mode, the compiler automatically detects components and hooks by their naming patterns (PascalCase for components, `use` prefix for hooks). If a component or hook isn't being compiled in `infer` mode, you should fix its naming convention rather than forcing compilation with `"use memo"`. + +--- + +## Troubleshooting {/*troubleshooting*/} + +### Verifying optimization {/*verifying-optimization*/} + +To confirm your component is being optimized: + +1. Check the compiled output in your build +2. Use React DevTools to check for Memo ✨ badge + +### See also {/*see-also*/} + +* [`"use no memo"`](/reference/react-compiler/directives/use-no-memo) - Opt out of compilation +* [`compilationMode`](/reference/react-compiler/compilationMode) - Configure compilation behavior +* [React Compiler](/learn/react-compiler) - Getting started guide \ No newline at end of file diff --git a/src/content/reference/react-compiler/directives/use-no-memo.md b/src/content/reference/react-compiler/directives/use-no-memo.md new file mode 100644 index 0000000000..e6c419bc66 --- /dev/null +++ b/src/content/reference/react-compiler/directives/use-no-memo.md @@ -0,0 +1,147 @@ +--- +title: "use no memo" +titleForTitleTag: "'use no memo' directive" +--- + +<Intro> + +`"use no memo"` prevents a function from being optimized by React Compiler. + +</Intro> + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `"use no memo"` {/*use-no-memo*/} + +Add `"use no memo"` at the beginning of a function to prevent React Compiler optimization. + +```js {1} +function MyComponent() { + "use no memo"; + // ... +} +``` + +When a function contains `"use no memo"`, the React Compiler will skip it entirely during optimization. This is useful as a temporary escape hatch when debugging or when dealing with code that doesn't work correctly with the compiler. + +#### Caveats {/*caveats*/} + +* `"use no memo"` must be at the very beginning of a function body, before any imports or other code (comments are OK). +* The directive must be written with double or single quotes, not backticks. +* The directive must exactly match `"use no memo"` or its alias `"use no forget"`. +* This directive takes precedence over all compilation modes and other directives. +* It's intended as a temporary debugging tool, not a permanent solution. + +### How `"use no memo"` opts-out of optimization {/*how-use-no-memo-opts-out*/} + +React Compiler analyzes your code at build time to apply optimizations. `"use no memo"` creates an explicit boundary that tells the compiler to skip a function entirely. + +This directive takes precedence over all other settings: +* In `all` mode: The function is skipped despite the global setting +* In `infer` mode: The function is skipped even if heuristics would optimize it + +The compiler treats these functions as if the React Compiler wasn't enabled, leaving them exactly as written. + +### When to use `"use no memo"` {/*when-to-use*/} + +`"use no memo"` should be used sparingly and temporarily. Common scenarios include: + +#### Debugging compiler issues {/*debugging-compiler*/} +When you suspect the compiler is causing issues, temporarily disable optimization to isolate the problem: + +```js +function ProblematicComponent({ data }) { + "use no memo"; // TODO: Remove after fixing issue #123 + + // Rules of React violations that weren't statically detected + // ... +} +``` + +#### Third-party library integration {/*third-party*/} +When integrating with libraries that might not be compatible with the compiler: + +```js +function ThirdPartyWrapper() { + "use no memo"; + + useThirdPartyHook(); // Has side effects that compiler might optimize incorrectly + // ... +} +``` + +--- + +## Usage {/*usage*/} + +The `"use no memo"` directive is placed at the beginning of a function body to prevent React Compiler from optimizing that function: + +```js +function MyComponent() { + "use no memo"; + // Function body +} +``` + +The directive can also be placed at the top of a file to affect all functions in that module: + +```js +"use no memo"; + +// All functions in this file will be skipped by the compiler +``` + +`"use no memo"` at the function level overrides the module level directive. + +--- + +## Troubleshooting {/*troubleshooting*/} + +### Directive not preventing compilation {/*not-preventing*/} + +If `"use no memo"` isn't working: + +```js +// ❌ Wrong - directive after code +function Component() { + const data = getData(); + "use no memo"; // Too late! +} + +// βœ… Correct - directive first +function Component() { + "use no memo"; + const data = getData(); +} +``` + +Also check: +* Spelling - must be exactly `"use no memo"` +* Quotes - must use single or double quotes, not backticks + +### Best practices {/*best-practices*/} + +**Always document why** you're disabling optimization: + +```js +// βœ… Good - clear explanation and tracking +function DataProcessor() { + "use no memo"; // TODO: Remove after fixing rule of react violation + // ... +} + +// ❌ Bad - no explanation +function Mystery() { + "use no memo"; + // ... +} +``` + +### See also {/*see-also*/} + +* [`"use memo"`](/reference/react-compiler/directives/use-memo) - Opt into compilation +* [React Compiler](/learn/react-compiler) - Getting started guide \ No newline at end of file diff --git a/src/content/reference/react-compiler/gating.md b/src/content/reference/react-compiler/gating.md new file mode 100644 index 0000000000..479506af32 --- /dev/null +++ b/src/content/reference/react-compiler/gating.md @@ -0,0 +1,141 @@ +--- +title: gating +--- + +<Intro> + +The `gating` option enables conditional compilation, allowing you to control when optimized code is used at runtime. + +</Intro> + +```js +{ + gating: { + source: 'my-feature-flags', + importSpecifierName: 'shouldUseCompiler' + } +} +``` + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `gating` {/*gating*/} + +Configures runtime feature flag gating for compiled functions. + +#### Type {/*type*/} + +``` +{ + source: string; + importSpecifierName: string; +} | null +``` + +#### Default value {/*default-value*/} + +`null` + +#### Properties {/*properties*/} + +- **`source`**: Module path to import the feature flag from +- **`importSpecifierName`**: Name of the exported function to import + +#### Caveats {/*caveats*/} + +- The gating function must return a boolean +- Both compiled and original versions increase bundle size +- The import is added to every file with compiled functions + +--- + +## Usage {/*usage*/} + +### Basic feature flag setup {/*basic-setup*/} + +1. Create a feature flag module: + +```js +// src/utils/feature-flags.js +export function shouldUseCompiler() { + // your logic here + return getFeatureFlag('react-compiler-enabled'); +} +``` + +2. Configure the compiler: + +```js +{ + gating: { + source: './src/utils/feature-flags', + importSpecifierName: 'shouldUseCompiler' + } +} +``` + +3. The compiler generates gated code: + +```js +// Input +function Button(props) { + return <button>{props.label}</button>; +} + +// Output (simplified) +import { shouldUseCompiler } from './src/utils/feature-flags'; + +const Button = shouldUseCompiler() + ? function Button_optimized(props) { /* compiled version */ } + : function Button_original(props) { /* original version */ }; +``` + +Note that the gating function is evaluated once at module time, so once the JS bundle has been parsed and evaluated the choice of component stays static for the rest of the browser session. + +--- + +## Troubleshooting {/*troubleshooting*/} + +### Feature flag not working {/*flag-not-working*/} + +Verify your flag module exports the correct function: + +```js +// ❌ Wrong: Default export +export default function shouldUseCompiler() { + return true; +} + +// βœ… Correct: Named export matching importSpecifierName +export function shouldUseCompiler() { + return true; +} +``` + +### Import errors {/*import-errors*/} + +Ensure the source path is correct: + +```js +// ❌ Wrong: Relative to babel.config.js +{ + source: './src/flags', + importSpecifierName: 'flag' +} + +// βœ… Correct: Module resolution path +{ + source: '@myapp/feature-flags', + importSpecifierName: 'flag' +} + +// βœ… Also correct: Absolute path from project root +{ + source: './src/utils/flags', + importSpecifierName: 'flag' +} +``` diff --git a/src/content/reference/react-compiler/logger.md b/src/content/reference/react-compiler/logger.md new file mode 100644 index 0000000000..41e2a1da06 --- /dev/null +++ b/src/content/reference/react-compiler/logger.md @@ -0,0 +1,118 @@ +--- +title: logger +--- + +<Intro> + +The `logger` option provides custom logging for React Compiler events during compilation. + +</Intro> + +```js +{ + logger: { + logEvent(filename, event) { + console.log(`[Compiler] ${event.kind}: ${filename}`); + } + } +} +``` + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `logger` {/*logger*/} + +Configures custom logging to track compiler behavior and debug issues. + +#### Type {/*type*/} + +``` +{ + logEvent: (filename: string | null, event: LoggerEvent) => void; +} | null +``` + +#### Default value {/*default-value*/} + +`null` + +#### Methods {/*methods*/} + +- **`logEvent`**: Called for each compiler event with the filename and event details + +#### Event types {/*event-types*/} + +- **`CompileSuccess`**: Function successfully compiled +- **`CompileError`**: Function skipped due to errors +- **`CompileDiagnostic`**: Non-fatal diagnostic information +- **`CompileSkip`**: Function skipped for other reasons +- **`PipelineError`**: Unexpected compilation error +- **`Timing`**: Performance timing information + +#### Caveats {/*caveats*/} + +- Event structure may change between versions +- Large codebases generate many log entries + +--- + +## Usage {/*usage*/} + +### Basic logging {/*basic-logging*/} + +Track compilation success and failures: + +```js +{ + logger: { + logEvent(filename, event) { + switch (event.kind) { + case 'CompileSuccess': { + console.log(`βœ… Compiled: ${filename}`); + break; + } + case 'CompileError': { + console.log(`❌ Skipped: ${filename}`); + break; + } + default: {} + } + } + } +} +``` + +### Detailed error logging {/*detailed-error-logging*/} + +Get specific information about compilation failures: + +```js +{ + logger: { + logEvent(filename, event) { + if (event.kind === 'CompileError') { + console.error(`\nCompilation failed: ${filename}`); + console.error(`Reason: ${event.detail.reason}`); + + if (event.detail.description) { + console.error(`Details: ${event.detail.description}`); + } + + if (event.detail.loc) { + const { line, column } = event.detail.loc.start; + console.error(`Location: Line ${line}, Column ${column}`); + } + + if (event.detail.suggestions) { + console.error('Suggestions:', event.detail.suggestions); + } + } + } + } +} +``` + diff --git a/src/content/reference/react-compiler/panicThreshold.md b/src/content/reference/react-compiler/panicThreshold.md new file mode 100644 index 0000000000..e20f5c0c50 --- /dev/null +++ b/src/content/reference/react-compiler/panicThreshold.md @@ -0,0 +1,87 @@ +--- +title: panicThreshold +--- + +<Intro> + +The `panicThreshold` option controls how the React Compiler handles errors during compilation. + +</Intro> + +```js +{ + panicThreshold: 'none' // Recommended +} +``` + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `panicThreshold` {/*panicthreshold*/} + +Determines whether compilation errors should fail the build or skip optimization. + +#### Type {/*type*/} + +``` +'none' | 'critical_errors' | 'all_errors' +``` + +#### Default value {/*default-value*/} + +`'none'` + +#### Options {/*options*/} + +- **`'none'`** (default, recommended): Skip components that can't be compiled and continue building +- **`'critical_errors'`**: Fail the build only on critical compiler errors +- **`'all_errors'`**: Fail the build on any compiler diagnostic + +#### Caveats {/*caveats*/} + +- Production builds should always use `'none'` +- Build failures prevent your application from building +- The compiler automatically detects and skips problematic code with `'none'` +- Higher thresholds are only useful during development for debugging + +--- + +## Usage {/*usage*/} + +### Production configuration (recommended) {/*production-configuration*/} + +For production builds, always use `'none'`. This is the default value: + +```js +{ + panicThreshold: 'none' +} +``` + +This ensures: +- Your build never fails due to compiler issues +- Components that can't be optimized run normally +- Maximum components get optimized +- Stable production deployments + +### Development debugging {/*development-debugging*/} + +Temporarily use stricter thresholds to find issues: + +```js +const isDevelopment = process.env.NODE_ENV === 'development'; + +{ + panicThreshold: isDevelopment ? 'critical_errors' : 'none', + logger: { + logEvent(filename, event) { + if (isDevelopment && event.kind === 'CompileError') { + // ... + } + } + } +} +``` \ No newline at end of file diff --git a/src/content/reference/react-compiler/target.md b/src/content/reference/react-compiler/target.md new file mode 100644 index 0000000000..8ccc4a6b12 --- /dev/null +++ b/src/content/reference/react-compiler/target.md @@ -0,0 +1,148 @@ +--- +title: target +--- + +<Intro> + +The `target` option specifies which React version the compiler should generate code for. + +</Intro> + +```js +{ + target: '19' // or '18', '17' +} +``` + +<InlineToc /> + +--- + +## Reference {/*reference*/} + +### `target` {/*target*/} + +Configures the React version compatibility for the compiled output. + +#### Type {/*type*/} + +``` +'17' | '18' | '19' +``` + +#### Default value {/*default-value*/} + +`'19'` + +#### Valid values {/*valid-values*/} + +- **`'19'`**: Target React 19 (default). No additional runtime required. +- **`'18'`**: Target React 18. Requires `react-compiler-runtime` package. +- **`'17'`**: Target React 17. Requires `react-compiler-runtime` package. + +#### Caveats {/*caveats*/} + +- 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@latest` + +--- + +## Usage {/*usage*/} + +### Targeting React 19 (default) {/*targeting-react-19*/} + +For React 19, no special configuration is needed: + +```js +{ + // defaults to target: '19' +} +``` + +The compiler will use React 19's built-in runtime APIs: + +```js +// Compiled output uses React 19's native APIs +import { c as _c } from 'react/compiler-runtime'; +``` + +### Targeting React 17 or 18 {/*targeting-react-17-or-18*/} + +For React 17 and React 18 projects, you need two steps: + +1. Install the runtime package: + +```bash +npm install react-compiler-runtime@latest +``` + +2. Configure the target: + +```js +// For React 18 +{ + target: '18' +} + +// For React 17 +{ + target: '17' +} +``` + +The compiler will use the polyfill runtime for both versions: + +```js +// Compiled output uses the polyfill +import { c as _c } from 'react-compiler-runtime'; +``` + +--- + +## Troubleshooting {/*troubleshooting*/} + +### Runtime errors about missing compiler runtime {/*missing-runtime*/} + +If you see errors like "Cannot find module 'react/compiler-runtime'": + +1. Check your React version: + ```bash + npm why react + ``` + +2. If using React 17 or 18, install the runtime: + ```bash + npm install react-compiler-runtime@latest + ``` + +3. Ensure your target matches your React version: + ```js + { + target: '18' // Must match your React major version + } + ``` + +### Runtime package not working {/*runtime-not-working*/} + +Ensure the runtime package is: + +1. Installed in your project (not globally) +2. Listed in your `package.json` dependencies +3. The correct version (`@latest` tag) +4. Not in `devDependencies` (it's needed at runtime) + +### Checking compiled output {/*checking-output*/} + +To verify the correct runtime is being used, note the different import (`react/compiler-runtime` for builtin, `react-compiler-runtime` standalone package for 17/18): + +```js +// For React 19 (built-in runtime) +import { c } from 'react/compiler-runtime' +// ^ + +// For React 17/18 (polyfill runtime) +import { c } from 'react-compiler-runtime' +// ^ +``` \ No newline at end of file diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md index 5a00e6c824..f11aa2abad 100644 --- a/src/content/reference/react-dom/client/createRoot.md +++ b/src/content/reference/react-dom/client/createRoot.md @@ -86,7 +86,7 @@ React akan menampilkan `<App />` dalam `root`, dan mengambil alih pengelolaan DO * Jika Anda memanggil `render` pada akar yang sama berulang kali, React akan memperbarui DOM sebisa mungkin hingga menyamai JSX terakhir yang Anda berikan. React akan memutuskan bagian mana dari DOM yang dapat digunakan kembali dan bagian mana yang perlu dibuat ulang, dengan melakukan ["pencocokan"](/learn/preserving-and-resetting-state) dengan pohon yang telah di-*render* sebelumnya. Pemanggilan kembali `render` di akar yang sama mirip dengan memanggil [fungsi `set`](/reference/react/useState#setstate) pada komponen akar: React menghindari pembaharuan DOM yang tidak diperlukan. -* Although rendering is synchronous once it starts, `root.render(...)` is not. This means code after `root.render()` may run before any effects (`useLayoutEffect`, `useEffect`) of that specific render are fired. This is usually fine and rarely needs adjustment. In rare cases where effect timing matters, you can wrap `root.render(...)` in [`flushSync`](https://react.dev/reference/react-dom/client/flushSync) to ensure the initial render runs fully synchronously. +* Although rendering is synchronous once it starts, `root.render(...)` is not. This means code after `root.render()` may run before any effects (`useLayoutEffect`, `useEffect`) of that specific render are fired. This is usually fine and rarely needs adjustment. In rare cases where effect timing matters, you can wrap `root.render(...)` in [`flushSync`](https://react.dev/reference/react-dom/flushSync) to ensure the initial render runs fully synchronously. ```js const root = createRoot(document.getElementById('root')); @@ -205,7 +205,11 @@ Saat HTML Anda kosong, pengguna akan melihat sebuah halaman kosong sampai kode J <div id="root"></div> ``` +<<<<<<< HEAD Ini dapat terasa sangat lambat! Untuk mengatasi masalah ini, Anda dapat membuat HTML awal dari komponen Anda [pada server atau saat proses *build*](/reference/react-dom/server) Sehingga pengunjung dapat membaca teks, melihat gambar dan mengklik tautan sebelum kode JavaScript apapun selesai dimuat. Kami merekomendasikan untuk [menggunakan sebuah *framework*](/learn/start-a-new-react-project#production-grade-react-frameworks) yang telah melakukan optimisasi ini sejak awal. Bergantung dari kapan proses ini berjalan, ini dapat dipanggil sebagai *server-side rendering (SSR)* atau *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).* +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Note> diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md index b434074935..bac72b2342 100644 --- a/src/content/reference/react-dom/client/hydrateRoot.md +++ b/src/content/reference/react-dom/client/hydrateRoot.md @@ -295,7 +295,8 @@ import App from './App.js'; hydrateRoot(document.getElementById('root'), <App />); ``` -```js src/App.js active +{/* kind of an edge case, seems fine to use this hack here */} +```js {expectedErrors: {'react-compiler': [7]}} src/App.js active import { useState, useEffect } from "react"; export default function App() { diff --git a/src/content/reference/react-dom/client/index.md b/src/content/reference/react-dom/client/index.md index 3a22c837b3..597a165be0 100644 --- a/src/content/reference/react-dom/client/index.md +++ b/src/content/reference/react-dom/client/index.md @@ -4,7 +4,11 @@ title: API Klien React DOM <Intro> +<<<<<<< HEAD API `react-dom/client` memungkinkan Anda me-*render* komponen React di sisi klien (di peramban). Biasanya API ini digunakan pada level teratas aplikasi React untuk menginisialisasi pohon React Anda. Sebuah [*framework*](/learn/start-a-new-react-project#production-grade-react-frameworks) mungkin memanggilnya untuk Anda. Biasanya komponen Anda tidak perlu mengimpor atau menggunakannya. +======= +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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Intro> diff --git a/src/content/reference/react-dom/components/common.md b/src/content/reference/react-dom/components/common.md index f9fb196807..8dd3967e6c 100644 --- a/src/content/reference/react-dom/components/common.md +++ b/src/content/reference/react-dom/components/common.md @@ -920,7 +920,11 @@ export default function Form() { </Sandpack> +<<<<<<< HEAD Baca lebih lanjut mengenai [memanipulasi DOM dengan refs](/learn/manipulating-the-dom-with-refs) and [lihat lebih banyak contoh.](/reference/react/useRef#examples-dom) +======= +Read more about [manipulating DOM with refs](/learn/manipulating-the-dom-with-refs) and [check out more examples.](/reference/react/useRef#usage) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Untuk kasus yang lebih canggih, attribut `ref` juga menerima sebuah [fungsi *callback*.](#ref-callback) diff --git a/src/content/reference/react-dom/components/form.md b/src/content/reference/react-dom/components/form.md index d7d3f271c9..4f150b1bd7 100644 --- a/src/content/reference/react-dom/components/form.md +++ b/src/content/reference/react-dom/components/form.md @@ -36,9 +36,15 @@ Untuk membuat kontrol interaktif untuk mengirimkan informasi, render [komponen ` #### Props {/*props*/} +<<<<<<< HEAD `<form>` mendukung semua [props elemen umum.](/reference/react-dom/components/common#props) [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action): URL atau fungsi. Ketika URL diberikan ke `action`, formulir akan berperilaku seperti komponen formulir HTML. Ketika fungsi diberikan ke `action`, fungsi tersebut akan menangani pengiriman formulir. Fungsi yang diberikan ke `action` dapat berupa *async* dan akan dipanggil dengan satu argumen yang berisi [data formulir](https://developer.mozilla.org/en-US/docs/Web/API/FormData) dari formulir yang dikirimkan. Prop `action` dapat ditimpa oleh atribut `formAction` pada komponen `<button>`, `<input type="submit">`, atau `<input type="image">`. +======= +`<form>` supports all [common element props.](/reference/react-dom/components/common#common-props) + +[`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action): a URL or function. When a URL is passed to `action` the form will behave like the HTML form component. When a function is passed to `action` the function will handle the form submission in a Transition following [the Action prop pattern](/reference/react/useTransition#exposing-action-props-from-components). The function passed to `action` may be async and will be called with a single argument containing the [form data](https://developer.mozilla.org/en-US/docs/Web/API/FormData) of the submitted form. The `action` prop can be overridden by a `formAction` attribute on a `<button>`, `<input type="submit">`, or `<input type="image">` component. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 #### Catatan Penting {/*caveats*/} @@ -228,8 +234,8 @@ export async function deliverMessage(message) { </Sandpack> -[//]: # 'Uncomment the next line, and delete this line after the `useOptimistic` reference documentatino page is published' -[//]: # 'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/hooks/useOptimistic).' +[//]: # 'Uncomment the next line, and delete this line after the `useOptimistic` reference documentation page is published' +[//]: # 'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/useOptimistic).' ### Menangani kesalahan pengiriman formulir {/*handling-form-submission-errors*/} @@ -276,9 +282,15 @@ export default function Search() { Menampilkan pesan kesalahan pengiriman formulir sebelum bundel JavaScript dimuat untuk peningkatan progresif mengharuskan bahwa: +<<<<<<< HEAD 1. `<form>` dirender oleh [Server Component](/reference/rsc/use-client) 1. fungsi yang diteruskan ke prop `action` `<form>` adalah [Fungsi Server](/reference/rsc/server-functions) 1. Hook `useActionState` digunakan untuk menampilkan pesan kesalahan +======= +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 +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 `useActionState` mengambil dua parameter: sebuah [Fungsi Server](/reference/rsc/server-functions) dan sebuah *state* awal. `useActionState` mengembalikan dua nilai, sebuah variabel *state* dan sebuah aksi. Aksi yang dikembalikan oleh `useActionState` harus diteruskan ke prop `action` dari formulir. Variabel *state* yang dikembalikan oleh `useActionState` dapat digunakan untuk menampilkan pesan kesalahan. Nilai yang dikembalikan oleh Fungsi Server yang diteruskan ke `useActionState` akan digunakan untuk memperbarui variabel *state*. diff --git a/src/content/reference/react-dom/components/index.md b/src/content/reference/react-dom/components/index.md index 5ed4cbd6d3..4b5e664d43 100644 --- a/src/content/reference/react-dom/components/index.md +++ b/src/content/reference/react-dom/components/index.md @@ -160,16 +160,138 @@ Serupa dengan [standar panduan DOM,](https://developer.mozilla.org/en-US/docs/We ### Elemen HTML *Custom* {/*custom-html-elements*/} +<<<<<<< HEAD Jika Anda *render* sebuah *tag* menggunakan tanda hubung, seperti `<my-element>`, React akan mengasumsikan Anda untuk *render* [elemen HTML *custom*.](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) Pada React, cara kerja *rendering* pada elemen *custom* akan berbeda dengan *rendering* pada *tags* bawaan peramban: - Semua props dari *custom element* akan diserialisasikan menjadi *strings* dan selalu disetel menggunakan *attributes*. - *Custom elements* menerima `class` ketimbang `className`, dan `for` ketimbang `htmlFor`. Jika Anda `render` sebuah elemen HTML bawaan peramban dengan atribut [`is`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is), maka itu akan diperlakukan sebagai *custom element*. +======= +If you render a tag with a dash, like `<my-element>`, React will assume you want to render a [custom HTML element.](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 +#### Setting values on custom elements {/*attributes-vs-properties*/} + +Custom elements have two methods of passing data into them: + +1) Attributes: Which are displayed in markup and can only be set to string values +2) Properties: Which are not displayed in markup and can be set to arbitrary JavaScript values + +By default, React will pass values bound in JSX as attributes: + +```jsx +<my-element value="Hello, world!"></my-element> +``` + +Non-string JavaScript values passed to custom elements will be serialized by default: + +```jsx +// Will be passed as `"1,2,3"` as the output of `[1,2,3].toString()` +<my-element value={[1,2,3]}></my-element> +``` + +React will, however, recognize an custom element's property as one that it may pass arbitrary values to if the property name shows up on the class during construction: + +<Sandpack> + +```js src/index.js hidden +import {MyElement} from './MyElement.js'; +import { createRoot } from 'react-dom/client'; +import {App} from "./App.js"; + +customElements.define('my-element', MyElement); + +const root = createRoot(document.getElementById('root')) +root.render(<App />); +``` + +```js src/MyElement.js active +export class MyElement extends HTMLElement { + constructor() { + super(); + // The value here will be overwritten by React + // when initialized as an element + this.value = undefined; + } + + connectedCallback() { + this.innerHTML = this.value.join(", "); + } +} +``` + +```js src/App.js +export function App() { + return <my-element value={[1,2,3]}></my-element> +} +``` + +</Sandpack> + +#### Listening for events on custom elements {/*custom-element-events*/} + +A common pattern when using custom elements is that they may dispatch [`CustomEvent`s](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) rather than accept a function to call when an event occur. You can listen for these events using an `on` prefix when binding to the event via JSX. + +<Sandpack> + +```js src/index.js hidden +import {MyElement} from './MyElement.js'; +import { createRoot } from 'react-dom/client'; +import {App} from "./App.js"; + +customElements.define('my-element', MyElement); + +const root = createRoot(document.getElementById('root')) +root.render(<App />); +``` + +```javascript src/MyElement.js +export class MyElement extends HTMLElement { + constructor() { + super(); + this.test = undefined; + this.emitEvent = this._emitEvent.bind(this); + } + + _emitEvent() { + const event = new CustomEvent('speak', { + detail: { + message: 'Hello, world!', + }, + }); + this.dispatchEvent(event); + } + + connectedCallback() { + this.el = document.createElement('button'); + this.el.innerText = 'Say hi'; + this.el.addEventListener('click', this.emitEvent); + this.appendChild(this.el); + } + + disconnectedCallback() { + this.el.removeEventListener('click', this.emitEvent); + } +} +``` + +```jsx src/App.js active +export function App() { + return ( + <my-element + onspeak={e => console.log(e.detail.message)} + ></my-element> + ) +} +``` + +</Sandpack> + <Note> +<<<<<<< HEAD [Versi React mendatang akan menambahkan lebih banyak dukungan komprehensif untuk *custom elements*.](https://github.com/facebook/react/issues/11347#issuecomment-1122275286) Anda dapat mencobanya dengan memperbarui *packages* React ke versi eksperimental terbaru: @@ -178,6 +300,16 @@ Anda dapat mencobanya dengan memperbarui *packages* React ke versi eksperimental - `react-dom@experimental` Versi eksperimental mungkin mengandung *bugs*. Jangan digunakan di *production*. +======= +Events are case-sensitive and support dashes (`-`). Preserve the casing of the event and include all dashes when listening for custom element's events: + +```jsx +// Listens for `say-hi` events +<my-element onsay-hi={console.log}></my-element> +// Listens for `sayHi` events +<my-element onsayHi={console.log}></my-element> +``` +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Note> --- diff --git a/src/content/reference/react-dom/components/input.md b/src/content/reference/react-dom/components/input.md index e4ee4c4929..f6d7cbe6f5 100644 --- a/src/content/reference/react-dom/components/input.md +++ b/src/content/reference/react-dom/components/input.md @@ -30,7 +30,11 @@ Untuk menampilkan sebuah masukan, *render* komponen [bawaan peramban `<input>`]( #### Props {/*props*/} +<<<<<<< HEAD `<input>` mendukung semua [element props yang umum.](/reference/react-dom/components/common#props) +======= +`<input>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 - [`formAction`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formaction): Sebuah *string* atau fungsi. Menimpa `<form action>` induk untuk `type="submit"` dan `type="image"`. Ketika URL dioper ke `action` form akan memiliki perilaku sebagai form standar HTML. Ketika fungsi dioper ke `formAction` fungsi akan menangani kiriman form. Lihat [`<form action>`](/reference/react-dom/components/form#props). diff --git a/src/content/reference/react-dom/components/link.md b/src/content/reference/react-dom/components/link.md index 3ea44bc9ef..b2be71f608 100644 --- a/src/content/reference/react-dom/components/link.md +++ b/src/content/reference/react-dom/components/link.md @@ -30,7 +30,11 @@ Untuk menautkan ke sumber daya eksternal seperti *stylesheet*, *font*, dan ikon, #### *Props* {/*props*/} +<<<<<<< HEAD `<link>` mendukung semua [*props* elemen umum.](/reference/react-dom/components/common#props) +======= +`<link>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 * `rel`: *string*, dibutuhkan. Menentukan [hubungan dengan sumber daya](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel). React [memperlakukan tautan dengan rel="stylesheet" secara berbeda](#special-rendering-behavior) dari tautan lainnya. diff --git a/src/content/reference/react-dom/components/meta.md b/src/content/reference/react-dom/components/meta.md index 5c9238fd89..fc7c90f5da 100644 --- a/src/content/reference/react-dom/components/meta.md +++ b/src/content/reference/react-dom/components/meta.md @@ -30,7 +30,11 @@ Untuk menambahkan metadata dokumen, *render* komponen HTML bawaan `<meta>`. Anda #### *Props* {/*props*/} +<<<<<<< HEAD `<meta>` mendukung semua [*props* elemen pada umumnya.](/reference/react-dom/components/common#props) +======= +`<meta>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Elemen ini harus memiliki *setidaknya satu* dari *props* berikut: `name`, `httpEquiv`, `charset`, `itemProp`. Komponen `<meta>` akan menghasilkan hal yang berbeda tergantung dari *props* yang diberikan. diff --git a/src/content/reference/react-dom/components/option.md b/src/content/reference/react-dom/components/option.md index 7ed4c05a60..5ffb456749 100644 --- a/src/content/reference/react-dom/components/option.md +++ b/src/content/reference/react-dom/components/option.md @@ -37,7 +37,11 @@ title: "<option>" #### Props {/*props*/} +<<<<<<< HEAD `<option>` mendukung semua [*props* elemen umum.](/reference/react-dom/components/common#props) +======= +`<option>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Sebagai tambahan, `<option>` mendukung *props* berikut: diff --git a/src/content/reference/react-dom/components/progress.md b/src/content/reference/react-dom/components/progress.md index 4cf2885628..d95bfb1b86 100644 --- a/src/content/reference/react-dom/components/progress.md +++ b/src/content/reference/react-dom/components/progress.md @@ -30,7 +30,11 @@ Untuk menampilkan indikator progres, render komponen [`<progress>` bawaan peramb #### Props {/*props*/} +<<<<<<< HEAD `<progress>` mendukung semua [elemen umum *props*.](/reference/react-dom/components/common#props) +======= +`<progress>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Selain itu, `<progress>` juga mendukung *props*: diff --git a/src/content/reference/react-dom/components/script.md b/src/content/reference/react-dom/components/script.md index a085c34183..856c24f67c 100644 --- a/src/content/reference/react-dom/components/script.md +++ b/src/content/reference/react-dom/components/script.md @@ -31,7 +31,11 @@ Untuk menambahkan *script* eksternal atau sisipan pada document, render [kompone #### Props {/*props*/} +<<<<<<< HEAD `<script>` mendukung segala [props elemen umum.](/reference/react-dom/components/common#props) +======= +`<script>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Seharusnya memiliki *salah satu* props `children` atau `src`. diff --git a/src/content/reference/react-dom/components/select.md b/src/content/reference/react-dom/components/select.md index 3c4abd83c3..87f3908566 100644 --- a/src/content/reference/react-dom/components/select.md +++ b/src/content/reference/react-dom/components/select.md @@ -36,7 +36,11 @@ Untuk menampilkan kotak pilih (*select box*), *render* komponen [`<select>` bawa #### Props {/*props*/} +<<<<<<< HEAD `<select>` mendukung seluruh [*props* elemen umum.](/reference/react-dom/components/common#props) +======= +`<select>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Anda dapat [membuat sebuah kotak pilih (*select box*) terkontrol](#controlling-a-select-box-with-a-state-variable) dengan memberikan *prop* `<value>`: diff --git a/src/content/reference/react-dom/components/style.md b/src/content/reference/react-dom/components/style.md index 39df92d9f1..561c207d1d 100644 --- a/src/content/reference/react-dom/components/style.md +++ b/src/content/reference/react-dom/components/style.md @@ -30,7 +30,7 @@ To add inline styles to your document, render the [built-in browser `<style>` co #### Props {/*props*/} -`<style>` supports all [common element props.](/reference/react-dom/components/common#props) +`<style>` supports all [common element props.](/reference/react-dom/components/common#common-props) * `children`: a string, required. The contents of the stylesheet. * `precedence`: a string. Tells React where to rank the `<style>` DOM node relative to others in the document `<head>`, which determines which stylesheet can override the other. React will infer that precedence values it discovers first are "lower" and precedence values it discovers later are "higher". Many style systems can work fine using a single precedence value because style rules are atomic. Stylesheets with the same precedence go together whether they are `<link>` or inline `<style>` tags or loaded using [`preinit`](/reference/react-dom/preinit) functions. @@ -49,7 +49,7 @@ React can move `<style>` components to the document's `<head>`, de-duplicate ide To opt into this behavior, provide the `href` and `precedence` props. React will de-duplicate styles if they have the same `href`. The precedence prop tells React where to rank the `<style>` DOM node relative to others in the document `<head>`, which determines which stylesheet can override the other. -This special treatment comes with two caveats: +This special treatment comes with three caveats: * React will ignore changes to props after the style has been rendered. (React will issue a warning in development if this happens.) * React will drop all extraneous props when using the `precedence` prop (beyond `href` and `precedence`). diff --git a/src/content/reference/react-dom/components/textarea.md b/src/content/reference/react-dom/components/textarea.md index 3751d9e31a..a9e67b475e 100644 --- a/src/content/reference/react-dom/components/textarea.md +++ b/src/content/reference/react-dom/components/textarea.md @@ -30,7 +30,11 @@ Untuk menampilkan sebuah area teks, me-*render* [komponen peramban bawaan `<text #### Props {/*props*/} +<<<<<<< HEAD `<textarea>` mendukung semua [elemen *props* yang umum.](/reference/react-dom/components/common#props) +======= +`<textarea>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Anda dapat [membuat sebuah area teks yang terkendali (*controlled*)](#controlling-a-text-area-with-a-state-variable) dengan cara mengoper sebuah *prop* `value`: diff --git a/src/content/reference/react-dom/components/title.md b/src/content/reference/react-dom/components/title.md index d71757e4ca..1bf1ae4ed5 100644 --- a/src/content/reference/react-dom/components/title.md +++ b/src/content/reference/react-dom/components/title.md @@ -30,7 +30,11 @@ Untuk menentukan judul dokmen, render [komponen bawaan peramban `<title>`](https #### Props {/*props*/} +<<<<<<< HEAD `<title>` mendukung semua [element props yang umum.](/reference/react-dom/components/common#props) +======= +`<title>` supports all [common element props.](/reference/react-dom/components/common#common-props) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 * `children`: `<title>` hanya menerima teks sebagai anak. Teks ini akan menjadi judul dokumen. Anda juga dapat meng-oper komponen Anda sendiri selama komponen tersebut hanya me-*render* teks. diff --git a/src/content/reference/react-dom/createPortal.md b/src/content/reference/react-dom/createPortal.md index 27f24f4b81..692559452b 100644 --- a/src/content/reference/react-dom/createPortal.md +++ b/src/content/reference/react-dom/createPortal.md @@ -50,7 +50,11 @@ Sebuah portal hanya mengubah penempatan kerangka dari simpul DOM. Dalam hal lain * `domNode`: Beberapa simpul DOM, seperti yang dikembalikan oleh `document.getElementById()`. Simpul tersebut harus sudah ada. Melewatkan simpul DOM yang berbeda selama pembaruan akan menyebabkan konten portal dibuat ulang. +<<<<<<< HEAD * **opsional** `key`: Sebuah *string* atau angka unik yang akan digunakan sebagai [kunci](/learn/rendering-lists/#keeping-list-items-in-order-with-key) portal. +======= +* **optional** `key`: A unique string or number to be used as the portal's [key.](/learn/rendering-lists#keeping-list-items-in-order-with-key) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 #### Returns {/*returns*/} diff --git a/src/content/reference/react-dom/flushSync.md b/src/content/reference/react-dom/flushSync.md index 685354ef7a..a52d3ec675 100644 --- a/src/content/reference/react-dom/flushSync.md +++ b/src/content/reference/react-dom/flushSync.md @@ -131,3 +131,75 @@ Tanpa `flushSync`, dialog cetak akan menampilkan `isPrinting` sebagai "no". Ini Seringnya, `flushSync` dapat dihindari, maka gunakan `flushSync` sebagai pilihan terakhir. </Pitfall> + +--- + +## Troubleshooting {/*troubleshooting*/} + +### I'm getting an error: "flushSync was called from inside a lifecycle method" {/*im-getting-an-error-flushsync-was-called-from-inside-a-lifecycle-method*/} + + +React cannot `flushSync` in the middle of a render. If you do, it will noop and warn: + +<ConsoleBlock level="error"> + +Warning: flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task. + +</ConsoleBlock> + +This includes calling `flushSync` inside: + +- rendering a component. +- `useLayoutEffect` or `useEffect` hooks. +- Class component lifecycle methods. + +For example, calling `flushSync` in an Effect will noop and warn: + +```js +import { useEffect } from 'react'; +import { flushSync } from 'react-dom'; + +function MyComponent() { + useEffect(() => { + // 🚩 Wrong: calling flushSync inside an effect + flushSync(() => { + setSomething(newValue); + }); + }, []); + + return <div>{/* ... */}</div>; +} +``` + +To fix this, you usually want to move the `flushSync` call to an event: + +```js +function handleClick() { + // βœ… Correct: flushSync in event handlers is safe + flushSync(() => { + setSomething(newValue); + }); +} +``` + + +If it's difficult to move to an event, you can defer `flushSync` in a microtask: + +```js {3,7} +useEffect(() => { + // βœ… Correct: defer flushSync to a microtask + queueMicrotask(() => { + flushSync(() => { + setSomething(newValue); + }); + }); +}, []); +``` + +This will allow the current render to finish and schedule another syncronous render to flush the updates. + +<Pitfall> + +`flushSync` can significantly hurt performance, but this particular pattern is even worse for performance. Exhaust all other options before calling `flushSync` in a microtask as an escape hatch. + +</Pitfall> diff --git a/src/content/reference/react-dom/hooks/index.md b/src/content/reference/react-dom/hooks/index.md index 52d40ee5b1..04d1ab1bfb 100644 --- a/src/content/reference/react-dom/hooks/index.md +++ b/src/content/reference/react-dom/hooks/index.md @@ -4,7 +4,11 @@ title: "Hook React DOM Bawaan" <Intro> +<<<<<<< HEAD *Package* `react-dom` berisi Hooks yang hanya didukung untuk aplikasi web (yang berjalan di lingkunan DOM peramban). Hooks ini tidak didukung di lingkungan non-*peramban* seperti aplikasi iOS, Android, atau Windows. Jika Anda mencari Hooks yang didukung di peramban web *dan lingkungan lainnya* lihat [halaman React Hooks](/reference/react). Halaman ini mencantumkan semua Hooks dalam *package* `react-dom`. +======= +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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Intro> diff --git a/src/content/reference/react-dom/index.md b/src/content/reference/react-dom/index.md index c7c634908d..e9b07fd74d 100644 --- a/src/content/reference/react-dom/index.md +++ b/src/content/reference/react-dom/index.md @@ -21,7 +21,7 @@ API ini dapat di import dari komponen. Namun, jarang digunakan: 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 1a0a80a608..efcb7d5d06 100644 --- a/src/content/reference/react-dom/preinit.md +++ b/src/content/reference/react-dom/preinit.md @@ -10,7 +10,11 @@ Fungsi `preinit` saat ini hanya tersedia di kanal Canary dan eksperimental React <Note> +<<<<<<< HEAD [Framework berbasis React](/learn/start-a-new-react-project) sering kali menangani pemuatan sumber daya untuk Anda, jadi Anda mungkin tidak perlu memanggil API ini sendiri. Lihat dokumentasi framework Anda untuk detailnya. +======= +[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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Note> diff --git a/src/content/reference/react-dom/preinitModule.md b/src/content/reference/react-dom/preinitModule.md index 8145b7031d..3b9cc1a555 100644 --- a/src/content/reference/react-dom/preinitModule.md +++ b/src/content/reference/react-dom/preinitModule.md @@ -4,7 +4,11 @@ title: preinitModule <Note> +<<<<<<< HEAD [Framework berbasis React](/learn/start-a-new-react-project) sering kali menangani pemuatan sumber daya untuk Anda, jadi Anda mungkin tidak perlu memanggil API ini sendiri. Lihat dokumentasi framework Anda untuk detailnya. +======= +[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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Note> diff --git a/src/content/reference/react-dom/preload.md b/src/content/reference/react-dom/preload.md index c25c38af2f..b0f59e5b36 100644 --- a/src/content/reference/react-dom/preload.md +++ b/src/content/reference/react-dom/preload.md @@ -4,7 +4,11 @@ title: preload <Note> +<<<<<<< HEAD [Framework berbasis React](/learn/start-a-new-react-project) sering kali menangani pemuatan sumber daya untuk Anda, jadi Anda mungkin tidak perlu memanggil API ini sendiri. Lihat dokumentasi framework Anda untuk detailnya. +======= +[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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Note> diff --git a/src/content/reference/react-dom/preloadModule.md b/src/content/reference/react-dom/preloadModule.md index ebc2fa6d05..944d438fc8 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 72a28ec387..2f4a25080b 100644 --- a/src/content/reference/react-dom/server/index.md +++ b/src/content/reference/react-dom/server/index.md @@ -4,12 +4,17 @@ title: API React DOM Server <Intro> +<<<<<<< HEAD API `react-dom/server` memungkinkan Anda me-*render* komponen React menjadi HTML di *server*. API ini hanya digunakan di *server* pada *top level* aplikasi Anda untuk menghasilkan HTML awal. Kemungkinan [*framework*](/learn/start-a-new-react-project#production-grade-react-frameworks) akan memanggilnya untuk Anda. Sebagian besar komponen Anda tidak perlu mengimpor atau menggunakannya. +======= +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. +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 </Intro> --- +<<<<<<< HEAD ## API *Server* untuk Node.js *Stream* {/*server-apis-for-nodejs-streams*/} Beberapa *method* ini hanya tersedia di lingkungan dengan [Node.js *Stream*:](https://nodejs.org/api/stream.html) @@ -19,10 +24,33 @@ Beberapa *method* ini hanya tersedia di lingkungan dengan [Node.js *Stream*:](ht --- ## API *Server* untuk *Web Stream* {/*server-apis-for-web-streams*/} +======= +## Server APIs for Web Streams {/*server-apis-for-web-streams*/} +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 Beberapa *method* ini hanya tersedia di lingkungan dengan [*Web Stream*](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), yang mencakup peramban, Deno, dan beberapa *runtime* modern: +<<<<<<< HEAD * [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) me-*render* sebuah React *tree* ke dalam [*Readable Web Stream*.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) +======= +* [`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 Node.js Streams {/*server-apis-for-nodejs-streams*/} + +These methods are only available in the environments with [Node.js Streams:](https://nodejs.org/api/stream.html) + +* [`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) +>>>>>>> 38b52cfdf059b2efc5ee3223a758efe00319fcc7 --- 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 0000000000..17b48b2acf --- /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 0000000000..48caa3be64 --- /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 `