I'm using the firebase NPM package with Next.JS/React/Typescript. From what I can tell, there are two ways of watching when a user changes:
useEffect(() => {
// do something
}, [firebase.auth().currentUser])
and something like
const onAuthStateChanged = () => {
return firebase.auth().onAuthStateChanged((user) => {
// do something
});
};
useEffect(() => {
const unsubscribe = onAuthStateChanged();
return () => {
unsubscribe();
};
}, [])
What's the difference here? They both seem to just watch the currentUser; is one preferable over the other?
This will run everytime currentUser changes.
useEffect(() => {
// do something
}, [firebase.auth().currentUser])
This only runs the first time your component mounted. You create a listener to handle changes and remove it when component unmounted.
useEffect(() => {
const unsubscribe = onAuthStateChanged();
return () => {
unsubscribe();
};
}, [])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With