Skip to content

Commit 11eced0

Browse files
Fix infinite loop on return
Fixed an infinite loop in the `useAuth` hook.
1 parent d1a367a commit 11eced0

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

src/hooks/useAuth.tsx

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
import { useEffect, useState } from 'react';
2+
import { useEffect, useState, useRef } from 'react';
33
import {
44
User,
55
signInWithEmailAndPassword,
@@ -12,25 +12,47 @@ import { auth, googleProvider } from '@/lib/firebase';
1212

1313
export const useAuth = () => {
1414
const [user, setUser] = useState<User | null>(null);
15-
const [loading, setLoading] = useState(false);
15+
const [loading, setLoading] = useState(true); // Commence à true pour éviter les flickers
1616
const [initialized, setInitialized] = useState(false);
17+
const unsubscribeRef = useRef<(() => void) | null>(null);
1718

1819
useEffect(() => {
20+
// Éviter les initialisations multiples
21+
if (initialized) {
22+
return;
23+
}
24+
1925
console.log('🔐 Initialisation de l\'authentification...');
2026

21-
setInitialized(true);
27+
// S'assurer qu'on n'a qu'un seul listener
28+
if (unsubscribeRef.current) {
29+
unsubscribeRef.current();
30+
}
2231

2332
const unsubscribe = onAuthStateChanged(auth, (user) => {
2433
console.log('🔐 État d\'authentification changé:', user ? 'Connecté' : 'Déconnecté');
2534
setUser(user);
2635
setLoading(false);
36+
if (!initialized) {
37+
setInitialized(true);
38+
}
2739
}, (error) => {
2840
console.error('🚨 Erreur d\'authentification:', error);
2941
setLoading(false);
42+
if (!initialized) {
43+
setInitialized(true);
44+
}
3045
});
3146

32-
return unsubscribe;
33-
}, []); // Dépendances vides pour éviter les boucles
47+
unsubscribeRef.current = unsubscribe;
48+
49+
return () => {
50+
if (unsubscribeRef.current) {
51+
unsubscribeRef.current();
52+
unsubscribeRef.current = null;
53+
}
54+
};
55+
}, [initialized]); // Dépendance sur initialized pour éviter les boucles
3456

3557
const signInWithEmail = async (email: string, password: string) => {
3658
console.log('🔐 Tentative de connexion avec email:', email);

0 commit comments

Comments
 (0)