MCPcopy
hub / github.com/dubinc/dub / useCookies

Function useCookies

packages/ui/src/hooks/use-cookies.ts:4–41  ·  view source on GitHub ↗
(
  key: string,
  initialValue: T,
  opts?: Cookies.CookieAttributes,
)

Source from the content-addressed store, hash-verified

2import { useEffect, useState } from "react";
3
4export function useCookies<T>(
5 key: string,
6 initialValue: T,
7 opts?: Cookies.CookieAttributes,
8): [T, (value: T) => void] {
9 const [storedValue, setStoredValue] = useState<T>(() => {
10 // Retrieve from Cookies
11 const item = Cookies.get(key);
12 return item ? JSON.parse(item) : initialValue;
13 });
14
15 useEffect(() => {
16 // Update state if the cookie changes
17 const handleStorageChange = () => {
18 const item = Cookies.get(key);
19 if (item) {
20 setStoredValue(JSON.parse(item));
21 }
22 };
23
24 // Add listener for storage changes
25 window.addEventListener("storage", handleStorageChange);
26
27 // Cleanup
28 return () => {
29 window.removeEventListener("storage", handleStorageChange);
30 };
31 }, [key]);
32
33 const setValue = (value: T) => {
34 // Save state
35 setStoredValue(value);
36 // Save to Cookies
37 Cookies.set(key, JSON.stringify(value), opts);
38 };
39
40 return [storedValue, setValue];
41}

Callers 1

ModalProviderClientFunction · 0.90

Calls 1

getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…