Skip to content

Commit

Permalink
refactor: remove unnecessary useEffect usage in useTimeoutFn hook
Browse files Browse the repository at this point in the history
  • Loading branch information
willnguyen1312 committed Feb 19, 2024
1 parent ade8d39 commit 3a93658
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/useTimeoutFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ export type UseTimeoutFnReturn = [() => boolean | null, () => void, () => void];
export default function useTimeoutFn(fn: Function, ms: number = 0): UseTimeoutFnReturn {
const ready = useRef<boolean | null>(false);
const timeout = useRef<ReturnType<typeof setTimeout>>();
const callback = useRef(fn);
const callback = useRef<Function>();
callback.current = fn;

const isReady = useCallback(() => ready.current, []);

Expand All @@ -15,6 +16,8 @@ export default function useTimeoutFn(fn: Function, ms: number = 0): UseTimeoutFn

timeout.current = setTimeout(() => {
ready.current = true;
// We know better than TypeScript that the callback is always available here
// @ts-ignore
callback.current();
}, ms);
}, [ms]);
Expand All @@ -24,11 +27,6 @@ export default function useTimeoutFn(fn: Function, ms: number = 0): UseTimeoutFn
timeout.current && clearTimeout(timeout.current);
}, []);

// update ref when function changes
useEffect(() => {
callback.current = fn;
}, [fn]);

// set on mount, clear on unmount
useEffect(() => {
set();
Expand Down

0 comments on commit 3a93658

Please sign in to comment.