How does firebase's onAuthStateChanged work in ComponentDidMount lifecycle in reactJS

1.5k views Asked by At

Can anyone explain we how this onAuthStateChanged function is working inside componentDidMount. I know this lifecycle hook get executed only once when the component is mounted. So how does the function inside gets executed?

What I assume is it's like callback function which keeps on running in event loop as gets fired when state changed like addEventlistner in JS.

componentDidMount() {
    console.log("Context Mounted");
    firebaseapp.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({ currentUser: user });
        console.log("User Signed IN ");
      } else {
        console.log("THERE IS NO USER");
      }
    });
  }
1

There are 1 answers

1
Frank van Puffelen On BEST ANSWER

You pretty much got the gist of it: after your register your onAuthStateChanged callback with Firebase it will be called:

  1. "immediately" with the current authentication state
  2. whenever that authentication state changes

Since you call setState to put the user into the state, this then triggers a rerender of the UI whenever one of the above events occurs.

This continues until the app exits or until your unregister the listener, which you should typically do in the componentWillUnmount method of the same component.