1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| let cbs = []; const useStorage = (key, initValue) => { const subscribe = (cb) => { cbs = [...cbs, cb]; return () => { cbs = cbs.filter(l => l !== cb); }; }
const emitChange = () => { for (let cb of cbs) { cb(); } }
const getSnapshot = () => { return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : initValue }
const updateStorage = (value) => { localStorage.setItem(key, JSON.stringify(value)) emitChange() } const res = useSyncExternalStore(subscribe, getSnapshot) return [res, updateStorage] }
|