Performance: Event handlers in client components
This affects interaction responsiveness and page load speed by controlling how event listeners are attached and executed in client components.
export default function Button() { const handleClick = () => { console.log('Clicked'); }; return <button onClick={handleClick}>Click me</button>; }
export default function Button() { return <button onClick={() => { console.log('Clicked'); }}>Click me</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline arrow function in JSX | No extra DOM nodes | Causes extra React re-renders | Minimal paint impact | [X] Bad |
| Stable handler function reference | No extra DOM nodes | No extra re-renders | Minimal paint impact | [OK] Good |
onClick={handleClick}, passing the function directly.onClick={handleClick} with a function reference. -> Option Dimport { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return (
Clicked {count} times
);
}import { useState } from 'react';
export default function Toggle() {
const [on, setOn] = useState(false);
function toggle() {
setOn(!on);
}
return (
{on ? 'ON' : 'OFF'}
);
}import { useState } from 'react';
export default function Greeting() {
const [name, setName] = useState('');
// What should the input's onChange handler be?
return (
Hello, {name || 'stranger'}!
);
}Pass the test and this pattern moves unknown