71

As of version ^3.0.0, I'm having a difficult time removing the auth state change listener.

To start the listener per the documentation:

firebase.auth().onAuthStateChanged(function (user) {
    // handle it
});

However, I cannot find anywhere in the documentation that refers to a remove auth state change listener. There is peculiar function on the Firebase.Auth class called removeAuthTokenListener. Unfortunately it's not documented (firebase docs reference).

Via your browser's web console.

var auth = firebase.auth();
auth.removeAuthTokenListener;

prints a function definition that takes one parameter. I tried to do the following:

this.authListener = firebase.auth().onAuthStateChanged(function (user) {...});
firebase.auth().removeAuthTokenListener(this.authListener);

but that didn't do anything.

2 Answers 2

139

According to the documentation, the onAuthStateChanged() function returns

The unsubscribe function for the observer.

So you can just:

var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
    // handle it
});

And then:

unsubscribe();
5
  • Oh jeez... not sure how I missed that. Thank you. May 22, 2016 at 4:14
  • 7
    I actually didn't know how it worked, but have some more experience making the most out of our documentation. ;-) May 22, 2016 at 4:24
  • 7
    Sorry if this is a dumb question, but why would an application ever need to unsubscribe from this observer?
    – nomad
    Jun 1, 2016 at 3:57
  • 8
    For example, when the user intentionally logs out and you don't want execute the listener anymore
    – dvdvck
    Aug 17, 2016 at 23:26
  • The documentation for firebase v9 shows it works the same way.
    – cgenco
    Jan 26, 2022 at 2:16
5

This has already been answered really well by Frank van Puffelen, but here is my use case for React components that are getting user data. These components need to unsubscribe when the component is unmounted or there will be a memory leak for each of these components.

React.useEffect(() => {
  let unsubscribe;
  const getUser = async () => {
    unsubscribe = await firebase.checkUserAuth(user => setUser(user));
  };
  getUser();
  return unsubscribe;
}, []);
2
  • not sure why the following didnt work for me. Your answer helped me tho useEffect(() => { const unsubscribe = firebase.auth().onStateChanged((user) => console.log(user)) return unsubscribe() }, []) May 10, 2021 at 16:45
  • 2
    as unsubscribe is already a function, you simply need to return that from the useEffect for clean-up. i.e. "return unsusbscribe;". Much cleaner than returning a function that calls a function ! Jun 28, 2021 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.