0 day streak
javascript / intermediate
Snippet

Generic Custom Hook for LocalStorage

This generic hook synchronizes state with LocalStorage while handling the Next.js SSR environment check (checking if window is defined).

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
Breakdown
1
useLocalStorage<T>
Uses TypeScript generics to allow any data type to be stored safely.
2
if (typeof window === 'undefined')
Ensures the code doesn't crash during Server-Side Rendering (SSR).