Skip to content

Commit

Permalink
[refactor] use-timeout: Memoize returned callbacks (#4914)
Browse files Browse the repository at this point in the history
* [@mantine/hooks] use-timeout: Memoize returned callbacks

* [@mantine/hooks] use-timeout: remove delay from effect dependencies

* [@mantine/hooks] use-timeout: remove autoInvoke from effect dependencies
  • Loading branch information
Raicuparta authored Oct 1, 2023
1 parent 4bffeff commit a878762
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions src/mantine-hooks/src/use-timeout/use-timeout.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRef, useEffect } from 'react';
import { useRef, useEffect, useCallback } from 'react';

export function useTimeout(
callback: (...callbackParams: any[]) => void,
Expand All @@ -7,29 +7,32 @@ export function useTimeout(
) {
const timeoutRef = useRef<number | null>(null);

const start = (...callbackParams: any[]) => {
if (!timeoutRef.current) {
timeoutRef.current = window.setTimeout(() => {
callback(callbackParams);
timeoutRef.current = null;
}, delay);
}
};
const start = useCallback(
(...callbackParams: any[]) => {
if (!timeoutRef.current) {
timeoutRef.current = window.setTimeout(() => {
callback(callbackParams);
timeoutRef.current = null;
}, delay);
}
},
[callback, delay]
);

const clear = () => {
const clear = useCallback(() => {
if (timeoutRef.current) {
window.clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
}, []);

useEffect(() => {
if (options.autoInvoke) {
start();
}

return clear;
}, [delay]);
}, [clear, start]);

return { start, clear };
}

0 comments on commit a878762

Please sign in to comment.