Here's how to make a useDebounce()
hook in React, which lets you delay a function's execution:
import { useState, useEffect } from 'react';
const useDebounce = (value, delay) => {
// State to hold the debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// Update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cleanup function to clear timeout on value change
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
export default useDebounce;
You can use this useDebounce
hook in your components to debounce the execution of a function or the handling of a value change. Here's how you can use it:
import React, { useState } from 'react';
import useDebounce from './useDebounce'; // Assuming you've placed the hook in a separate file
const MyComponent = () => {
// State to hold input value
const [inputValue, setInputValue] = useState('');
// State to hold debounced input value
const debouncedInputValue = useDebounce(inputValue, 500);
// Handler function for input change
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
<h1>Debounce Example</h1>
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Type something..."
/>
<p>Debounced value: {debouncedInputValue}</p>
</div>
);
};
export default MyComponent;
In this example:
We create a functional component called
MyComponent
.We use the
useState
hook to keep track of the input value (inputValue
).We use the
useDebounce
hook to delay the input value (debouncedInputValue
) from updating right away.When the input value (
inputValue
) changes, theuseDebounce
hook waits for 500 milliseconds before updating the debounced value (debouncedInputValue
), but only if there are no new changes.We show the debounced value (
debouncedInputValue
) in the component, which is the input value after waiting for the specified delay.