import { useCallback, useEffect, useState } from 'react';
const useDebounce = ({ func, delay, deps }) => {
const callback = useCallback(func, deps);
useEffect(() => {
const timer = setTimeout(() => {
callback();
}, delay);
return () => {
clearTimeout(timer);
};
}, [callback, delay]);
};
export { useDebounce };
import { useMemo, useState, ChangeEvent, MouseEvent } from 'react';
import { useDebounce } from 'util/hooks/useDebounce';
const About = () => {
const [second, setSecond] = useState<string>('');
const [timer, setTimer] = useState<any>(0);
const handleOnChangeSecond = (e: ChangeEvent<HTMLInputElement>) => {
setSecond(e.target.value as string);
if (timer) {
console.log('clear', timer);
clearTimeout(timer);
}
const newTimer = setTimeout(() => {
console.log('hi!', e.target.value);
}, 800);
setTimer(newTimer);
return;
};
const handleNormalOne = () => {
console.log('hi!');
};
useDebounce({
func: () => {
console.log('debounce????');
},
delay: 1000,
deps: [second],
});
return (
<div role="heading">
<div>
<h2>second</h2>
<h4>{second}</h4>
</div>
<input onChange={handleOnChangeSecond} />
<input onChange={handleNormalOne} />
</div>
);
};
export default About;