'use client'; import React, { useState } from 'react'; export default function ClickCounter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( <button onClick={handleClick} aria-label="Increment count"> Count: {count} </button> ); }
Clicking the button calls handleClick, which updates the count state by adding 1. This causes the component to re-render and display the updated count.
doSomething.function doSomething() { console.log('Clicked'); } export default function MyButton() { return ( <button /* event handler here */>Click me</button> ); }
Option D correctly passes the function doSomething as a reference to onClick. Options B and C use strings which are invalid in JSX. Option D calls the function immediately instead of passing it.
'use client'; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); function handleClick() { count = count + 1; } return ( <button onClick={handleClick} aria-label="Increment"> Count: {count} </button> ); }
State variables like count cannot be changed directly. The function handleClick modifies count directly, which does not cause React to re-render. The correct way is to call setCount(count + 1).
'use client'; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 1); } return ( <button onClick={handleClick} aria-label="Increment"> Count: {count} </button> ); }
Both setCount(count + 1) calls use the same count value (0) because state updates are asynchronous and batched. So the count increments only by 1, not 2.
Event handlers need to run in the browser to respond to user actions. The 'use client' directive tells Next.js to render the component on the client side, enabling JavaScript interactivity. Without it, components are server components and cannot have event handlers.