Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
      }
    });
  }
like image 907
Amar Avatar asked Oct 25 '25 03:10

Amar


1 Answers

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.

like image 90
Frank van Puffelen Avatar answered Oct 27 '25 17:10

Frank van Puffelen



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!