0 Tage Serie
javascript / intermediate
Snippet

Generischer Custom Hook für LocalStorage

Dieser generische Hook synchronisiert den State mit dem LocalStorage und berücksichtigt dabei den SSR-Umgebungscheck von Next.js (Prüfung, ob window definiert ist).

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
if (typeof window === 'undefined') return initialValue;
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = (value: T | ((val: T) => T)) => {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
};
return [storedValue, setValue] as const;
}
nextjs
Erklärung
1
useLocalStorage<T>
Verwendet TypeScript-Generics, um jeden Datentyp sicher speichern zu können.
2
if (typeof window === 'undefined')
Stellt sicher, dass der Code während des Server-Side Rendering (SSR) nicht abstürzt.