Skip to content

Commit

Permalink
fix: 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 327aa64
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/useTimeoutFn.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useRef } from 'react';
import { useCallback, useEffect, useRef } from "react";

Check failure on line 1 in src/useTimeoutFn.ts

View workflow job for this annotation

GitHub Actions / Linting

Replace `"react"` with `'react'`

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 327aa64

Please sign in to comment.