Home > Software engineering >  Why is the state of the hook changing even when I use the preventdefault() function in React?
Why is the state of the hook changing even when I use the preventdefault() function in React?

Time:12-16

recently I started learning React and I cannot understand why onSubmit the e.preventDefault() function is simply not working as it is supposed to... Instead of waiting until I click the "Deposit" or "Change" buttons for the value displayed on the React components hooks state to change, their state is changing as I type into the form.

The preventDefault() function should not let the hook state to change until I hit the button, hence the onSubmit{}. However, the state changes as soon as I type a new character.

function App() {
  const [depositValue, setDepositValue] = useState('');
  
  const handleDepositValue = (e) => {
    setDepositValue(e.target.value);
  };

  return (
          <div className="col">
          <form onSubmit={handleDepositSubmit}>
            <div className="mb-3">
              <input type="number" className="form-control" placeholder="0" onChange={handleDepositValue} defaultValue={depositValue} />
            </div>
            <button type="submit" className="btn btn-primary">Deposit</button>
          </form>

CodePudding user response:

I made the same mistake when I was first starting with React. preventDefault() is typically used to prevent a browser reload/refresh. This would never stop a state update in React. Since you are using onChange, your state is going to update for each keystroke in that input. Here is a link to an article I think would be helpful and relevant to your situation.

From looking at your code, I don't think that the fact that your depositValue state is updating on each keystroke is a problem. That is pretty typical for React forms so I wouldn't worry about it. Good luck with your studies!

  • Related