🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

Events

AI & DATA SCIENCE // events

React lets components respond to user interactions, like clicks or input changes, by attaching event handler functions directly to JSX elements.

Syntax

<button onClick={handleClick}>Click me</button>

Deep Dive Course

React events are attached using camelCase attribute names, like onClick or onChange, and are passed a function reference rather than a string of code, unlike the old-style HTML onclick="..." attribute. Under the hood, React attaches a single listener at the root of the application and uses event delegation, along with its own SyntheticEvent wrapper around the browser's native event, which normalizes behavior consistently across different browsers while still exposing the same familiar event properties and methods, like .preventDefault().

1Understanding Events

React events are attached using camelCase attribute names, like onClick or onChange, and are passed a function reference rather than a string of code, unlike the old-style HTML onclick="..." attribute. Under the hood, React attaches a single listener at the root of the application and uses event delegation, along with its own SyntheticEvent wrapper around the browser's native event, which normalizes behavior consistently across different browsers while still exposing the same familiar event properties and methods, like .preventDefault().

💡

Pass a function reference, onClick={handleClick}, not a function call, onClick={handleClick()} — the latter calls the function immediately during rendering, rather than only when the button is actually clicked.

editor.html
function Button() {
  const handleClick = () => console.log('Button clicked!');
  return <button onClick={handleClick}>Click me</button>;
}
localhost:3000

2Practical Example

Here is a real-world application of Events showing how it is used in production React code.

editor.html
function ItemButton({ id }) {
  const handleClick = (itemId) => console.log('Clicked item:', itemId);
  return <button onClick={() => handleClick(id)}>Select</button>;
}

// <ItemButton id={42} />
localhost:3000

3Best Practices

Follow these guidelines when working with Events:

1. Pass event handlers as function references, never invoking them directly in JSX, to avoid accidentally calling the handler during every render

2. Use an inline arrow function, onClick={() => handleClick(id)}, when you need to pass arguments to the handler, since a direct reference alone can't include extra arguments

3. Call event.preventDefault() on a form's submit event to stop the browser's default full-page reload before handling the submission with your own JavaScript logic

⚠️

Tip: Pass a function reference, onClick={handleClick}, not a function call, onClick={handleClick()} — the latter calls the function immediately during rendering, rather than only when the button is actually clicked.

editor.html
function Button() {
  const handleClick = () => console.log('Button clicked!');
  return <button onClick={handleClick}>Click me</button>;
}
localhost:3000

4Stopping Propagation

Because React uses event delegation, a click on a nested element also triggers any click handlers on its parents, in order — the same bubbling behavior as native DOM events. Calling event.stopPropagation() inside a handler prevents the event from continuing to bubble up and firing those parent handlers.

editor.html
function Card({ onCardClick, onDeleteClick }) {
  return (
    <div onClick={onCardClick}>
      <button onClick={(e) => { e.stopPropagation(); onDeleteClick(); }}>Delete</button>
    </div>
  );
}
localhost:3000

Examples

Example 01Basic Usage
function Button() {
  const handleClick = () => console.log('Button clicked!');
  return <button onClick={handleClick}>Click me</button>;
}
Example 02Advanced Example
function ItemButton({ id }) {
  const handleClick = (itemId) => console.log('Clicked item:', itemId);
  return <button onClick={() => handleClick(id)}>Select</button>;
}

// <ItemButton id={42} />

Best Practices

  • Pass event handlers as function references, never invoking them directly in JSX, to avoid accidentally calling the handler during every render
  • Use an inline arrow function, onClick={() => handleClick(id)}, when you need to pass arguments to the handler, since a direct reference alone can't include extra arguments
  • Call event.preventDefault() on a form's submit event to stop the browser's default full-page reload before handling the submission with your own JavaScript logic
  • Call event.stopPropagation() inside a nested element's handler when a click on it should not also trigger a parent element's own click handler

Interview Question

Why does writing onClick={handleClick()} instead of onClick={handleClick} cause the handler to run immediately when the component renders, rather than only when the button is clicked?

Hint: Think about the difference between referencing a function and calling it, in terms of when each one actually executes.

onClick={handleClick} passes the function itself as a value, a reference React can store and call later, at the actual moment the click event occurs. onClick={handleClick()}, by contrast, immediately invokes handleClick during the JSX expression's evaluation, which happens synchronously as part of rendering the component, not later in response to a click — whatever handleClick() actually returns, often undefined, is what actually gets assigned to onClick, meaning there's frequently no valid function left for React to call when the click genuinely happens later. This is a common beginner mistake precisely because the visual difference, adding parentheses, is small, but the behavioral difference, passing a reference to call later versus calling it right now during render, is fundamental to how JSX expressions and event handlers work.

Exercises

MediumPractice using Events in a real scenario.
View Solution
function Button() {
  const handleClick = () => console.log('Button clicked!');
  return <button onClick={handleClick}>Click me</button>;
}

Frequently Asked Questions

Why does writing onClick={handleClick()} instead of onClick={handleClick} cause the handler to run immediately when the component renders, rather than only when the button is clicked?

onClick={handleClick} passes the function itself as a value, a reference React can store and call later, at the actual moment the click event occurs. onClick={handleClick()}, by contrast, immediately invokes handleClick during the JSX expression's evaluation, which happens synchronously as part of rendering the component, not later in response to a click — whatever handleClick() actually returns, often undefined, is what actually gets assigned to onClick, meaning there's frequently no valid function left for React to call when the click genuinely happens later. This is a common beginner mistake precisely because the visual difference, adding parentheses, is small, but the behavioral difference, passing a reference to call later versus calling it right now during render, is fundamental to how JSX expressions and event handlers work.

Related Functions

onclicksynthetic-eventsevents-in-react