blob: 2b28b019746e7e75b0fffb78e17441916d36a426 [file] [log] [blame]
LaoeGaocid0773912025-06-09 00:38:40 +08001import { useEffect, useState } from 'react';
2
3export const useLocalStorage = <T>(key: string): T | null => {
4 const [value, setValue] = useState<T | null>(null);
5
6 useEffect(() => {
7 if (typeof window !== 'undefined') {
8 const item = localStorage.getItem(key);
9 if (item) {
10 try {
11 setValue(JSON.parse(item));
12 } catch (e) {
13 console.error(`解析 localStorage ${key} 失败`, e);
14 }
15 }
16 }
17 }, [key]);
18
19 return value;
20};