react/no-deriving-state-in-effects Perf
作用
禁止在 effect 中从状态派生值并将其存回状态;派生值应在渲染期间计算。
由 React Compiler 提供支持,该编译器会针对每个文件运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/no-deriving-state-in-effects。
为什么这是不好的做法?
在 effect 中派生状态会导致每次更新都额外进行一次渲染,并使派生副本与其来源失去同步。
示例
此规则的错误代码示例:
jsx
import { useEffect, useState } from "react";
function Component() {
const [firstName] = useState("Taylor");
const [lastName] = useState("Swift");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
return <div>{fullName}</div>;
}此规则的正确代码示例:
jsx
function Component({ firstName, lastName }) {
const fullName = firstName + " " + lastName;
return <div>{fullName}</div>;
}使用方法
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-deriving-state-in-effects": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-deriving-state-in-effects": "error",
},
});bash
oxlint --deny react/no-deriving-state-in-effects --react-plugin版本
此规则在 vnext 中添加。
