Debounced Search Input
ReactJS
Hard
6 views
Problem Description
Debounce a search input so it updates results after user stops typing.
Output Format
Render a React component.
Constraints
Use useEffect with a timeout and cleanup on change.
Official Solution
import React, { useEffect, useMemo, useState } from 'react';
const all = ['React state', 'React props', 'React hooks', 'CSS grid', 'HTML forms', 'meetcode daily'];
export default function App() {
const [text, setText] = useState('');
const [query, setQuery] = useState('');
useEffect(() => {
const id = setTimeout(() => setQuery(text.trim()), 350);
return () => clearTimeout(id);
}, [text]);
const results = useMemo(() => {
if (!query) return all;
return all.filter((x) => x.toLowerCase().includes(query.toLowerCase()));
}, [query]);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode search</h2>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder='Type to search' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 10, color: '#555' }}>Query: {query || '...'}</div>
<ul style={{ marginTop: 10, paddingLeft: 18 }}>
{results.map((r) => <li key={r}>{r}</li>)}
</ul>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!