Performance: Search implementation
MEDIUM IMPACT
This affects page load speed and interaction responsiveness by how search queries are handled and results rendered.
import { useState, useEffect } from 'react'; import { useDebounce } from 'use-debounce'; export function Search() { const [query, setQuery] = useState(''); const [debouncedQuery] = useDebounce(query, 300); const [results, setResults] = useState([]); useEffect(() => { if (debouncedQuery) { fetch(`/api/search?q=${debouncedQuery}`) .then(res => res.json()) .then(data => setResults(data)); } else { setResults([]); } }, [debouncedQuery]); return ( <> <input value={query} onChange={e => setQuery(e.target.value)} aria-label="Search input" /> <ul>{results.map(r => <li key={r.id}>{r.name}</li>)}</ul> </> ); }
import React from 'react'; export function Search() { const [query, setQuery] = React.useState(''); const [results, setResults] = React.useState([]); React.useEffect(() => { fetch(`/api/search?q=${query}`) .then(res => res.json()) .then(data => setResults(data)); }, [query]); return ( <> <input value={query} onChange={e => setQuery(e.target.value)} /> <ul>{results.map(r => <li key={r.id}>{r.name}</li>)}</ul> </> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetch on every keystroke | Many network calls, frequent state updates | Multiple reflows per keystroke | High paint cost due to frequent updates | [X] Bad |
| Debounced fetch | Fewer network calls, batched updates | Single reflow per user pause | Lower paint cost | [OK] Good |
| Render full large list | Thousands of DOM nodes | Single but heavy reflow | High paint cost | [X] Bad |
| Virtualized list rendering | Few DOM nodes at a time | Minimal reflows | Low paint cost | [OK] Good |