useDebouncedValue Hook
ReactJS
Hard
7 views
Problem Description
Create a hook that debounces a value and updates after a delay.
Output Format
Render a React component.
Constraints
Use useEffect + setTimeout and clean it up on change.
Official Solution
import React, { useEffect, useState } from 'react';
function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}
export default function App() {
const [query, setQuery] = useState('');
const debounced = useDebouncedValue(query, 450);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode search</h2>
<input value={query} onChange={(e) => setQuery(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' }}>Debounced: {debounced || '...'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!