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.
Question 1: The Syntax Check
How do we correctly attach the defined handleClick event handler function to the button element in JSX?
function Btn () {
const handleClick = () => {
console.log('clicked')
}
return (
// Which option goes here?
<button ... >
Submit
</button>
)
}A) <button handleClick={handleClick}>
B) <button onClick={handleClick}>
C) <button @click={handleClick}>
D) <button [click]={handleClick}>
Question 2: The Execution Trap
What is the critical issue with the following code snippet?
function Btn () {
const handleClick = () => {
console.log('clicked')
}
return (
// Pay close attention here:
<button onClick={handleClick()}>
Submit
</button>
)
}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.
Question 3: Scope and Closures
What happens when the button in the following code is clicked?
// 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!" />
)
}A) Alerts "Hello World!"
B) Alerts undefined
C) Nothing, you get a Reference Error in the console.
D) It alerts a Synthetic Event object.
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.
A) False (mostly)
B) True