Performance: State and hooks in client components
MEDIUM IMPACT
This affects interaction responsiveness and rendering speed of client components by managing state changes efficiently.
"use client"; import { useState, useRef } from 'react'; export default function Search() { const [query, setQuery] = useState(''); const timeout = useRef(null); function handleChange(e) { clearTimeout(timeout.current); const value = e.target.value; timeout.current = setTimeout(() => setQuery(value), 300); } return <input defaultValue={query} onChange={handleChange} />; }
"use client"; import { useState } from 'react'; export default function Search() { const [query, setQuery] = useState(''); return <input value={query} onChange={e => setQuery(e.target.value)} />; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| State update on every keystroke | Many small DOM updates | Triggers 1 reflow per update | High paint cost due to frequent changes | [X] Bad |
| Debounced state update | Fewer DOM updates | Single reflow after debounce | Lower paint cost | [OK] Good |
| Multiple independent state variables | Multiple updates possible | Multiple reflows if updated separately | Moderate paint cost | [!] OK |
| Combined state object | Single update per change | Single reflow | Lower paint cost | [OK] Good |