Skip to content

Commit

Permalink
fix: use memoized fn in use-interval (#2029) (#2070)
Browse files Browse the repository at this point in the history
* fix: use memoized fn in use-interval

* fix: fn naming

---------

Co-authored-by: lijianan <574980606@qq.com>
  • Loading branch information
kongmoumou and li-jia-nan authored Mar 6, 2023
1 parent 0c5d74a commit ef8624a
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions packages/hooks/src/useInterval/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef } from 'react';
import useLatest from '../useLatest';
import useMemoizedFn from '../useMemoizedFn';
import { isNumber } from '../utils';

function useInterval(
Expand All @@ -11,25 +11,23 @@ function useInterval(
) {
const { immediate } = options;

const fnRef = useLatest(fn);
const timerCallback = useMemoizedFn(fn);
const timerRef = useRef<NodeJS.Timer | null>(null);

useEffect(() => {
if (!isNumber(delay) || delay < 0) {
return;
}
if (immediate) {
fnRef.current();
timerCallback();
}
timerRef.current = setInterval(() => {
fnRef.current();
}, delay);
timerRef.current = setInterval(timerCallback, delay);
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, [delay]);
}, [delay, timerCallback]);

const clear = useCallback(() => {
if (timerRef.current) {
Expand Down

0 comments on commit ef8624a

Please sign in to comment.