Performance: Search implementation
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 |
loader function when implementing a search feature??q=apple and the data array is ["apple", "banana", "apricot"]?
export async function loader({ request }) {
const url = new URL(request.url);
const q = url.searchParams.get('q')?.toLowerCase() || '';
const data = ["apple", "banana", "apricot"];
return data.filter(item => item.toLowerCase().includes(q));
}export async function loader({ request }) {
const url = new URL(request.url);
const q = url.searchParams.get('query');
const data = ["cat", "dog", "bird"];
return data.filter(item => item.includes(q));
}q. Which approach correctly handles empty queries and case-insensitive matching in the loader?
export async function loader({ request }) {
const url = new URL(request.url);
const q = url.searchParams.get('q')?.toLowerCase() || '';
const products = [
{ name: 'Table', category: 'Furniture' },
{ name: 'Chair', category: 'Furniture' },
{ name: 'Apple', category: 'Fruit' }
];
// Which filter code is correct?
}q = ... || '' ensures empty query is handled. Converting both fields and query to lowercase enables case-insensitive matching.includes with lowercase conversion on both sides, correctly matching partial substrings in name or category.Pass the test and this pattern moves unknown