diff --git a/src/hooks/timer/useTimer.ts b/src/hooks/timer/useTimer.ts index fe0ab58..644e613 100644 --- a/src/hooks/timer/useTimer.ts +++ b/src/hooks/timer/useTimer.ts @@ -15,21 +15,28 @@ export function useTimer({ persist = false, storageKey, }: UseTimerOptions) { - const [seconds, setSeconds] = useState(() => { - if (persist && storageKey) { - const saved = localStorage.getItem(storageKey); - if (saved !== null) { - const parsed = parseInt(saved, 10); - if (!isNaN(parsed)) return parsed; - } - } - return initialSeconds; - }); + // Always initialize with initialSeconds to match SSR + const [seconds, setSeconds] = useState(initialSeconds); const intervalRef = useRef(null); + // Load from localStorage after mount (client-only) useEffect(() => { - if (persist && storageKey) { + if (persist && storageKey && typeof window !== 'undefined') { + const saved = localStorage.getItem(storageKey); + if (saved !== null) { + const parsed = parseInt(saved, 10); + if (!isNaN(parsed)) { + setSeconds(parsed); + return; // Don't save again if we just loaded + } + } + } + }, [persist, storageKey]); // Run once on mount + + // Save to localStorage when seconds change + useEffect(() => { + if (persist && storageKey && typeof window !== 'undefined') { localStorage.setItem(storageKey, seconds.toString()); } }, [seconds, persist, storageKey]); @@ -54,7 +61,7 @@ export function useTimer({ const reset = useCallback(() => { setSeconds(initialSeconds); - if (persist && storageKey) { + if (persist && storageKey && typeof window !== 'undefined') { localStorage.setItem(storageKey, initialSeconds.toString()); } }, [initialSeconds, persist, storageKey]);