|
|
@@ -10,23 +10,21 @@ export function useLocalStorage<T>(
|
|
|
key: string,
|
|
|
initialValue: T
|
|
|
): [T, (value: T | ((prevValue: T) => T)) => void, () => void] {
|
|
|
- // State to store our value
|
|
|
- // Pass initial state function to useState so logic is only executed once
|
|
|
- const [storedValue, setStoredValue] = useState<T>(() => {
|
|
|
- if (typeof window === 'undefined') {
|
|
|
- return initialValue;
|
|
|
- }
|
|
|
+ // Always start with initialValue to prevent hydration mismatch
|
|
|
+ // Load from localStorage only after client-side hydration
|
|
|
+ const [storedValue, setStoredValue] = useState<T>(initialValue);
|
|
|
+
|
|
|
+ // Load value from localStorage after component mounts (client-side only)
|
|
|
+ useEffect(() => {
|
|
|
try {
|
|
|
- // Get from local storage by key
|
|
|
const item = window.localStorage.getItem(key);
|
|
|
- // Parse stored json or if none return initialValue
|
|
|
- return item ? JSON.parse(item) : initialValue;
|
|
|
+ if (item) {
|
|
|
+ setStoredValue(JSON.parse(item));
|
|
|
+ }
|
|
|
} catch (error) {
|
|
|
- // If error also return initialValue
|
|
|
console.warn(`Error loading localStorage key "${key}":`, error);
|
|
|
- return initialValue;
|
|
|
}
|
|
|
- });
|
|
|
+ }, [key]);
|
|
|
|
|
|
// Return a wrapped version of useState's setter function that ...
|
|
|
// ... persists the new value to localStorage.
|