30 lines
763 B
TypeScript
30 lines
763 B
TypeScript
// FIX: This file was empty. Added a standard implementation for the useLocalStorage hook.
|
|
import { useState, useEffect, Dispatch, SetStateAction } from 'react';
|
|
|
|
function getStoredValue<T>(key: string, defaultValue: T): T {
|
|
if (typeof window === 'undefined') {
|
|
return defaultValue;
|
|
}
|
|
const saved = localStorage.getItem(key);
|
|
try {
|
|
return saved ? JSON.parse(saved) : defaultValue;
|
|
} catch {
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
export function useLocalStorage<T>(
|
|
key: string,
|
|
defaultValue: T
|
|
): [T, Dispatch<SetStateAction<T>>] {
|
|
const [value, setValue] = useState<T>(() =>
|
|
getStoredValue(key, defaultValue)
|
|
);
|
|
|
|
useEffect(() => {
|
|
localStorage.setItem(key, JSON.stringify(value));
|
|
}, [key, value]);
|
|
|
|
return [value, setValue];
|
|
}
|