Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: remove unnecessary useEffect usage in useTimeoutFn hook #2544

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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