Performance: Inline vs function handlers
This affects interaction responsiveness and rendering performance by controlling how event handlers are created and reused in React components.
import { useCallback } from 'react'; function MyButton() { const handleClick = useCallback(() => console.log('Clicked'), []); return <button onClick={handleClick}>Click me</button>; }
function MyButton() { return <button onClick={() => console.log('Clicked')}>Click me</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline function handler | No extra DOM ops | Causes extra React re-renders | No direct paint cost | [X] Bad |
| Stable function handler reference | No extra DOM ops | Minimal React re-renders | No direct paint cost | [OK] Good |
<button onClick={() => alert('Hi')}>.onClick={handleClick}.onClick={handleClick} is correct.function MyButton() {
const handleClick = () => alert('Clicked!');
return <button onClick={() => handleClick()}>Click me</button>;
}handleClick() when clicked.handleClick shows an alert with 'Clicked!'. So clicking triggers the alert once.function Counter() {
const [count, setCount] = React.useState(0);
return <button onClick={setCount(count + 1)}>Increment</button>;
}onClick={setCount(count + 1)}, which calls setCount immediately during render.onClick={() => setCount(count + 1)} to call on click.Option 1: Inline handler
<button onClick={() => increment(index)}>Increment</button>
Option 2: Function handler
function handleClick() { increment(index); }
<button onClick={handleClick}>Increment</button>
Pass the test and this pattern moves unknown