Debouncing
Satish kumar gupta
Front-End Developer, Having experience on live projects around 3 years.
Debounce limits the times an event fires. No matter how many times the user fires the event, the function will be executed only after a specific time after the last fired.
Key Features:
The useDebouncedValue hook is a custom React hook that delays the update of a value (inputValue) until a specified delay has passed since the last change.
import React, { useState, useEffect } from 'react';
const useDebouncedValue = (inputValue, delay) => {
const [debouncedValue, setDebouncedValue] = useState(inputValue);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(inputValue);
}, delay);
return () => {
clearTimeout(handler);
};
}, [inputValue, delay]);
return debouncedValue;
};
export default function App() {
const [value, setValue] = useState('');
const debouncedSearchTerm = useDebouncedValue(value, 500);
useEffect(() => {
// API call or other actions to be performed with debounced value
}, [debouncedSearchTerm]);
return (
<div>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</div>
);
}