-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalstorage.tsx
43 lines (38 loc) · 1.34 KB
/
localstorage.tsx
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
32
33
34
35
36
37
38
39
40
41
42
43
import { useState, useEffect } from 'react';
/**
* A custom hook for managing state with local storage persistence
* @param key - The key to use in localStorage
* @param initialValue - The initial value of the state
* @returns [state, setState] - A stateful value and a function to update it
*/
function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] {
// Read the initial state from localStorage or use the provided initial value
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
// Update localStorage whenever the state changes
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.log(error);
}
}, [key, storedValue]);
// Custom setter function that can handle both direct values and update functions
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
export default useLocalStorage;