File size: 794 Bytes
ddac6a2
 
f044ea5
 
ddac6a2
 
 
 
 
 
 
 
 
 
 
 
 
f044ea5
 
 
 
 
 
ddac6a2
f044ea5
ddac6a2
 
 
 
f044ea5
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
import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue, options = {}) {
  const { disableCache = false } = options;
  // 获取初始值
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  // 监听值的变化并更新到 localStorage
  useEffect(() => {
    if (!disableCache) {
      try {
        window.localStorage.setItem(key, JSON.stringify(storedValue));
      } catch (error) {
        console.error(error);
      }
    }
  }, [key, storedValue, disableCache]);

  return [storedValue, setStoredValue];
}

export default useLocalStorage;