debounce 2
12930 ワード
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;
Reference
この問題について(debounce 2), 我々は、より多くの情報をここで見つけました https://velog.io/@zerozoo-front/debounce-2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol