docs-writer-reference

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

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 (
    <Something>
    )? Use Type B (Component)
  3. Is it a compiler configuration option? Use Type C (Configuration)
  4. Is it a directive (
    'use something'
    )? Use Type D (Directive)
  5. Is it an ESLint rule? Use Type E (ESLint Rule)
  6. Is it listing multiple APIs? Use Type F (Index/Category)
  1. 是Hook吗?使用类型A(Hook/函数)
  2. 是React组件(
    <Something>
    )吗?使用类型B(组件)
  3. 是编译器配置选项吗?使用类型C(配置)
  4. 是指令(
    'use something'
    )吗?使用类型D(指令)
  5. 是ESLint规则吗?使用类型E(ESLint规则)
  6. 是列出多个API的页面吗?使用类型F(索引/分类)

Component Selection

组件选择

For component selection and patterns, invoke
/docs-components
.

如需了解组件选择和相关模式,请查看
/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

语气: 权威的技术参考文档撰写者 语调: 精准、全面、中立
如需了解语调、大小写、术语和行文模式,请查看
/docs-voice
建议:
  • 以单行描述开头:"
    useState
    是一个React Hook,可让你..."
  • 为每个API包含参数、返回值、注意事项章节
  • 记录大多数开发者会遇到的边缘情况
  • 在主要章节之间使用分隔线
  • 包含“查看下方更多示例”的链接
  • 表述直接,避免含糊 - 用“这是为...设计的”而非“这有助于避免...的问题”
  • 陈述事实而非优势 - 用“回调始终访问最新值”而非“这有助于避免闭包过时问题”
  • 使用简洁且有意义的命名 - 用
    onEvent
    onTick
    而非
    onSomething
禁忌:
  • 跳过InlineToc组件
  • 省略错误案例或注意事项
  • 使用口语化语言
  • 将教学内容与参考内容混合(那是Learn板块的职责)
  • 记录已修复的历史Bug
  • 包含小众边缘情况(如
    this
    绑定、罕见的类模式)
  • 添加解释“你为什么需要这个”的表述 - 使用场景章节的示例会说明这一点
  • 例外:Pitfall和DeepDive附注可使用略带口语化的表述

Page Templates

页面模板

Type A: Hook/Function

类型A:Hook/函数

When to use: Documenting React hooks and standalone functions (useState, useEffect, memo, lazy, etc.)
mdx
---
title: hookName
---

<Intro>

`hookName` is a React Hook that lets you [brief description].

```js
const result = hookName(arg)
</Intro> <InlineToc />
适用场景: 记录React Hook和独立函数(useState、useEffect、memo、lazy等)
mdx
---
title: hookName
---

<Intro>

`hookName` 是一个React Hook,可让你[简要描述]。

```js
const result = hookName(arg)
</Intro> <InlineToc />

Reference {/reference/}

参考 {/reference/}

hookName(arg)
{/hookname/}

hookName(arg)
{/hookname/}

Call
hookName
at the top level of your component to...
js
[signature example with annotations]
在组件的顶层调用
hookName
以...
js
[带注释的签名示例]

Parameters {/parameters/}

参数 {/parameters/}

  • arg
    : Description of the parameter.
  • arg
    : 参数说明。

Returns {/returns/}

返回值 {/returns/}

Description of return value.
返回值说明。

Caveats {/caveats/}

注意事项 {/caveats/}

  • Important caveat about usage.

  • 重要的使用注意事项。

Usage {/usage/}

使用场景 {/usage/}

Common Use Case {/common-use-case/}

常见用例 {/common-use-case/}

Explanation with Sandpack examples...

带Sandpack示例的说明...

Troubleshooting {/troubleshooting/}

问题排查 {/troubleshooting/}

Common Problem {/common-problem/}

常见问题 {/common-problem/}

How to solve it...

---
解决方法...

---

Type B: Component

类型B:组件

When to use: Documenting React components (Suspense, Fragment, Activity, StrictMode)
mdx
---
title: <ComponentName>
---

<Intro>

`<ComponentName>` lets you [primary action].

```js
<ComponentName prop={value}>
  <Children />
</ComponentName>
</Intro> <InlineToc />
适用场景: 记录React组件(Suspense、Fragment、Activity、StrictMode)
mdx
---
title: <ComponentName>
---

<Intro>

`<ComponentName>` 可让你[主要功能]。

```js
<ComponentName prop={value}>
  <Children />
</ComponentName>
</Intro> <InlineToc />

