import { useRef, useEffect } from 'react';
import { DEBOUNCE_RESIZE_DELAY } from '../../constants/debounceResize';

/**
 * Hook to attach a function to the window's resize event with a debounce to prevent excessive updates
 * @param {Function} onResizeCallback function to call on window resize
 */
export const useDebounceResize = onResizeCallback => {
    const resizeTimeoutId = useRef(null);
    useEffect(() => {
        const onResize = () => {
            if (resizeTimeoutId.current) {
                clearTimeout(resizeTimeoutId.current);
            }
            resizeTimeoutId.current = setTimeout(onResizeCallback, DEBOUNCE_RESIZE_DELAY);
        };

        window.addEventListener('resize', onResize);
        return () => window.removeEventListener('resize', onResize);
    }, [resizeTimeoutId, onResizeCallback]);
};
