Sub topic 3
Passing arguments to handlers
This chapter assumes you know JavaScript arrow functions and closures, basic JSX, props, and useState. You have already seen how to attach a handler to an element and how to read the event object. Here you will learn how to give a handler extra information, such as which list item was clicked.
The problem: React calls handlers with the event only
When you write onClick={handleClick}, React calls handleClick(event) when the click happens. The handler receives one argument, the event object. It does not know which item, row, or id the click belongs to.
Suppose you render a list of products and want a handler that deletes the clicked product. The handler needs the product id. The event object does not carry it, so you must supply it yourself.
Wrapping the call in an inline arrow function
The usual solution is an inline arrow function. You pass React a new function that calls your handler with the arguments you choose.
function ProductList({ products, onDelete }) {
return (
<ul>
{products.map(product => (
<li key={product.id}>
{product.name}
<button onClick={() => onDelete(product.id)}>Delete</button>
</li>
))}
</ul>
);
}Each button gets its own arrow function. The arrow function closes over product, the variable for the current iteration of map. When the click happens, React calls the arrow function, and the arrow function calls onDelete with that product's id.
Reference versus call
The most common error in this area is writing the call instead of the reference.
// Wrong: runs during render, and passes its return value to onClick
<button onClick={onDelete(product.id)}>Delete</button>
// Right: passes a function that runs on click
<button onClick={() => onDelete(product.id)}>Delete</button>In JSX, {...} holds an expression. The expression onDelete(product.id) is evaluated while React renders, so the handler runs immediately, before any click. Its return value, usually undefined, becomes the onClick prop. If the handler also sets state, you get a re-render loop, and React reports "Too many re-renders".
Also passing the event
An inline arrow function receives the event as its first parameter. Forward it when the handler needs both the event and your own arguments.
function Row({ id, onAction }) {
return (
<button onClick={e => onAction(id, e)}>
Run
</button>
);
}Put your own arguments first and the event last. This keeps the handler signature predictable, and the event is easy to omit when the handler does not need it. React does not require this order, but a consistent one helps readers.
Defining a handler that takes arguments
Handlers can be named functions declared inside the component. A named handler is easier to read when its body is more than one line.
import { useState } from 'react';
function Cart() {
const [items, setItems] = useState([
{ id: 1, name: 'Tea', qty: 1 },
{ id: 2, name: 'Coffee', qty: 2 },
]);
function changeQty(id, delta) {
setItems(current =>
current.map(item =>
item.id === id ? { ...item, qty: item.qty + delta } : item
)
);
}
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name}: {item.qty}
<button onClick={() => changeQty(item.id, 1)}>+</button>
<button onClick={() => changeQty(item.id, -1)}>-</button>
</li>
))}
</ul>
);
}The arrow functions only choose the arguments. The logic stays in changeQty. This keeps JSX short and makes the handler testable and reusable.
Currying: a handler factory
An alternative is a function that returns a handler. This is called currying, or a handler factory.
function Toolbar({ onChoose }) {
function choose(option) {
return function handleClick() {
onChoose(option);
};
}
return (
<div>
<button onClick={choose('bold')}>Bold</button>
<button onClick={choose('italic')}>Italic</button>
</div>
);
}choose('bold') runs during render, but it only builds and returns a function. React stores that returned function as the click handler. This is not the reference-versus-call bug, because choose(...) returns a function, not the result of the action.
Both styles work. Inline arrows are more common and easier for most readers to follow. Factories help when you want to name the pattern or reuse it across many elements.
Reading arguments from the DOM instead
Sometimes you can avoid closures by reading data from the element the event came from. Use event.currentTarget and a data- attribute.
function Tabs({ onSelect }) {
function handleClick(e) {
onSelect(e.currentTarget.dataset.tab);
}
return (
<div>
<button data-tab="home" onClick={handleClick}>Home</button>
<button data-tab="docs" onClick={handleClick}>Docs</button>
</div>
);
}All buttons share one function. The trade-off is that dataset values are always strings. An id that is a number in your data becomes "3", so you must convert it back. For data that is already in JavaScript scope, such as the product in map, a closure is simpler and keeps the original type.
Use currentTarget, not target. currentTarget is the element that has the handler. target may be a child element, such as an icon inside the button.
Stale values and closures
An inline arrow captures the values from the render in which it was created. This is normally what you want. With state it needs care.
import { useState } from 'react';
function Delayed() {
const [count, setCount] = useState(0);
function handleClick() {
setTimeout(() => {
alert(`Count was ${count}`);
}, 2000);
}
return (
<button onClick={() => { setCount(count + 1); handleClick(); }}>
Clicked {count}
</button>
);
}On the first click, count is 0 in that render, so the alert says Count was 0 even though the screen now shows 1. Each render has its own count. This is a snapshot, not a bug. When you need the newest state inside a handler that runs later, prefer a functional update such as setCount(c => c + 1), which reads the latest queued value.
Performance: do inline arrows cost too much?
Every render creates a new arrow function for each element. For most apps this is cheap and does not matter. Do not rewrite readable code to avoid it.
It can matter in one case. If you pass the arrow function as a prop to a child wrapped in React.memo, the child sees a new function each time and re-renders anyway. Only then should you consider useCallback, and for per-item arguments a better fix is usually to let the child receive the id and call the handler itself.
import { memo } from 'react';
const ProductRow = memo(function ProductRow({ product, onDelete }) {
return (
<li>
{product.name}
<button onClick={() => onDelete(product.id)}>Delete</button>
</li>
);
});
function ProductList({ products, onDelete }) {
return (
<ul>
{products.map(product => (
<ProductRow key={product.id} product={product} onDelete={onDelete} />
))}
</ul>
);
}Here the parent passes the same onDelete to every row, and each row builds its own arrow. If onDelete is stable (for example wrapped in useCallback), memoized rows can skip re-rendering. Measure first. Add memo and useCallback only when profiling shows a real cost.
Choosing an approach
| Approach | Best for | Watch out for |
|---|---|---|
| Inline arrow `() => fn(id)` | Most cases, loop items | Calling `fn(id)` directly by mistake |
| Handler factory `fn(id)` returns a function | Reusing a pattern across many elements | Harder to read for newcomers |
| `data-` attribute with `currentTarget` | One shared handler, many similar elements | Values are strings |
How the flow works
Common errors
- Calling the handler in JSX (
onClick={fn(id)}) instead of passing a function. The handler runs on every render. - Forgetting that the event is not passed automatically when you wrap the handler. With
() => fn(id),fngets no event unless you forward it. - Using
targetinstead ofcurrentTargetwhen reading adata-attribute, which givesundefinedwhen the user clicks a child element. - Expecting
datasetvalues to keep their original type. - Using a loop index as an argument when the list can be reordered or filtered. Pass a stable id instead.
Exercise
A teammate writes <button onClick={removeItem(item.id)}>Remove</button> inside a map. The items are removed as soon as the list appears, before any click. Explain why this happens and give the fix.
Show answer
removeItem(item.id) is a function call, and JSX evaluates it while rendering. So each item is removed during render, and the value returned by removeItem (usually undefined) becomes the onClick prop. The fix is to pass a function that makes the call later: onClick={() => removeItem(item.id)}.
Exercise
A handler selectRow(id, event) needs both the row id and the event. Write the onClick prop that provides both.
Show answer
onClick={e => selectRow(row.id, e)}. The arrow function receives the event from React, and forwards it along with the id.
Exercise
You use one shared handler with data-id={item.id} on each button, and read e.currentTarget.dataset.id. Your items have numeric ids, and items.find(i => i.id === id) returns undefined. Why, and how do you fix it?
Show answer
dataset values are strings, so id is "3" while i.id is 3, and === is false. Convert with Number(e.currentTarget.dataset.id), or use an inline arrow () => handle(item.id) to keep the original number.