Skip to content

Commit

Permalink
refactor(useRafInterval): optimize useEffect cleanup fn (#2426)
Browse files Browse the repository at this point in the history
  • Loading branch information
coding-ice authored Mar 5, 2024
1 parent e55414b commit 256a753
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions packages/hooks/src/useRafInterval/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ function useRafInterval(
const fnRef = useLatest(fn);
const timerRef = useRef<Handle>();

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

useEffect(() => {
if (!isNumber(delay) || delay < 0) {
return;
Expand All @@ -61,19 +67,9 @@ function useRafInterval(
timerRef.current = setRafInterval(() => {
fnRef.current();
}, delay);
return () => {
if (timerRef.current) {
clearRafInterval(timerRef.current);
}
};
return clear;
}, [delay]);

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

return clear;
}

Expand Down

0 comments on commit 256a753

Please sign in to comment.