Performance: Form submission handling
This affects how quickly the page responds to user input and how fast the form data is processed and sent, impacting interaction responsiveness and perceived speed.
function MyForm() { const handleSubmit = async (e) => { e.preventDefault(); await new Promise(resolve => setTimeout(resolve, 0)); // yield to browser alert('Form submitted'); }; return ( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> ); }
function MyForm() { return ( <form onSubmit={(e) => { e.preventDefault(); // heavy synchronous processing for(let i=0; i<1000000000; i++) {} alert('Form submitted'); }}> <button type="submit">Submit</button> </form> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy processing on submit | Minimal | 0 immediate, but blocks | High due to blocking | [X] Bad |
| Async lightweight submit handler | Minimal | 0 immediate | Low | [OK] Good |
| Default form submit with page reload | Full page reload | Many reflows | Very high | [X] Bad |
| Prevent default + async submit | Minimal | 0 immediate | Low | [OK] Good |
event.preventDefault() do in a React form submission handler?onSubmit.onsubmit is incorrect, must be onSubmit.function MyForm() {
const [name, setName] = React.useState('');
function handleSubmit(event) {
event.preventDefault();
console.log(name);
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={e => setName(e.target.value)} />
<button type="submit">Send</button>
</form>
);
}name, updated on every change.handleSubmit logs the current name state, which matches input content.function Form() {
const [email, setEmail] = React.useState('');
function handleSubmit() {
event.preventDefault();
alert(email);
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={e => setEmail(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
}event.preventDefault() but does not receive event as a parameter.event parameter, event is undefined, causing a runtime error.function ContactForm() {
const [message, setMessage] = React.useState('');
function handleSubmit(event) {
event.preventDefault();
console.log(message);
// What goes here?
}
return (
<form onSubmit={handleSubmit}>
<textarea value={message} onChange={e => setMessage(e.target.value)} />
<button type="submit">Send</button>
</form>
);
}message, so clearing input means resetting this state.setMessage('') updates state to empty string, clearing the textarea in UI.Pass the test and this pattern moves unknown