mirror of
https://github.com/emsesp/EMS-ESP32.git
synced 2026-01-27 00:59:10 +03:00
optimizations
This commit is contained in:
@@ -2,24 +2,43 @@ import { useEffect, useRef } from 'react';
|
||||
|
||||
const DEFAULT_DELAY = 3000;
|
||||
|
||||
// adapted from https://www.joshwcomeau.com/snippets/react-hooks/use-interval/
|
||||
export const useInterval = (callback: () => void, delay: number = DEFAULT_DELAY) => {
|
||||
const intervalRef = useRef<number | null>(null);
|
||||
const savedCallback = useRef<() => void>(callback);
|
||||
/**
|
||||
* Custom hook for setting up an interval with proper cleanup
|
||||
* Adapted from https://www.joshwcomeau.com/snippets/react-hooks/use-interval/
|
||||
*
|
||||
* @param callback - Function to be called at each interval
|
||||
* @param delay - Delay in milliseconds (default: 3000ms)
|
||||
* @param immediate - If true, executes callback immediately on mount (default: false)
|
||||
* @returns Reference to the interval ID
|
||||
*/
|
||||
export const useInterval = (
|
||||
callback: () => void,
|
||||
delay: number = DEFAULT_DELAY,
|
||||
immediate = false
|
||||
) => {
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const savedCallback = useRef(callback);
|
||||
|
||||
// Remember the latest callback without resetting the interval
|
||||
useEffect(() => {
|
||||
savedCallback.current = callback;
|
||||
}, [callback]);
|
||||
|
||||
useEffect(() => {
|
||||
const tick = () => savedCallback.current();
|
||||
intervalRef.current = window.setInterval(tick, delay);
|
||||
|
||||
// Execute immediately if requested
|
||||
if (immediate) {
|
||||
tick();
|
||||
}
|
||||
|
||||
intervalRef.current = setInterval(tick, delay);
|
||||
return () => {
|
||||
if (intervalRef.current !== null) {
|
||||
window.clearInterval(intervalRef.current);
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
};
|
||||
}, [delay]);
|
||||
}, [delay, immediate]);
|
||||
|
||||
return intervalRef;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user