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

[@mantine/hooks] use-timeout: Memoize returned callbacks #4914

Merged
merged 3 commits into from
Oct 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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