useDebounce, useThrottle - boostcamp-2020/Project15-C-Client-Based-Formula-Editor GitHub Wiki
useDebounce์ useThrottle์ debounce์ throttle์ด ์ ์ฉ๋ ํจ์๋ฅผ ๋ฐํํด์ฃผ๋ hook์ด๋ค.
timer๋ฅผ useRef๋ก ํ์ฌ ๋ฆฌ๋ ๋๋ง ๋ผ๋ timer๊ฐ ์ด๊ธฐํ ๋๋ ํ์์ ๋ง๋๋ค.
callback ํจ์์ ํ์ ์ถ๋ก ์ ์ํ๊ฒ ํ๊ธฐ ์ํด์ <T extends any[]> ๋ฅผ generic์ผ๋ก ๋ฐ๋๋ค. ์ด๋ ๊ฒ ํ๋ ์ด์ ๋ ...params ํํ๋ก ์ฌ๋ฌ ๊ฐ์ ์ธ์๋ฅผ ๋ฐ์ ์ ์๊ฒ ํ๊ธฐ ์ํด์์ด๋ค. callback ํจ์์ ์ธ์๊ฐ ๋ช๊ฐ๊ฐ ๋ค์ด์ฌ์ง ๋ชจ๋ฅด๋ ์ ๋ฐฉ์์ผ๋ก ํด๊ฒฐํ์๋ค.
ํด๋น hook์ ๋ ๋ค ๋๊ฐ์ด callback๊ณผ time์ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ๋๋ค.
debounce๋ time ์์ ํจ์๊ฐ ํ๋ฒ๋ ์คํ๋๋ฉด ์์ ์์ ์ ์ทจ์ํ๊ณ time์ด ์ง๋ ๋๊น์ง ๋ค์ ํธ์ถ ๋์ง ์์ผ๋ฉด callback์ ์คํํ๋ ํ์์ผ๋ก ๋์ด์๋ค.
throttle์ time ๋ค์ callback์ด ์คํ๋๊ณ time์ด ์ง๋๊ธฐ์ ๋ค์ ํธ์ถ๋ ๊ฒฝ์ฐ ์์ง time์ด ์ง๋์ง ์์๊ธฐ ๋๋ฌธ์ callback์ ์คํํ์ง ์๊ณ ํจ์๋ฅผ ์ข ๋ฃ์ํค๋ ํํ๋ก ๋์ด์๋ค.
์ฝ๋๋ ๋ค์๊ณผ ๊ฐ๋ค. ์ด์ ์ด๋ค ํจ์๋ debounce ์ throttle์ ์ ์ฉํ ์ ์๊ฒ ๋์๋ค.
useDebounce
import { useRef } from 'react';
function useDebounce<T extends any[]>(callback: (...params: T) => void, time: number) {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
return (...params: T) => {
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => {
callback(...params);
timer.current = null;
}, time);
};
}
export default useDebounce;
useThrottle
import { useRef } from 'react';
function useThrottle<T extends any[]>(callback: (...params: T) => void, time: number) {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
return (...params: T) => {
if (!timer.current) {
timer.current = setTimeout(() => {
callback(...params);
timer.current = null;
}, time);
}
};
}
export default useThrottle;
์ค์ ์ฌ์ฉ ์
const onScroll = (e: React.UIEvent<HTMLDivElement>) => {
const target = e.target as HTMLDivElement;
const scrollHeight = target.scrollHeight;
const scrollTop = target.scrollTop;
const clientHieght = target.clientHeight;
if (scrollTop + clientHieght >= scrollHeight - 50 && maxNumber < allMenu.current.length) {
setMaxNumber((number) => number + DISPLAY_INTERVAL);
}
};
const throttleOnScroll = useThrottle<[React.UIEvent<HTMLDivElement>]>(onScroll, 300);
์์ callback์ผ๋ก ๋๊ฒจ์ค ํจ์๋ฅผ ์ ์ํด์ค๋ค.
๊ทธ๋ฆฌ๊ณ useThrottle์ ์คํํด์ throttle์ด ์ ์ฉ๋ ํจ์๋ฅผ ๋ฐ์ผ๋ฉด ๋๋ค. ์ค์ํ ๊ฒ์ T์ ๋ค์ด๊ฐ ํ์ ์ด๋ค. callback์ผ๋ก ๋๊ฒจ์ค ํจ์์ ํ๋ผ๋ฏธํฐ ํ์ ์์๋๋ก ( ex)<[type1, type2] ์ด๋ฐ์) ์ ์ด์ฃผ์ด์ผํ๋ค. ๊ทธ๋ฌ๋ฉด ๋ฐํ๋ throttleOnScroll ํจ์์์๋ ํ์ ์ถ๋ก ์ด ๋๋ ๊ฒ์ ํ์ธํ ์ ์์ ๊ฒ์ด๋ค.