From cbf7b80a6c578d0de10b353a57b93020a9ee9b61 Mon Sep 17 00:00:00 2001 From: Nalla Prakash <81852531+prakashNalla@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:20:25 +0530 Subject: [PATCH] fix(storage): don't write the initial value over stored data on mount --- lib/useLocalStorage.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/useLocalStorage.ts b/lib/useLocalStorage.ts index 42d0306..0a0d076 100644 --- a/lib/useLocalStorage.ts +++ b/lib/useLocalStorage.ts @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; export function useLocalStorage( key: string, @@ -8,7 +8,7 @@ export function useLocalStorage( ): [T, (value: T | ((prev: T) => T)) => void, () => void, Error | null] { const [value, setValue] = useState(initial); const [persistError, setPersistError] = useState(null); - const loadedRef = useRef(false); + const [loaded, setLoaded] = useState(false); useEffect(() => { try { @@ -17,11 +17,13 @@ export function useLocalStorage( } 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); @@ -30,7 +32,7 @@ export function useLocalStorage( // 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 {