Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Firebase user change with useEffect vs onAuthStateChanged - what's the difference?

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?

like image 864
James Whiteley Avatar asked Dec 18 '25 21:12

James Whiteley


1 Answers

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();
  };
}, [])
like image 110
Vo Quoc Thang Avatar answered Dec 20 '25 12:12

Vo Quoc Thang



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!