jsx-eslint / eslint-plugin-react

React-specific linting rules for ESLint
MIT License
9k stars 2.77k forks source link

New Rule Proposal: `no-unnecessary-setstate` #2997

Open karlhorky opened 3 years ago

karlhorky commented 3 years ago

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);
      }}
    />
  );
}
ljharb commented 3 years ago

If it’s a common problem only with the useState hook, it seems like eslint-plugin-react-hooks would be a better place for it.

karlhorky commented 3 years ago

I'll try, although from experience, this probably won't get accepted over there.

Edit: open https://github.com/facebook/react/issues/21595