Validates against higher order functions defining nested components or hooks. Components and hooks should be defined at the module level.
Rule Details
Section titled “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
Section titled “Invalid”Examples of incorrect code for this rule:
// ❌ Factory function creating componentsfunction createComponent(defaultValue) { return function Component() { // ... };}
// ❌ Component defined inside componentfunction Parent() { function Child() { // ... }
return <Child />;}
// ❌ Hook factory functionfunction createCustomHook(endpoint) { return function useData() { // ... };}Examples of correct code for this rule:
// ✅ Component defined at module levelfunction Component({ defaultValue }) { // ...}
// ✅ Custom hook at module levelfunction useData(endpoint) { // ...}Troubleshooting
Section titled “Troubleshooting”I need dynamic component behavior
Section titled “I need dynamic component behavior”You might think you need a factory to create customized components:
// ❌ Wrong: Factory patternfunction makeButton(color) { return function Button({children}) { return ( <button style={{backgroundColor: color}}> {children} </button> ); };}
const RedButton = makeButton('red');const BlueButton = makeButton('blue');Pass JSX as children instead:
// ✅ Better: Pass JSX as childrenfunction Button({color, children}) { return ( <button style={{backgroundColor: color}}> {children} </button> );}
function App() { return ( <> <Button color="red">Red</Button> <Button color="blue">Blue</Button> </> );}