import { Dispatch, useMemo, useState, useCallback, useEffect } from "react"; import { useApp } from "../App"; export default function useLocalStorage(key: string) : [string|null, Dispatch] { const app = useApp(); const _key = app.id + '_' + key; const [ value, setValue ] = useState(() => typeof window !== 'undefined' ? window.localStorage.getItem(_key) : null); const update = useCallback(function(value: string) { setValue(value); localStorage.setItem(_key, value); }, [setValue]); useEffect(function() { const updateFnc = function(e: StorageEvent) { if (e.key === _key) { setValue(e.newValue); } }; window.addEventListener('storage', updateFnc); return function() { window.removeEventListener('storage', updateFnc); }; }, [_key, update]); return useMemo(() => [ value, update ], [ value, update ]); }