Performance: Handling events in React
This affects how quickly the app responds to user actions and how efficiently the browser updates the UI after events.
function MyButton() { const handleClick = React.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 arrow function in JSX | Multiple event handler re-registrations | Multiple reflows if state changes unnecessarily | Higher paint cost due to frequent updates | [X] Bad |
| Memoized handler with useCallback | Single event handler registration | Minimal reflows only when needed | Lower paint cost due to fewer updates | [OK] Good |
onClick is correct, not lowercase or capitalized differently.{handleClick} is correct, not a string like "handleClick()".<button onClick={handleClick}>Click me</button> [OK]const for event handlers.const handleClick = () => console.log('Clicked'); is correct. Other options have syntax errors such as missing variable declaration or invalid syntax.import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => setCount(count + 1);
return (
<button onClick={handleClick}>Clicked {count} times</button>
);
}count starts at 0, so the button initially shows 'Clicked 0 times'.handleClick, which updates count by adding 1, so the displayed count increments on each click.function MyButton() {
const handleClick = () => {
console.log('Clicked');
}
return <button onclick={handleClick}>Click me</button>;
}onclick is incorrect; it should be onClick.handleClick is correctly defined and passed as a reference, so no error there.function EnterCounter() {
const [count, setCount] = React.useState(0);
const handleKeyDown = (event) => {
// What condition should be here?
};
return (
<>
<input type="text" onKeyDown={handleKeyDown} aria-label="Enter key counter input" />
<p>Count: {count}</p>
</>
);
}event.key as a string to detect keys, so checking event.key === 'Enter' is correct.event.keyCode and event.which are deprecated or inconsistent; also, comparing event.key to a number like 13 is incorrect.Pass the test and this pattern moves unknown