Skip to content

Commit

Permalink
refactor(useRafInterval): optimize useEffect cleanup fn (alibaba#2426)
Browse files Browse the repository at this point in the history
  • Loading branch information
coding-ice authored and raotaohub committed Mar 28, 2024
1 parent 2d51ce4 commit d1bd918
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 d1bd918

Please sign in to comment.