Reference {/reference/}

参考 {/reference/}

<ComponentName>
{/componentname/}

<ComponentName>
{/componentname/}

[Component purpose and behavior]
[组件用途和行为说明]

Props {/props/}

属性 {/props/}

  • propName
    : Description of the prop...
  • optional
    optionalProp
    : Description...
  • propName
    : 属性说明...
  • 可选
    optionalProp
    : 说明...

Caveats {/caveats/}

注意事项 {/caveats/}

  • [Caveats specific to this component]

**Key differences from Hook pages:**
- Title uses JSX syntax: `<ComponentName>`
- Uses `#### Props` instead of `#### Parameters`
- Reference heading uses JSX: `` ### `<ComponentName>` ``

---
  • [该组件特有的注意事项]

**与Hook页面的主要区别:**
- 标题使用JSX语法:`<ComponentName>`
- 使用`#### 属性`而非`#### 参数`
- 参考标题使用JSX:`` ### `<ComponentName>` ``

---

Type C: Configuration

类型C:配置

When to use: Documenting React Compiler configuration options
mdx
---
title: optionName
---

<Intro>

The `optionName` option [controls/specifies/determines] [what it does].

</Intro>

```js
{
  optionName: 'value' // Quick example
}
<InlineToc />
适用场景: 记录React Compiler配置选项
mdx
---
title: optionName
---

<Intro>

`optionName`选项[控制/指定/决定][功能描述]。

</Intro>

```js
{
  optionName: 'value' // 快速示例
}
<InlineToc />

Reference {/reference/}

参考 {/reference/}

optionName
{/optionname/}

optionName
{/optionname/}

