import { useEffect, useRef, useState } from 'react' import { getCookieByName } from '../utils' export const useCookieListener = ( key: string, handler: (value: string | null) => void ) => { const getCookie = () => getCookieByName(key) const [intervalValue, setIntervalValue] = useState() const cookieRef = useRef(getCookie()) const handleCookieChange = () => { const currentCookie = getCookie() const prevCookie = cookieRef.current if (currentCookie !== prevCookie) { cookieRef.current = getCookie() handler(cookieRef.current) } } useEffect(() => { const interval = setInterval(handleCookieChange, 500) setIntervalValue(interval) return () => { intervalValue && clearInterval(intervalValue) } // eslint-disable-next-line react-hooks/exhaustive-deps }, []) }