reactjs / reactjs/react.dev

[Bug]: Documentation for hooks: warning about infinite loop useEffect with state update is not prominent

未关闭
#8,131 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug: unconfirmed
主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

Summary

Description

The documentation for React Hooks (especially useEffect) mentions that updating state inside an effect without a proper dependency array can cause infinite loops, but this warning is not highlighted prominently. Many beginners miss this and end up in render loops.

Given how frequently this issue occurs, the documentation should emphasize it more clearly, perhaps with a bold warning and a simple example.

Example that causes confusion

import React, { useState, useEffect } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(c => c + 1);
  }); // Missing dependency array

  return <div>{count}</div>;
}

Running this causes an infinite render loop because setCount triggers a state update on every render, re-invoking useEffect.

Actual behavior

  • Docs mention dependency arrays briefly, but the infinite loop risk is not highlighted enough.
  • Beginners often miss this and think React is “re-rendering infinitely” due to a bug.

Expected behavior

  • The official docs should include a bold, visible warning in the useEffect section, such as:

Warning: Omitting the dependency array causes the effect to run after every render, potentially leading to infinite loops if state or props are updated inside.

  • Include a small “bad vs. good” code example pair to clarify.

Why this matters

This is one of the most common pitfalls for new React developers. Making the warning prominent in official docs will help reduce confusion and GitHub issues related to infinite re-renders.

Environment

  • React version: 18.x (or whichever version is current)
  • Browser: Chrome 118
  • OS: Windows 11 / Ubuntu 22.04

Additional info

Several discussions online highlight this confusion; here’s one example:
https://www.reddit.com/r/reactjs/comments/oomo1w/what_are_the_biggest_issues_you_see_with_react_in/

Page

https://react.dev/reference/react/useEffect

Details

The warning could be moved closer to the main example or highlighted with a strong visual cue (e.g., bold text or a red caution box).
This would help prevent confusion among new React users who encounter infinite loop behavior.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中链接的 useEffect 参考页面开始,检查当前对依赖数组和主要示例的说明方式。突出显示关于无限循环的警告,并添加一个简洁的错误示例与正确示例,然后确认页面清楚地说明了在没有依赖数组的情况下从 effect 更新 state 的风险。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
52/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。