component-hook-factories

验证是否定义嵌套组件或钩子的高阶函数。组件和钩子应该在模块级别定义。

¥Validates against higher order functions defining nested components or hooks. Components and hooks should be defined at the module level.

规则详情

¥Rule Details

在其他函数中定义组件或钩子会在每次调用时创建新实例。React 将每个组件视为完全不同的组件,销毁并重新创建整个组件树,丢失所有状态,并导致性能问题。

¥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

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

// ❌ 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

此规则的正确代码示例:

¥Examples of correct code for this rule:

// ✅ Component defined at module level
function Component({ defaultValue }) {
// ...
}

// ✅ Custom hook at module level
function useData(endpoint) {
// ...
}

故障排除

¥Troubleshooting

我需要动态组件行为

¥I need dynamic component behavior

你可能认为需要一个工厂来创建自定义组件:

¥You might think you need a factory to create customized components:

// ❌ 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');

改为传递 JSX 作为子元素

¥Pass JSX as children instead:

// ✅ 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>
</>
);
}