Synthetic Events & Event Handling
React event handlers are functions passed to event props such as onClick, onChange, and onSubmit. Pass a function reference; do not invoke it during render unless you intentionally want the return value.
Event handlers are a natural place for user-driven side effects: updating state, calling an API, starting a transition, or navigating. Keep the event handler focused on the event and delegate substantial business logic to reusable functions.
For forms, call preventDefault() when you are intentionally handling submission without a native navigation.
Form submission
function LoginForm() {
function handleSubmit(event) {
event.preventDefault();
// validate and submit credentials
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Sign in</button>
</form>
);
}💡 The form owns the submit event. Keeping submission logic in a named handler improves readability and testing.
Key Takeaways
- Event handlers are explicit side-effect boundaries.
- Do not call event handlers during render unless that is actually intended.
- Use semantic HTML events such as form submit.