0

I've created a very simple form using React 16.13.1, with just 2 fields:

<div>
  <form onSubmit={handleSubmit}>
    <div>
      <label>Username</label>
      <input name="username" onChange={handleInputChange} value={credentials.username} />
    </div>
    <div>
      <label>Password</label>
      <input type="password" name="password" onChange={handleInputChange} value={credentials.password} />
    </div>
    <div>
      <input type="submit" value="Login" />
    </div>
  </form>
</div>

I'm using a generic function to handle the input change event:

const [credentials, setCredentials] = useState({});

const handleInputChange = event => {
  const { name, value } = event.target;
  setCredentials({ ...credentials, [name]: value }); // <<< This line is causing the component to re-render twice on every key typed in any field
};

Shouldn't it only re-render the component once? What is causing the second re-render?

Working demo

AndreFeijo
  • 10,044
  • 7
  • 34
  • 64
  • 1
    Please check the duplicate, it does answer your concern. Just to give you a brief, its because of React.StrictMode that you have in your index.js and is a way to detect unexpected errors by double invocation of certain function – Shubham Khatri Jun 09 '20 at 04:55
  • 2
    https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/ hope this blog help your problem – Anh Tuan Jun 09 '20 at 04:56
  • Thanks for that, not sure why I didn't find that question when I searched. – AndreFeijo Jun 09 '20 at 04:56

0 Answers0