I'm writing a simple debounce function for an input component
export const debounce = (func, wait) => {
let timeout
return function (...args) {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
timeout = null
Reflect.apply(func, this, args)
}, wait)
}
}
it imported from an external file, and used as a wrap for input
onKeyUp handler inside a React component (Hooks)
const handleChange = debounce(() => console.log("test"), 1000)
PROBLEM: I'm getting "test" log every time when text in input
changes, not only one - as expected.
What am I doing wrong?
I'm not sure what is the problem with your code but here is a version with hooks working
import { useEffect, useState } from "react";
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
};
export default useDebounce;
and then you use it as
const debouncedValue = useDebounce(inputValue, delay);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.