Open
Description
openedon Jun 1, 2021
Rule proposal: no-unnecessary-setstate
- forbid setting state to the value of the existing state variable
I've seen this pattern also a bunch from beginners. And regardless of whether you're a beginner or not, this is probably not what you want to do (even if it's an object / array).
Example of incorrect code:
function Input (props) {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={(event) => {
setName(event.currentTarget.value);
setName(name); // ESLint problem reported
}}
/>
);
}
Examples of correct code:
function Input (props) {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={(event) => {
setName(event.currentTarget.value);
}}
/>
);
}
function Input (props) {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={(event) => {
const name = event.currentTarget.value; // Shadowing
setName(name);
}}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment