Performance: Preventing default behavior
This affects interaction responsiveness and can reduce unnecessary page reloads or layout shifts caused by default browser actions.
function handleSubmit(event) { event.preventDefault(); console.log('Form submitted'); } <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form>
function handleSubmit(event) { // No preventDefault called console.log('Form submitted'); } <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No preventDefault on form submit | Triggers full form submission and reload | Multiple reflows due to reload | High paint cost from full page repaint | [X] Bad |
| Using preventDefault on form submit | No extra DOM ops, stays client-side | Single reflow or none | Low paint cost, no reload | [OK] Good |
| No preventDefault on link click | Triggers navigation and reload | Multiple reflows and layout shifts | High paint cost from reload | [X] Bad |
| Using preventDefault on link click | No reload, SPA routing | Minimal reflows | Low paint cost | [OK] Good |
event.preventDefault() do in a React event handler?function Link() {
function handleClick(event) {
event.preventDefault();
alert('Link clicked!');
}
return <a href='https://example.com' onClick={handleClick}>Click me</a>;
}function handleSubmit() {
event.preventDefault();
console.log('Submitted');
}function handleSubmit(event) {
// Prevent submission only if checkbox is unchecked
const checkbox = document.getElementById('agree');
if (/* condition here */) {
event.preventDefault();
alert('You must agree first');
}
}Pass the test and this pattern moves unknown