December 30, 2025
2025-12-30
// Generated at: 2025-12-30T20:26:31.862Z
Here's a simple yet practical React component that implements a debounced input field. This can be very useful for optimizing performance when dealing with user inputs that trigger searches or API calls.
import React, { useState, useEffect } from 'react';
const DebouncedInput = ({ debounceTime = 300, onChange }) => {
const [inputValue, setInputValue] = useState('');
useEffect(() => {
const handler = setTimeout(() => {
onChange(inputValue);
}, debounceTime);
return () => {
clearTimeout(handler);
};
}, [inputValue, debounceTime, onChange]);
return (
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Type something..."
/>
);
};
// Example usage:
// <DebouncedInput onChange={value => console.log(value)} />
How it works:
- This component takes
debounceTimeandonChangeas props. - It maintains an internal state for the input value.
- When the input changes, it sets a timeout for the
onChangecallback, which is only called after the specifieddebounceTimehas passed. - If the user types again before the timeout completes, the previous timeout is cleared, and a new one is set. This effectively debounces the input.
Usage:
You can use this DebouncedInput component wherever you need debounced input handling, like in search bars, to prevent excessive calls during typing. Simply pass a function to handle the input value when it's updated.