Skip to content

New Rule Proposal: no-unnecessary-setstate #2997

Open

Description

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

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions