Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use onAuthStateChanged inside a useEffect in React?

I am trying to implement authentication through firebase in a react project but all the tutorials that I see on online use onAuthStateChanged method inside a useEffect but I really dont understand what is the reason behind doing this instead of running it normally inside a function.

useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => setCurrentUser(user)
    });
    return unsubscribe;
}, []);

As per this logic wouldnt the function only run once, like if the user is not logged in the function will set currentuser to null and then when the user tries to login it will not setcurrentuser to user because here useffect will run only once on mount.

Maybe I have weak understanding of react hook concepts or maybe I am missing something here. I would really appreciate if someone could give an in depth explanation and explain in most basic terms as possible.

Thankss.

like image 719
Syed Abdullah Avatar asked Jun 29 '26 20:06

Syed Abdullah


1 Answers

As per this logic wouldnt the function only run once

The effect as a whole will just run once. When the effect runs, it executes this code:

auth.onAuthStateChanged((user) => setCurrentUser(user));

That's a subscription to firebase auth telling it that every time the auth state changes you want the function (user) => setCurrentUser(user) to be called. The inner function will get called at least once, but if the user logs in or out the function will get called again every time. This will continue happening until the unsubscribe function is called.

Since you've (correctly) returned the unsubscribe function from the effect, your component will stop listening for auth state changes when the component unmounts, but not before. If the component never unmounts, it will never stop listening for auth state changes.

like image 84
Nicholas Tower Avatar answered Jul 01 '26 12:07

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!