Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions lib/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useState } from "react";

export function useLocalStorage<T>(
key: string,
initial: T
): [T, (value: T | ((prev: T) => T)) => void, () => void, Error | null] {
const [value, setValue] = useState<T>(initial);
const [persistError, setPersistError] = useState<Error | null>(null);
const loadedRef = useRef(false);
const [loaded, setLoaded] = useState(false);

useEffect(() => {
try {
Expand All @@ -17,11 +17,13 @@ export function useLocalStorage<T>(
} catch {
/* ignore */
}
loadedRef.current = true;
setLoaded(true);
}, [key]);

// Wait for the render that has the stored value, or the initial value
// would be written over it on mount.
useEffect(() => {
if (!loadedRef.current) return;
if (!loaded) return;
try {
window.localStorage.setItem(key, JSON.stringify(value));
setPersistError(null);
Expand All @@ -30,7 +32,7 @@ export function useLocalStorage<T>(
// the user instead of silently dropping their data.
setPersistError(e instanceof Error ? e : new Error("Storage write failed"));
}
}, [key, value]);
}, [key, value, loaded]);

const reset = useCallback(() => {
try {
Expand Down
Loading