Performance: Passing arguments to handlers
This affects interaction responsiveness and rendering speed when event handlers receive arguments.
function MyButton() { const handleClickWithArg = React.useCallback(() => handleClick('arg'), []); return <button onClick={handleClickWithArg}>Click me</button>; } function handleClick(value) { console.log(value); }
function MyButton() { return <button onClick={() => handleClick('arg')}>Click me</button>; } function handleClick(value) { console.log(value); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline arrow function in JSX | No direct DOM ops, but triggers React reconciliation | 0 | Low paint cost but extra React work | [X] Bad |
| Memoized handler with useCallback | No extra DOM ops, stable React props | 0 | Minimal paint cost, efficient React updates | [OK] Good |
id to a click handler in React without calling the function immediately?handleClick(id) calls the function immediately, which is not desired on render.() => handleClick(id) passes a function reference that calls handleClick with id only when clicked.event and id to a handler handleClick in React?(event) => handleClick(event, id) correctly receives the event and passes both event and id to the handler.function MyButton() {
const handleClick = (id) => {
console.log('Clicked id:', id);
};
return <button onClick={() => handleClick(5)}>Click me</button>;
}handleClick(5) when clicked, passing 5 as argument.function ListItem({ id }) {
return <li onClick={handleClick(id)}>Item {id}</li>;
function handleClick(id) {
alert('Clicked ' + id);
}
}onClick={handleClick(id)} calls handleClick immediately during render, which is wrong.onClick={() => handleClick(id)} to call on user click.const List = () => {
const handleClick = (index) => alert(`Button ${index} clicked`);
return (
<div>
{[0,1,2].map((i) => (
<button key={i} onClick={/* ??? */}>Button {i}</button>
))}
</div>
);
};handleClick(i) calls the function immediately during render, causing all alerts at once.() => handleClick(i) delays the call until the button is clicked, passing the correct index.Pass the test and this pattern moves unknown