技术问询:什么是react/no-unused-state?为何它属于不良实践?
react/no-unused-state Hey there! Let's break down the react/no-unused-state ESLint rule clearly, including what it does and why leaving unused state around is considered bad practice.
规则具体含义
As the commit note you found states:
This adds a new rule, react/no-unused-state, which discovers state fields in a React component and warns if any of them are never read.
Put simply, this rule scans your React components (both class components and function components using useState) to detect state variables that are defined but never accessed or used anywhere in the component.
For example:
- In a class component, if you define a state property but never reference it in
render, event handlers, lifecycle methods, or anywhere else:
class UserProfile extends React.Component { state = { username: 'johndoe', email: 'john@example.com' // This email state is never read }; render() { return <div>Welcome, {this.state.username}!</div>; } }
ESLint will flag the email field as an unused state.
- In a function component, if you declare a state variable with
useStatebut never use the variable itself (even if you use the setter):
function Counter() { const [count, setCount] = useState(0); const [theme, setTheme] = useState('dark'); // theme is never read return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Here, theme will trigger a warning from the rule.
为什么未使用的state是不良开发实践
Leaving unused state in your components isn't just a minor nitpick—it's considered bad practice for several key reasons:
- Unnecessary code bloat: Unused state adds clutter to your component, making it harder for other developers (or future you) to understand which state actually matters. It creates confusion: "Why is this state here? Did someone forget to remove it?"
- Risk of future bugs: Over time, unused state might be accidentally referenced later, leading to unexpected behavior. Or, it might make developers assume the state is used somewhere, leading to wasted time tracing non-existent logic.
- Suboptimal performance: While React is efficient at handling state, unused state still adds to the component's state object. In edge cases with many unused state fields, this can lead to tiny but unnecessary overhead during re-renders, as React tracks all state changes regardless of whether they're used.
- Violates minimal state principles: React encourages keeping component state as minimal as possible—only storing data that's necessary for rendering or component logic. Unused state goes against this, making your component's state management less focused and harder to maintain.
内容的提问来源于stack exchange,提问作者skube

