11'use client' ;
22
3- import { createContext , useContext , useState , useEffect , ReactNode } from 'react' ;
3+ import { createContext , useContext , useState , ReactNode } from 'react' ;
44import posthog from 'posthog-js' ;
55
66interface User {
@@ -20,17 +20,19 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
2020const users : Map < string , User > = new Map ( ) ;
2121
2222export function AuthProvider ( { children } : { children : ReactNode } ) {
23- const [ user , setUser ] = useState < User | null > ( null ) ;
23+ // Use lazy initializer to read from localStorage only once on mount
24+ const [ user , setUser ] = useState < User | null > ( ( ) => {
25+ if ( typeof window === 'undefined' ) return null ;
2426
25- useEffect ( ( ) => {
2627 const storedUsername = localStorage . getItem ( 'currentUser' ) ;
2728 if ( storedUsername ) {
2829 const existingUser = users . get ( storedUsername ) ;
2930 if ( existingUser ) {
30- setUser ( existingUser ) ;
31+ return existingUser ;
3132 }
3233 }
33- } , [ ] ) ;
34+ return null ;
35+ } ) ;
3436
3537 const login = async ( username : string , password : string ) : Promise < boolean > => {
3638 try {
@@ -42,13 +44,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
4244
4345 if ( response . ok ) {
4446 const { user : userData } = await response . json ( ) ;
45-
47+
4648 let localUser = users . get ( username ) ;
4749 if ( ! localUser ) {
48- localUser = userData ;
50+ localUser = userData as User ;
4951 users . set ( username , localUser ) ;
5052 }
51-
53+
5254 setUser ( localUser ) ;
5355 localStorage . setItem ( 'currentUser' , username ) ;
5456
0 commit comments