import React, { useState } from 'react'; function ClickCounter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } export default ClickCounter;
Clicking the button triggers the onClick handler, which calls setCount with count + 1. This updates the state from 0 to 1, so the displayed text updates accordingly.
In React, event handlers use camelCase like onClick. You pass the function itself, not the result of calling it. So onClick={handleClick} is correct.
import React from 'react'; function MyButton() { function handleClick() { console.log(this); } return <button onClick={handleClick}>Click me</button>; } export default MyButton;
In React functional components, 'this' is not bound automatically. Using a regular function for handleClick means 'this' is undefined inside it, causing errors if accessed.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function increment() { setCount(count + 1); setCount(count + 1); } return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); } export default Counter;
Both setCount calls use the same stale 'count' value, so each sets count to 1. Two quick clicks call increment twice, each setting count to 1, so final count is 1.
React's synthetic event system attaches one listener at the root and delegates events, reducing memory use and improving performance compared to attaching listeners to many elements.