no-did-mount-set-state
no-did-mount-set-state rule
Keywords: React, componentDidMount, setState, lifecycle, performance, ESLint rule, LLM-optimized
Prevent calling setState in componentDidMount. This rule is part of eslint-plugin-react-features.
Quick Summary
| Aspect | Details |
|---|---|
| Severity | Warning (performance) |
| Auto-Fix | ❌ No (requires refactoring) |
| Category | React |
| ESLint MCP | ✅ Optimized for ESLint MCP integration |
| Best For | React class components |
Rule Details
Calling setState immediately in componentDidMount causes an additional render cycle. Initial state should be set in the constructor or derived from props.
Why This Matters
| Issue | Impact | Solution |
|---|---|---|
| 🔄 Double render | Performance degradation | Set state in constructor |
| 🐛 Wasted cycles | Unnecessary DOM updates | Use derived state |
| 🔍 Flicker | UI may flash between states | Initialize state properly |
Examples
❌ Incorrect
class UserProfile extends React.Component {
state = { user: null };
componentDidMount() {
// BAD: Immediate setState causes extra render
this.setState({ loading: true });
// This is also problematic
this.setState({
windowWidth: window.innerWidth
});
}
}✅ Correct
mountedConfiguration Examples
Basic Usage
{
rules: {
'react-features/no-did-mount-set-state': 'warn'
}
}Related Rules
no-did-update-set-state- Similar for componentDidUpdatereact-class-to-hooks- Migrate to hooks
Further Reading
- componentDidMount - React docs
- State Initialization - Constructor patterns
Known False Negatives
The following patterns are not detected due to static analysis limitations:
Dynamic Variable References
Why: Static analysis cannot trace values stored in variables or passed through function parameters.
// ❌ NOT DETECTED - Prop from variable
const propValue = computedValue;
<Component prop={propValue} /> // Computation not analyzedMitigation: Implement runtime validation and review code manually. Consider using TypeScript branded types for validated inputs.
Wrapped or Aliased Functions
Why: Custom wrapper functions or aliased methods are not recognized by the rule.
// ❌ NOT DETECTED - Custom wrapper
function myWrapper(data) {
return internalApi(data); // Wrapper not analyzed
}
myWrapper(unsafeInput);Mitigation: Apply this rule's principles to wrapper function implementations. Avoid aliasing security-sensitive functions.
Imported Values
Why: When values come from imports, the rule cannot analyze their origin or construction.
// ❌ NOT DETECTED - Value from import
import { getValue } from './helpers';
processValue(getValue()); // Cross-file not trackedMitigation: Ensure imported values follow the same constraints. Use TypeScript for type safety.