4

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");
      }
    });
  }
Amar
  • 135
  • 1
  • 11
  • 1
    The auth state observer function you pass to `onAuthStateChanged` will be invoked whenever the user's auth state changes, until you remove that observer. If you're observing something different, please explain what you're doing and what's not working the way you expect. – Doug Stevenson Dec 11 '20 at 19:51
  • I was just trying to understand how componentDidMount works. Even after it is executed once but the function inside this hook is executed again. so what i guess is the function inside is registered inside callback event loop and is executed when user registers – Amar Dec 11 '20 at 20:04

1 Answers1

2

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for your wonderful answer. So i was right! This function inside is registered inside callback event loop just like addEventListner in Vanilla JavaScript – Amar Dec 11 '20 at 20:05