[Chapter 8] Debouncing & Throttling#47
Merged
starvingorange merged 1 commit intogang/mainfrom May 23, 2025
Merged
Conversation
duwlsssss
approved these changes
May 23, 2025
| @@ -0,0 +1,13 @@ | |||
| import { useRef } from "react"; | |||
|
|
|||
| export default function useThrottledFn(fn: () => void, delay: number) { | |||
Contributor
There was a problem hiding this comment.
지금은 훅이 매개변수가 없는 함수만 받을 수 있게 제한되어 있어요
다양한 매개변수를 받는 모든 형태의 함수를 받게 하려면, 제네릭을 추가하는 게 좋겠어요!
추가로 callback을 ref로 관리해 useThrottleCallback 훅을 사용하는 컴포넌트가 리렌더링되도 넘긴 callback이 새로 생성되지 않아야 쓰로틀링이 안전하게 동작할 것 같아요!
export default function useThrottledFn<T extends (...args: any[]) => void>(
fn: T,
delay: number
): T {
const lastCalled = useRef(0);
const savedFn = useRef(fn);
// 최신 fn을 항상 유지
useEffect(() => {
savedFn.current = fn;
}, [fn]);
return useCallback((...args: Parameters<T>) => {
const now = Date.now();
if (now - lastCalled.current >= delay) {
lastCalled.current = now;
savedFn.current(...args); // 최신 함수 사용
}
}, [delay]) as T;
}
이런식으로 하면 더 확장성있는 훅이 될 것 같습니다
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
✏️ 작업 내용
#️⃣ 연관된 이슈
#46
Week8-1.mp4
Week8-2.mp4
💡 함께 공유하고 싶은 부분
🤔 질문
✅ 워크북 체크리스트
✅ 컨벤션 체크리스트