Validates against higher order functions defining nested components or hooks. Components and hooks should be defined at the module level.
Rule Details
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
functioncreateComponent(defaultValue){
returnfunctionComponent(){
// ...
};
}
// ❌ Component defined inside component
functionParent(){
functionChild(){
// ...
}
return<Child/>;
}
// ❌ Hook factory function
functioncreateCustomHook(endpoint){
returnfunctionuseData(){
// ...
};
}Valid
Examples of correct code for this rule:
// ✅ Component defined at module level
functionComponent({defaultValue}){
// ...
}
// ✅ Custom hook at module level
functionuseData(endpoint){
// ...
}Troubleshooting
I need dynamic component behavior
You might think you need a factory to create customized components:
// ❌ Wrong: Factory pattern
functionmakeButton(color){
returnfunctionButton({children}){
return(
<buttonstyle={{backgroundColor:color}}>
{children}
</button>
);
};
}
constRedButton =makeButton('red');
constBlueButton =makeButton('blue');PassJSX as children instead:
// ✅ Better: Pass JSX as children
functionButton({color,children}){
return(
<buttonstyle={{backgroundColor:color}}>
{children}
</button>
);
}
functionApp(){
return(
<>
<Buttoncolor="red">Red</Button>
<Buttoncolor="blue">Blue</Button>
</>
);
}