[Description of the option's purpose]
[选项用途说明]

Type {/type/}

类型 {/type/}

'value1' | 'value2' | 'value3'
'value1' | 'value2' | 'value3'

Default value {/default-value/}

默认值 {/default-value/}

'value1'
'value1'

Options {/options/}

可选值 {/options/}

  • 'value1'
    (default): Description
  • 'value2'
    : Description
  • 'value3'
    : Description
  • 'value1'
    (默认):说明
  • 'value2'
    :说明
  • 'value3'
    :说明

Caveats {/caveats/}

注意事项 {/caveats/}

  • [Usage caveats]

---
  • [使用注意事项]

---

Type D: Directive

类型D:指令

When to use: Documenting directives like 'use server', 'use client', 'use memo'
mdx
---
title: "'use directive'"
titleForTitleTag: "'use directive' directive"
---

<RSC>

`'use directive'` is for use with [React Server Components](/reference/rsc/server-components).

</RSC>

<Intro>

`'use directive'` marks [what it marks] for [purpose].

```js {1}
function MyComponent() {
  'use directive';
  // ...
}
</Intro> <InlineToc />
适用场景: 记录
'use server'
'use client'
'use memo'
等指令
mdx
---
title: "'use directive'"
titleForTitleTag: "'use directive' directive"
---

<RSC>

`'use directive'` 用于[React Server Components](/reference/rsc/server-components)。

</RSC>

<Intro>

`'use directive'` 标记[标记对象]以[用途]。

```js {1}
function MyComponent() {
  'use directive';
  // ...
}
</Intro> <InlineToc />

Reference {/reference/}

参考 {/reference/}

'use directive'
{/use-directive/}

'use directive'
{/use-directive/}

Add
'use directive'
at the beginning of [location] to [action].
在[位置]的开头添加
'use directive'
以[作用]。

Caveats {/caveats/}

注意事项 {/caveats/}

  • 'use directive'
    must be at the very beginning...
  • The directive must be written with single or double quotes, not backticks.
  • [Other placement/syntax caveats]

**Key characteristics:**
- Title includes quotes: `title: "'use server'"`
- Uses `titleForTitleTag` for browser tab title
- `<RSC>` block appears before `<Intro>`
- Caveats focus on placement and syntax requirements

---
  • 'use directive'
    必须放在最开头...
  • 指令必须使用单引号或双引号,不能使用反引号。
  • [其他位置/语法注意事项]

**主要特征:**
- 标题包含引号:`title: "'use server'"`
- 使用`titleForTitleTag`设置浏览器标签页标题
- `<RSC>`块出现在`<Intro>`之前
- 注意事项重点关注位置和语法要求

---

Type E: ESLint Rule

类型E:ESLint规则

When to use: Documenting ESLint plugin rules
mdx
---
title: rule-name
---

<Intro>
Validates that [what the rule checks].
</Intro>
适用场景: 记录ESLint插件规则
mdx
---
title: rule-name
---

<Intro>
验证[规则检查内容]。
</Intro>

Rule Details {/rule-details/}

规则详情 {/rule-details/}

[Explanation of why this rule exists and React's underlying assumptions]
[说明该规则存在的原因以及React的底层假设]

Common Violations {/common-violations/}

常见违规情况 {/common-violations/}

[Description of violation patterns]
[违规模式说明]

Invalid {/invalid/}

无效代码 {/invalid/}

Examples of incorrect code for this rule:
js
// X Missing dependency
useEffect(() => {
  console.log(count);
}, []); // Missing 'count'
该规则的错误代码示例:
js
// ❌ 缺少依赖项
useEffect(() => {
  console.log(count);
}, []); // 缺少'count'

Valid {/valid/}

有效代码 {/valid/}

Examples of correct code for this rule:
js
// checkmark All dependencies included
useEffect(() => {
  console.log(count);
}, [count]);
该规则的正确代码示例:
js
// ✅ 包含所有依赖项
useEffect(() => {
  console.log(count);
}, [count]);

Troubleshooting {/troubleshooting/}

问题排查 {/troubleshooting/}

[Problem description] {/problem-slug/}

[问题描述] {/problem-slug/}

[Solution]
[解决方案]

Options {/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

类型F:索引/分类

When to use: Overview pages listing multiple APIs in a category
mdx
---
title: "Built-in React [Type]"
---

<Intro>

*Concept* let you [purpose]. Brief scope statement.

</Intro>

---
适用场景: 列出某一分类下多个API的概览页面
mdx
---
title: "内置React [类型]"
---

<Intro>

*概念*可让你[用途]。简要范围说明。

</Intro>

---

Category Name {/category-name/}

分类名称 {/category-name/}

Concept explanation with Learn section link.
To [action], use one of these [Type]:
js
function Example() {
  const value = useHookName(args);
}

概念说明,附带Learn板块链接
要[操作],可使用以下[类型]之一:
js
function Example() {
  const value = useHookName(args);
}

Your own [Type] {/your-own-type/}

自定义[类型] {/your-own-type/}

You can also define your own as JavaScript functions.

**Key characteristics:**
- Title format: "Built-in React [Type]"
- Italicized concept definitions
- Horizontal rules between sections
- Closes with "Your own [Type]" section

---
你也可以自定义为JavaScript函数。

**主要特征:**
- 标题格式:“内置React [类型]”
- 概念定义使用斜体
- 章节之间使用水平分隔线
- 以“自定义[类型]”章节结尾

---

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
undefined
适用场景: 当Hook返回的函数需要单独文档时(如useState的setter、useReducer的dispatch)
md
undefined

hookName(args)
{/hookname/}

hookName(args)
{/hookname/}

[Main hook documentation]
[主Hook文档]

Parameters {/parameters/}

参数 {/parameters/}

Returns {/returns/}

返回值 {/returns/}

Caveats {/caveats/}

注意事项 {/caveats/}



set
functions, like
setSomething(nextState)
{/setstate/}

set
函数,如
setSomething(nextState)
{/setstate/}

The
set
function returned by
hookName
lets you [action].
hookName
返回的
set
函数可让你[操作]。

Parameters {/setstate-parameters/}

参数 {/setstate-parameters/}

Returns {/setstate-returns/}

返回值 {/setstate-returns/}

Caveats {/setstate-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"

---

**主要约定:**
- 使用水平分隔线(`---`)分隔主Hook和返回的函数
- 标题ID包含前缀:`{/*setstate-parameters*/}` 对比 `{/*parameters*/}`
- 使用通用名称:“set函数”而非“setCount”

---

Compound Return Objects

复合返回对象

When to use: When a function returns an object with multiple properties/methods (createContext)
md
undefined
适用场景: 当函数返回包含多个属性/方法的对象时(如createContext)
md
undefined

createContext(defaultValue)
{/createcontext/}

createContext(defaultValue)
{/createcontext/}

[Main function documentation]
[主函数文档]

Returns {/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.

createContext
返回一个上下文对象。
上下文对象本身不存储任何信息。 它代表...
  • SomeContext
    可让你提供上下文值。
  • SomeContext.Consumer
    是读取上下文的替代方式。

SomeContext
Provider {/provider/}

SomeContext
Provider {/provider/}

[Documentation for Provider]
[Provider文档]

Props {/provider-props/}

属性 {/provider-props/}



SomeContext.Consumer
{/consumer/}

SomeContext.Consumer
{/consumer/}

[Documentation for Consumer]
[Consumer文档]

Props {/consumer-props/}

属性 {/consumer-props/}


---

---

Writing Patterns

写作模式

Opening Lines by Page Type

按页面类型划分的开篇句式

Page TypePatternExample
Hook
`hookName` is a React Hook that lets you [action].
"
useState
is a React Hook that lets you add a state variable to your component."
Component
`<ComponentName>` lets you [action].
"
<Suspense>
lets you display a fallback until its children have finished loading."
API
`apiName` lets you [action].
"
memo
lets you skip re-rendering a component when its props are unchanged."
Configuration
The `optionName` option [controls/specifies/determines] [what].
"The
target
option specifies which React version the compiler generates code for."
Directive
`'directive'` [marks/opts/prevents] [what] for [purpose].
"
'use server'
marks a function as callable from the client."
ESLint Rule
Validates that [condition].
"Validates that dependency arrays for React hooks contain all necessary dependencies."

页面类型句式示例
Hook
`hookName` 是一个React Hook,可让你[操作]。
"
useState
是一个React Hook,可让你为组件添加状态变量。"
组件
`<ComponentName>` 可让你[操作]。
"
<Suspense>
可让你在子组件加载完成前显示回退内容。"
API
`apiName` 可让你[操作]。
"
memo
可让你在组件属性未变化时跳过重新渲染。"
配置
`optionName`选项[控制/指定/决定][功能]。
"
target
选项指定编译器生成代码所针对的React版本。"
指令
`'directive'` [标记/启用/阻止][对象]以[用途]。
"
'use server'
将函数标记为可从客户端调用。"
ESLint规则
验证[条件]。
"验证React Hook的依赖数组是否包含所有必要的依赖项。"

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`.

简单参数:
md
* `paramName`: 参数功能说明。
可选参数:
md
* **可选** `paramName`: 参数功能说明。
具有特殊函数行为的参数:
md
* `initialState`: 你希望状态初始化为的值。可以是任意类型,但传入函数时有特殊行为。该参数在初始渲染后会被忽略。
  * 如果传入函数作为`initialState`,它将被视为_初始化函数_。它应该是纯函数,不接受参数,返回任意类型的值。
带子参数的回调参数:
md
* `subscribe`: 接收单个`callback`参数并将其订阅到存储的函数。当存储内容变化时,应调用提供的`callback``subscribe`函数应返回一个用于清理订阅的函数。
嵌套选项对象:
md
* **可选** `options`: 包含React根选项的对象。
  * **可选** `onCaughtError`: 当React在Error Boundary中捕获错误时调用的回调。
  * **可选** `onUncaughtError`: 当错误被抛出且未被捕获时调用的回调。
  * **可选** `identifierPrefix`: React用于`useId`生成ID的字符串前缀。

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.

单值返回:
md
`hookName`返回当前值。在首次渲染时,该值与`initialValue`相同。
数组返回(编号列表):
md
`useState`返回一个恰好包含两个值的数组:

1. 当前状态。在首次渲染时,它与你传入的`initialState`一致。
2. 用于更新状态为不同值并触发重新渲染的[`set`函数](#setstate)
对象返回(项目符号列表):
md
`createElement`返回一个包含以下几个属性的React元素对象:

* `type`: 你传入的`type`* `props`: 你传入的`props``ref``key`除外)。
* `ref`: 你传入的`ref`。如果未传入,则为`null`* `key`: 你传入的`key`,被转换为字符串。如果未传入,则为`null`
Promise返回:
md
`prerender`返回一个Promise:
- 如果渲染成功,Promise将解析为包含以下内容的对象:
  - `prelude`: HTML的[Web Stream](MDN-link)  - `postponed`: 可序列化的JSON对象,用于恢复渲染。
- 如果渲染失败,Promise将被拒绝。
包装函数返回:
md
`cache`返回`fn`的缓存版本,具有相同的类型签名。在此过程中不会调用`fn`
当使用给定参数调用`cachedFn`时,它首先检查是否存在缓存结果。如果有缓存,则返回结果;如果没有,则调用`fn`,存储结果并返回。

Caveats Patterns

注意事项模式

Standard Hook caveat (almost always first for Hooks):
md
* `useXxx` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
Stable identity caveat (for returned functions):
md
* The `set` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire.
Strict Mode caveat:
md
* In Strict Mode, React will **call your render function twice** in order to help you find accidental impurities. This is development-only behavior and does not affect production.
Caveat with code example:
md
* It's not recommended to _suspend_ a render based on a store value returned by `useSyncExternalStore`. For example, the following is discouraged:

  ```js
  const selectedProductId = useSyncExternalStore(...);
  const data = use(fetchItem(selectedProductId)) // X Don't suspend based on store value

**Canary caveat:**
```md
* <CanaryBadge /> If you want to pass `ref` to a Fragment, you can't use the `<>...</>` syntax.

标准Hook注意事项(Hook的第一条注意事项几乎总是这个):
md
* `useXxx`是一个Hook,因此你只能在**组件或自定义Hook的顶层**调用它。不能在循环或条件语句中调用。如果需要,请提取新组件并将状态移入其中。
稳定标识注意事项(针对返回的函数):
md
* `set`函数具有稳定的标识,因此你经常会看到它被排除在Effect的依赖项之外,但将其包含在内也不会导致Effect触发。
严格模式注意事项:
md
* 在严格模式下,React会**调用你的渲染函数两次**,以帮助你发现意外的不纯操作。这仅在开发环境中存在,不影响生产环境。
带代码示例的注意事项:
md
* 不建议基于`useSyncExternalStore`返回的存储值来暂停渲染。例如,不建议以下写法:

  ```js
  const selectedProductId = useSyncExternalStore(...);
  const data = use(fetchItem(selectedProductId)) // ❌ 不要基于存储值暂停渲染

**Canary版本注意事项:**
```md
* <CanaryBadge /> 如果你想将`ref`传递给Fragment,不能使用`<>...</>`语法。

Troubleshooting Patterns

问题排查模式

Heading format (first person problem statements):
md
undefined
标题格式(第一人称问题陈述):
md
undefined

I've updated the state, but logging gives me the old value {/old-value/}

我更新了状态,但日志显示旧值 {/old-value/}

My initializer or updater function runs twice {/runs-twice/}

我的初始化函数或更新函数运行了两次 {/runs-twice/}

I want to read the latest state from a callback {/read-latest-state/}

我想从回调中读取最新状态 {/read-latest-state/}


**Error message format:**
```md

**错误消息格式:**
```md

I'm getting an error: "Too many re-renders" {/too-many-rerenders/}

我遇到了错误:“Too many re-renders” {/too-many-rerenders/}

I'm getting an error: "Rendered more hooks than during the previous render" {/more-hooks/}

我遇到了错误:“Rendered more hooks than during the previous render” {/more-hooks/}


**Lint error format:**
```md

**Lint错误格式:**
```md

I'm getting a lint error: "[exact error message]" {/lint-error-slug/}

我遇到了Lint错误:“[确切错误消息]” {/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

---

**问题-解决方案结构:**
1. 陈述问题并展示有问题的代码
2. 解释原因
3. 提供修复后的代码解决方案
4. 链接到Learn板块以深入了解

---

Code Comment Conventions

代码注释约定

For code comment conventions (wrong/right, legacy/recommended, server/client labeling, bundle size annotations), invoke
/docs-sandpack
.

如需了解代码注释约定(错误/正确、旧版/推荐、服务端/客户端标记、包大小注释),请查看
/docs-sandpack

Link Description Patterns

链接描述模式

PatternExample
"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
.
"
"Similar to""Similar to
useTransition
.
"

模式示例
"lets you" + 操作"
memo
lets you skip re-rendering when props are unchanged."
"declares" + 对象"
useState
declares a state variable that you can update directly."
"reads" + 对象"
useContext
reads and subscribes to a context."
"connects" + 对象"
useEffect
connects a component to an external system."
"Used with""Used with
useContext
.
"
"Similar to""Similar to
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
.
如需了解完整的MDX组件模式(Note、Pitfall、DeepDive、Recipes、Deprecated、RSC、Canary、Diagram、Code Steps),请查看
/docs-components
如需了解Sandpack特有的模式和代码风格,请查看
/docs-sandpack

Reference-Specific Component Rules

参考页面专属组件规则

Component placement in Reference pages:
  • <RSC>
    goes before
    <Intro>
    at top of page
  • <Deprecated>
    goes after
    <Intro>
    for page-level deprecation
  • <Deprecated>
    goes after method heading for method-level deprecation
  • <Canary>
    wrapper goes inline within
    <Intro>
  • <CanaryBadge />
    appears in headings, props lists, and caveats
Troubleshooting-specific components:
  • Use first-person problem headings
  • Cross-reference Pitfall IDs when relevant
Callout spacing:
  • Never place consecutive Pitfalls or consecutive Notes
  • Combine related warnings into one with titled subsections, or separate with prose/code
  • Consecutive DeepDives OK for multi-part explorations
  • See
    /docs-components
    Callout Spacing Rules

参考页面中的组件位置:
  • <RSC>
    放在页面顶部的
    <Intro>
    之前
  • <Deprecated>
    在页面级弃用时放在
    <Intro>
    之后
  • <Deprecated>
    在方法级弃用时放在方法标题之后
  • <Canary>
    包装器内联在
    <Intro>
  • <CanaryBadge />
    出现在标题、属性列表和注意事项中
问题排查专属组件:
  • 使用第一人称问题标题
  • 相关时交叉引用Pitfall ID
提示框间距:
  • 不要连续放置Pitfall或Note
  • 将相关警告合并到一个带小标题的组件中,或用正文/代码分隔
  • 连续放置DeepDive是允许的,用于多部分探索
  • 请查看
    /docs-components
    中的提示框间距规则

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."
  • 一句话,约15个词以内 - 说明Hook的功能,而非工作原理
  • ✅ "
    useEffectEvent
    是一个React Hook,可让你将事件与Effect分离。"
  • ❌ "
    useEffectEvent
    是一个React Hook,可让你将非响应式逻辑从Effect中提取到名为Effect Event的可重用函数中。"

Reference Code Example

参考代码示例

  • Show just the API call (5-10 lines), not a full component
  • Move full component examples to Usage section
  • 仅展示API调用(5-10行),而非完整组件
  • 将完整组件示例移至使用场景章节

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
  1. 第一个示例:核心思维模型 - 展示最典型的用例和最简单的具体示例
  2. 后续示例:典型用例 - 说明“为什么”(如“避免重新连接到外部系统”),展示具体的“怎么做”
    • 优先选择广泛的典型用例,而非多个狭窄的具体示例
    • 章节标题就是教学内容 - “我什么时候会用到这个?”应该能从标题中找到答案

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)
  • 绝不记录已修复的历史Bug
  • 包含大多数开发者会遇到的边缘情况
  • 排除小众边缘情况(如
    this
    绑定、罕见的类模式)

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
  • 包含linter强制执行的规则或会导致直接错误的规则
  • 包含基本的使用限制
  • 排除实现细节,除非它们影响使用
  • 排除其他地方已解释过的重复内容
  • 尽可能将每条注意事项控制在一句话以内

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
  • 仅使用错误标题:“我遇到了错误:'[消息]'”格式
  • 绝不记录已修复的历史Bug - 如果已修复,就不属于这里
  • 聚焦于开发者当前实际会遇到的错误

DeepDive Content

DeepDive内容

  • 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

  • 适中原则 - 足够深入以满足好奇的开发者,但又不会过于冗长
  • 回答“为什么要这样设计?”而非详尽的技术细节
  • 跳过此部分的读者不应错过使用API的任何必要信息
  • 如果解释变得过长,你可能解释得太多了

Domain-Specific Guidance

领域特定指南

Hooks

Hooks

Returned function documentation:
  • Document setter/dispatch functions as separate
    ###
    sections
  • Use generic names: "set functions" not "setCount"
  • Include stable identity caveat for returned functions
Dependency array documentation:
  • List what counts as reactive values
  • Explain when dependencies are ignored
  • Link to removing effect dependencies guide
Recipes usage:
  • Group related examples with meaningful titleText
  • Each recipe has brief intro, Sandpack, and
    <Solution />

返回函数的文档:
  • 将setter/dispatch函数作为单独的
    ###
    章节记录
  • 使用通用名称:“set函数”而非“setCount”
  • 为返回的函数包含稳定标识注意事项
依赖数组文档:
  • 列出哪些属于响应式值
  • 解释何时会忽略依赖项
  • 链接到移除Effect依赖项的指南
Recipes使用:
  • 用有意义的titleText分组相关示例
  • 每个Recipe包含简短介绍、Sandpack和
    <Solution />

Components

组件

Props documentation:
  • Use
    #### Props
    instead of
    #### Parameters
  • Mark optional props with
    **optional**
    prefix
  • Use
    <CanaryBadge />
    inline for canary-only props
JSX syntax in titles/headings:
  • Frontmatter title:
    title: <Suspense>
  • Reference heading:
    ### `<Suspense>` {/*suspense*/}

属性文档:
  • 使用
    #### 属性
    而非
    #### 参数
  • **可选**
    前缀标记可选属性
  • 对仅在Canary版本中可用的属性使用内联
    <CanaryBadge />
标题/标题中的JSX语法:
  • 前置元数据标题:
    title: <Suspense>
  • 参考标题:
    ### `<Suspense>` {/*suspense*/}

React-DOM

React-DOM

Common props linking:
md
`<input>` supports all [common element props.](/reference/react-dom/components/common#common-props)
Props categorization:
  • Controlled vs uncontrolled props grouped separately
  • Form-specific props documented with action patterns
  • MDN links for standard HTML attributes
Environment-specific notes:
mdx
<Note>

This API is specific to Node.js. Environments with [Web Streams](MDN-link), like Deno and modern edge runtimes, should use [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) instead.

</Note>
Progressive enhancement:
  • Document benefits for users without JavaScript
  • Explain Server Function + form action integration
  • Show hidden form field and
    .bind()
    patterns

通用属性链接:
md
`<input>` 支持所有[通用元素属性。](/reference/react-dom/components/common#common-props)
属性分类:
  • 受控属性和非受控属性分开分组
  • 表单特定属性结合操作模式记录
  • 为标准HTML属性添加MDN链接
环境特定说明:
mdx
<Note>

此API特定于Node.js。支持[Web Streams](MDN-link)的环境(如Deno和现代边缘运行时)应使用[`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream)替代。

</Note>
渐进式增强:
  • 记录无JavaScript时对用户的好处
  • 解释Server Function + 表单操作的集成
  • 展示隐藏表单字段和
    .bind()
    模式

RSC

RSC

RSC banner (before Intro): Always place
<RSC>
component before
<Intro>
for Server Component-only APIs.
Serialization type lists: When documenting Server Function arguments, list supported types:
md
Supported types for Server Function arguments:

* Primitives
	* [string](MDN-link)
	* [number](MDN-link)
* Iterables containing serializable values
	* [Array](MDN-link)
	* [Map](MDN-link)

Notably, these are not supported:
* React elements, or [JSX](/learn/writing-markup-with-jsx)
* Functions (other than Server Functions)
Bundle size comparisons:
  • Show "Not included in bundle" for server-only imports
  • Annotate client bundle sizes with gzip:
    // 35.9K (11.2K gzipped)

RSC横幅(在Intro之前): 对于仅适用于Server Component的API,始终将
<RSC>
组件放在
<Intro>
之前。
序列化类型列表: 记录Server Function参数时,列出支持的类型:
md
Server Function参数支持的类型:

* 基本类型
	* [string](MDN-link)
	* [number](MDN-link)
* 包含可序列化值的可迭代对象
	* [Array](MDN-link)
	* [Map](MDN-link)

不支持的类型:
* React元素或[JSX](/learn/writing-markup-with-jsx)
* 函数(Server Function除外)
包大小比较:
  • 对仅在服务端导入的内容标注“不包含在客户端包中”
  • 标注客户端包的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

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

规则详情章节:
  • 解释“为什么”而非仅“是什么”
  • 聚焦于React的底层假设
  • 描述违规的后果
无效/有效章节:
  • 标准简介:“以下是该规则的[不]正确代码示例:”
  • 无效代码使用❌表情,有效代码使用✅表情
  • 展示解释违规原因的内联注释
配置选项:
  • 展示共享设置(优先选择)
  • 展示规则级选项(向后兼容)
  • 说明两者同时存在时的优先级

Edge Cases

边缘情况

For deprecated, canary, and version-specific component patterns (placement, syntax, examples), invoke
/docs-components
.
Quick placement rules:
  • <Deprecated>
    after
    <Intro>
    for page-level, after heading for method-level
  • <Canary>
    wrapper inline in Intro,
    <CanaryBadge />
    in headings/props/caveats
  • Version notes use
    <Note>
    with "Starting in React 19..." pattern
Removed APIs on index pages:
md
undefined
如需了解已弃用、Canary版本和特定版本的组件模式(位置、语法、示例),请查看
/docs-components
快速位置规则:
  • <Deprecated>
    在页面级弃用时放在
    <Intro>
    之后,在方法级弃用时放在标题之后
  • <Canary>
    包装器内联在Intro中,
    <CanaryBadge />
    放在标题/属性/注意事项中
  • 版本说明使用
    <Note>
    并采用“从React 19开始...”的模式
索引页面上的已移除API:
md
undefined

Removed APIs {/removed-apis/}

已移除API {/removed-apis/}

These APIs were removed in React 19:

Link to previous version docs (18.react.dev) for removed API documentation.

---
这些API在React 19中被移除:

链接到旧版本文档(18.react.dev)查看已移除API的文档。

---

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
    <InlineToc />
    after Intro
  7. Consistent parameter format: Use
    * \
    paramName`: description
    with
    optional` prefix for optional params
  8. Numbered lists for array returns: When hooks return arrays, use numbered lists in Returns section
  9. Generic names for returned functions: Use "set functions" not "setCount"
  10. Props vs Parameters: Use
    #### Props
    for Components (Type B),
    #### Parameters
    for Hooks/APIs (Type A)
  11. RSC placement:
    <RSC>
    component goes before
    <Intro>
    , not after
  12. Canary markers: Use
    <Canary>
    wrapper inline in Intro,
    <CanaryBadge />
    in headings/props
  13. Deprecated placement:
    <Deprecated>
    goes after
    <Intro>
    for page-level, after heading for method-level
  14. Code comment emojis: Use X for wrong, checkmark for correct in code examples
  15. No consecutive Pitfalls/Notes: Combine into one component with titled subsections, or separate with prose/code (see
    /docs-components
    )
For component heading level conventions (DeepDive, Pitfall, Note, Recipe headings), see
/docs-components
.
  1. 必须设置标题ID:
    ## 标题 {/*title-id*/}
    (小写,连字符分隔)
  2. Sandpack主文件需要
    export default
  3. 活动文件语法:
    ```js src/File.js active
  4. 问题排查中的错误标题: 使用
    ### 我遇到了错误:“[消息]” {/*id*/}
  5. 必须使用章节分隔线(
    ---
    分隔标题(见下方章节分隔线)
  6. 必须包含InlineToc: 始终在Intro之后包含
    <InlineToc />
  7. 参数格式一致: 使用
    * \
    paramName`: 说明
    ,可选参数前缀为
    可选`
  8. 数组返回使用编号列表: 当Hook返回数组时,在返回值章节使用编号列表
  9. 返回函数使用通用名称: 使用“set函数”而非“setCount”
  10. 属性vs参数: 组件(类型B)使用
    #### 属性
    ,Hook/API(类型A)使用
    #### 参数
  11. RSC位置:
    <RSC>
    组件放在
    <Intro>
    之前,而非之后
  12. Canary标记:
    <Canary>
    包装器内联在Intro中,
    <CanaryBadge />
    放在标题/属性/注意事项中
  13. Deprecated位置:
    <Deprecated>
    在页面级弃用时放在
    <Intro>
    之后,在方法级弃用时放在标题之后
  14. 代码注释表情: 错误代码使用❌,正确代码使用✅
  15. 不要连续放置Pitfall/Note: 合并到一个带小标题的组件中,或用正文/代码分隔(查看
    /docs-components
如需了解组件标题层级约定(DeepDive、Pitfall、Note、Recipe标题),请查看
/docs-components

Section Dividers

章节分隔线

Use
---
horizontal rules to visually separate major sections:
  • After
    <InlineToc />
    - Before
    ## Reference
    heading
  • Between API subsections - Between different function/hook definitions (e.g., between
    useState()
    and
    set functions
    )
  • Before
    ## Usage
    - Separates API reference from examples
  • Before
    ## Troubleshooting
    - Separates content from troubleshooting
  • Between EVERY Usage subsections - When switching to a new major use case
Always have a blank line before and after
---
.
使用
---
水平分隔线可视化分隔主要章节:
  • <InlineToc />
    之后
    - 在
    ## 参考
    标题之前
  • 在API子章节之间 - 在不同函数/Hook定义之间(如
    useState()
    set函数
    之间)
  • ## 使用场景
    之前
    - 分隔API参考和示例
  • ## 问题排查
    之前
    - 分隔内容和问题排查
  • 在每个使用场景子章节之间 - 切换到新的主要用例时
---
前后必须各有一个空行。

Section ID Conventions

章节ID约定

SectionID 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*/}
章节ID格式
主函数
{/*functionname*/}
返回的函数
{/*setstate*/}
,
{/*dispatch*/}
返回函数的子章节
{/*setstate-parameters*/}
问题排查项
{/*problem-description-slug*/}
Pitfall
{/*pitfall-description*/}
Deep dive
{/*deep-dive-topic*/}