1
/
5

React - lodashなしでthrottleを使う方法

throttle 独自実装

TypeScript Reactでlodashをインストールせずすぐ使えるコード

useThrottle hook

import { useRef, useCallback, useEffect } from "react";

const useThrottle = <T extends any[]>(callback: (...args: T) => void, delay: number) => {
const waitingRef = useRef<boolean>(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

const throttledFunction = useCallback(
(...args: T) => {
if (waitingRef.current) return;
callback(...args);
waitingRef.current = true;
timeoutRef.current = setTimeout(() => {
waitingRef.current = false;
}, delay);
},
[callback, delay]
);

useEffect(() => {
return () => {
if (!timeoutRef.current) return;
clearTimeout(timeoutRef.current);
};
}, []);

return throttledFunction;
};

export default useThrottle;

使用例

import useThrottle from "@/components/hooks/useThrottle";

const throttledHandler = useThrottle(func, 10);