Lesson 1.X

React Event Handler Mistakes

React's declarative nature makes building UIs intuitive, but handling user interactions—events—often trips up developers new to the framework (or even experienced ones moving quickly).

Unlike standard HTML, React uses its own synthetic event system. While powerful, it comes with specific rules regarding syntax, scope, and execution.

Let's test your knowledge with four quick scenario-based questions.

1

Question 1: The Syntax Check

How do we correctly attach the defined handleClick event handler function to the button element in JSX?

jsx
function Btn () {
  const handleClick = () => {
    console.log('clicked')
  }

  return (
    // Which option goes here?
    <button ... >
      Submit
    </button>
  )
}
Select the correct answer:

A) <button handleClick={handleClick}>

B) <button onClick={handleClick}>

C) <button @click={handleClick}>

D) <button [click]={handleClick}>

2

Question 2: The Execution Trap

What is the critical issue with the following code snippet?

jsx
function Btn () {
  const handleClick = () => {
    console.log('clicked')
  }

  return (
    // Pay close attention here:
    <button onClick={handleClick()}>
      Submit
    </button>
  )
}
Select the correct answer:

A) Nothing is wrong.

B) onClick accepts a string, "handleClick()", not a function.

C) onClick accepts a function reference, not the result of invoking a function.

D) onClick accepts a string, "handleClick", not a function.

3

Question 3: Scope and Closures

What happens when the button in the following code is clicked?

jsx
// Note: this function is defined OUTSIDE the component
const handleClick = () => alert(message)

function AlertButton({ message }) {
  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  )
}

export default function App () {
  return (
    <AlertButton message="Hello, world!" />
  )
}
Select the correct answer:

A) Alerts "Hello World!"

B) Alerts undefined

C) Nothing, you get a Reference Error in the console.

D) It alerts a Synthetic Event object.

4

Question 4: The Performance Myth?

True or False: Putting event handler functions inside the component body will lead to performance issues because React will have to re-create those functions on every single render.

True or False?

A) False (mostly)

B) True