Skip to content

⚡ Events in React

  • React uses Synthetic events (a wrapper around browser’s native events).
  • Provides a cross-browser consistent API (so you don’t worry about differences in Chrome, Firefox, IE, etc).
  • Event names in React are camelCase instead of lowercase.
  • Eg:
const App = () => {
function handleClick(){
alert("Button Clicked")
}
return (
<butto onClick={handleClick}>Click Me!</button>
)
}
  • 👉 In vanilla JS -> onclick=""
  • 👉 In React JS -> onClick={function}
  • Mouse Events
    • onClick, onDoubleClick, onMouseEnter, onMouseLeave.
  • Keyboard Events
    • onKeyDown, onKeyPress, onKeyUp.
  • Form Events:
    • onSubmit, onChange, onFocus, onBlur.
  • Clipboard/Input Events:
    • onCopy, onPaste, onInput.
  • Others:
    • onScroll, onLoad, onError.
function Form (){
const [value, setValue] = React.useState('')
const handleSubmit = (e) => {
e.preventDefault() // prevents page reload.
alert(`Submitted ${value}`)
}
return (
<form onSubmit={handleSubmit}>
<input type="text" value={value} onChange={(e)=> setValue(e.target.value)} />
<button type="submit">Submit</button>
</form>
)
}
  • e.preventDefault() -> stops form from reloading the page.
  • ✅ React’s e is a Synthetic event but still gives access to native events if needed (e.nativeEvent)
  • In older React (<17), SyntheticEvents were pooled (reused for performance).
  • Accessing event properties asynchronously caused issues.
  • Now in React 17+, events are no longer pooled, so this issue is gone.
  • In React, events are not attached directly to elements.
  • Instead, they are delegated at root (document) level for performance.
  • This avoids too many listeners.
  • A technique where you attach a single event listener to a common ancestor element (the parent) instead of attaching separate listeners to multiple individual child elements.
  • When an event (like a click) occurs on a specific HTML element, it first triggers on that element (the target) and then “bubbles up” through its parent, grandparent, and other ancestor elements all the way to the document and window objects.
  • Event bubbling is the browser’s process of an event propagating up the DOM tree from the target element to its ancestors

⚖️ Comparison: Vanilla JS vs React Events

Section titled “⚖️ Comparison: Vanilla JS vs React Events”
FeatureVanilla JSReact Events
Syntaxonclick="fn()"onClick={fn}
Event objectNative EventSyntheticEvent (cross-browser)
Default behaviorMust use preventDefault()Same, but wrapped in SyntheticEvent
DelegationAttach per elementDelegated at root (document)
  • “React events use SyntheticEvent for cross browser compatibility and event delegation at the root for performance”.
  • “They look like DOM elements but follows camelCase (onClick, onChange)”.
  • “We use `preventDefault() to stop default behavior like form submission”.