0
0
NextJSframework~8 mins

Event handlers in client components in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Event handlers in client components
MEDIUM IMPACT
This affects interaction responsiveness and page load speed by controlling how event listeners are attached and executed in client components.
Handling button clicks in a Next.js client component
NextJS
export default function Button() {
  const handleClick = () => { console.log('Clicked'); };
  return <button onClick={handleClick}>Click me</button>;
}
Defines the handler once per render, avoiding recreating the function inline and reducing re-renders.
📈 Performance GainReduces JavaScript execution and improves interaction responsiveness (lower INP).
Handling button clicks in a Next.js client component
NextJS
export default function Button() {
  return <button onClick={() => { console.log('Clicked'); }}>Click me</button>;
}
The inline arrow function creates a new function on every render, causing unnecessary re-renders and memory usage.
📉 Performance CostTriggers extra JavaScript executions and can cause more frequent re-renders, increasing INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Inline arrow function in JSXNo extra DOM nodesCauses extra React re-rendersMinimal paint impact[X] Bad
Stable handler function referenceNo extra DOM nodesNo extra re-rendersMinimal paint impact[OK] Good
Rendering Pipeline
Event handlers are registered during the JavaScript execution phase after the DOM is ready. When events occur, the browser executes the handler code, which can trigger state updates and re-renders in React components.
JavaScript Execution
Layout
Paint
⚠️ BottleneckJavaScript Execution when handlers are inefficient or recreated frequently
Core Web Vital Affected
INP
This affects interaction responsiveness and page load speed by controlling how event listeners are attached and executed in client components.
Optimization Tips
1Avoid defining event handlers inline in JSX to prevent unnecessary re-renders.
2Always clean up event listeners added in useEffect to prevent memory leaks.
3Memoize or define handlers outside render to reduce JavaScript execution cost.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance downside of defining event handlers inline in JSX?
AThey block the initial page load completely.
BThey create a new function on every render causing extra JavaScript work.
CThey prevent the browser from painting the page.
DThey increase the size of the HTML file.
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for frequent JavaScript function creations and React re-renders.
What to look for: High JavaScript execution time caused by event handler recreations and excessive React renders indicate poor performance.