import { useEffect, useState } from 'react'; | |
export const useLocalStorage = <T>(key: string): T | null => { | |
const [value, setValue] = useState<T | null>(null); | |
useEffect(() => { | |
if (typeof window !== 'undefined') { | |
const item = localStorage.getItem(key); | |
if (item) { | |
try { | |
setValue(JSON.parse(item)); | |
} catch (e) { | |
console.error(`解析 localStorage ${key} 失败`, e); | |
} | |
} | |
} | |
}, [key]); | |
return value; | |
}; |