[Suggestion]: Document that hooks can be called after a conditional `throw`
还没有人认领这个 Issue。
- 主要语言
- JavaScript
- 星标
- 11.8k
- 派生
- 7.9k
- 平均合并
- 1 天 11 小时
- 30 天内合并 PR
- 11
描述
Summary
I don't believe it is documented anywhere that calling a hook after a conditional throw statement is not a violation of the rules of hooks. If this is a valid pattern, it should be documented. If it is not, the Eslint rule rules-of-hooks should warn for it.
Page
Rules of hooks
Details
I realised this is effectively the pattern when using Next.js app router notFound(), which throws an Error in the component render. I had assumed this not being flagged by the rules-of-hooks was a limitation of the Next.js eslint plugin, but actually, this is not flagged as an issue with a standard throw:
const Component = ({ someOtherCondition }) => {
const [foo, setFoo] = useState();
if (someOtherCondition) throw new Error();
const [bar, setBar] = useState();
return (<>...</>);
};
My assumption is this is a valid pattern as if someOtherCondition becomes true, the error will be thrown up the call stack to the nearest error boundary, and the render that was in-progress will be discarded. There is not a case to have this conditional throw call more hooks than the previous render, only less. The rules of hooks state:
It’s not supported to call Hooks (functions starting with use) in any other cases, for example:
🔴 Do not call Hooks inside conditions or loops.
🔴 Do not call Hooks after a conditional return statement.
In the example above, the second useState call comes after a conditional throw statement. Not quite either of the cases in documentation.
If this is a valid pattern, it should be mentioned in the docs, with potential warnings about it not being a recommended workaround to conditionally call hooks (as there is no way to resume execution of the other path of the conditional once an error is thrown from the component).
If this isn't a valid pattern, it should be flagged by the eslint rule.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Rules of Hooks 页面以及 issue 中描述的 rules-of-hooks 文档化行为开始。重现条件 throw 示例,然后确定页面是否需要澄清,或者 ESLint 规则是否应该更改;完成的标准是,该行为及其预期指导已经得到解决,并反映在适当的位置。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- eslint, javascript, next.js, react
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 35/100