diff --git a/src/context/ActivePetContext.tsx b/src/context/ActivePetContext.tsx index eed9bee..c15ab26 100644 --- a/src/context/ActivePetContext.tsx +++ b/src/context/ActivePetContext.tsx @@ -1,6 +1,6 @@ "use client"; -import { createContext, useContext, useState, useEffect } from "react"; +import { createContext, useContext, useState } from "react"; /** * Active Pet Context — tracks the currently active pet for the logged-in owner. @@ -25,13 +25,19 @@ const ActivePetContext = createContext(null); const STORAGE_KEY = "active_pet_id"; export function ActivePetProvider({ children }: { children: React.ReactNode }) { - const [activePetId, setActivePetId] = useState(null); - - useEffect(() => { - // Initialize from localStorage on client mount (avoids SSR mismatch) - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) setActivePetId(stored); - }, []); + // Lazy initializer reads localStorage synchronously on the client's first + // render (guarded by the window check for SSR, where localStorage doesn't + // exist) instead of via a useEffect. This used to be an effect, but + // ActivePetInitializer's own effect (a descendant, so it fires first — + // React runs effects child-before-parent) raced it: on every reload it + // saw activePetId still at its initial null and overwrote localStorage + // with the owner's first pet before this provider's effect ever read the + // real stored value, silently reverting the active-pet switch on every + // page reload. Reading synchronously here removes the race entirely. + const [activePetId, setActivePetId] = useState(() => { + if (typeof window === "undefined") return null; + return localStorage.getItem(STORAGE_KEY); + }); const setActivePet = (id: string) => { setActivePetId(id);