Skip to content

Commit

Permalink
refactor(useRafTimeout): optimize useEffect cleanup fn (alibaba#2420)
Browse files Browse the repository at this point in the history
  • Loading branch information
coding-ice authored and Wait committed Feb 26, 2024
1 parent fef3676 commit f105b07
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions packages/hooks/src/useRafTimeout/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,20 @@ function useRafTimeout(fn: () => void, delay: number | undefined) {
const fnRef = useLatest(fn);
const timerRef = useRef<Handle>();

const clear = useCallback(() => {
if (timerRef.current) {
clearRafTimeout(timerRef.current);
}
}, []);

useEffect(() => {
if (!isNumber(delay) || delay < 0) return;
timerRef.current = setRafTimeout(() => {
fnRef.current();
}, delay);
return () => {
if (timerRef.current) {
clearRafTimeout(timerRef.current);
}
};
return clear;
}, [delay]);

const clear = useCallback(() => {
if (timerRef.current) {
clearRafTimeout(timerRef.current);
}
}, []);

return clear;
}

Expand Down

0 comments on commit f105b07

Please sign in to comment.