How to use useEffect with firebase's signin method properly?

Viewed 132

Current code

const [uid, setUid] = React.useState(null);

useEffect(() => {
  if (!uid) {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        const { uid } = user;
        setUid(uid);
      } else {
        Authentication.signInAnonymously();
      }
    });
  }
});
import { ENV } from 'app/config/Env';
import firebase from 'firebase';

const { firebaseConfig } = ENV;

firebase.initializeApp(firebaseConfig);

export default {
  signInAnonymously() {
    firebase.auth().signInAnonymously();
  },
};

If not signed in, users need to sign in with firebase's signInAnonymously method.

This is working but I'm not sure about if this code is right.

I would appreciate it if you could give me any advice.

1 Answers

Your code will result in multiple calls to firebase.auth every time the component is rendered, until the uid gets populated. While it might work, this doesn't seem desirable. It'd be better to run that block of code only once, the first time the component mounts:

const [uid, setUid] = React.useState(null);

useEffect(() => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      const { uid } = user;
      setUid(uid);
    } else {
      Authentication.signInAnonymously();
    }
  });
}, []);
// ^^  use an empty dependency array - this is very important
// to ensure the above block runs exactly once, when component mounts
Related