Consider this React component. What will be logged to the console when the button is clicked?
import React, { useState } from 'react'; function ClickLogger() { const [count, setCount] = useState(0); function handleClick(value) { console.log(`Clicked with value: ${value}`); setCount(count + value); } return ( <button onClick={() => handleClick(5)}> Click me </button> ); } export default ClickLogger;
Look at how the argument is passed inside the onClick handler.
The arrow function () => handleClick(5) calls handleClick with the argument 5 when the button is clicked. This logs the message and updates the state count to 5.
Which of the following is the correct way to pass the argument 10 to the handleClick function in React?
function MyComponent() { function handleClick(num) { console.log(num); } return ( <button /* choose correct onClick here */> Press </button> ); }
Remember that calling the function directly in JSX runs it immediately.
Option A uses an arrow function to delay calling handleClick(10) until the button is clicked. Option A calls it immediately on render. Option A passes the function without arguments. Option A incorrectly uses bind.
Examine the code below. Clicking the button causes an error. What is the cause?
import React from 'react'; function Counter() { let count = 0; function increment(step) { count += step; console.log(count); } return ( <button onClick={increment(1)}> Add 1 </button> ); } export default Counter;
Check when the function inside onClick is executed.
Because increment(1) is called immediately during render, React tries to assign the result (undefined) to onClick, causing an error. It should be wrapped in a function to delay execution.
Given this React component, what will be the value of count after clicking the button two times?
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function increment(step) { setCount(count + step); } return ( <button onClick={() => increment(1)}> Increment </button> ); } export default Counter;
Remember how React batches state updates and closures capture values.
The increment function uses the current count value from closure, which does not update immediately. Each click adds 1 to the initial 0, so after two clicks, count is 1, not 2.
Which explanation best describes why we often use arrow functions like () => handleClick(arg) when passing arguments to event handlers?
Think about when the function should run in React.
Using an arrow function delays the call until the event happens. Without it, the function runs immediately during rendering, which is not desired.