Skip to content

Instantly share code, notes, and snippets.

@morellodev
Last active March 24, 2021 10:33
Show Gist options
  • Save morellodev/46fd0e20f878c1a811f5d6fec2cb568e to your computer and use it in GitHub Desktop.
Save morellodev/46fd0e20f878c1a811f5d6fec2cb568e to your computer and use it in GitHub Desktop.
Custom React Hook for reading a cookie value and listening for changes (by polling, to be compatible with all browsers)
import Cookie from "js-cookie";
import { useCallback, useEffect, useRef, useState } from "react";
const useCookieValue = (name) => {
const cookieUpdaterId = useRef();
const [currentCookie, setCurrentCookie] = useState(() => Cookie.get(name));
const updateCookie = useCallback(() => {
const cookie = Cookie.get(name);
if (cookie !== currentCookie) {
setCurrentCookie(cookie);
}
}, [currentCookie, name]);
useEffect(() => {
cookieUpdaterId.current = setInterval(updateCookie, 1000);
return () => clearInterval(cookieUpdaterId.current);
}, [updateCookie]);
return currentCookie;
};
export default useCookieValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment