How to remove the new firebase onAuthStateChanged listener in react

I know I am late to the game, but here's a hooks based solution:

React.useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => { // detaching the listener
        if (user) {
            // ...your code to handle authenticated users. 
        } else {
            // No user is signed in...code to handle unauthenticated users. 
        }
    });
    return () => unsubscribe(); // unsubscribing from the listener when the component is unmounting. 
}, []);

Any listeners that you have set up will also need to be torn down.

Your suspicions are very much on-spot.

You should use the componentWillUnmount lifecycle method to remove any leftover listeners that might pollute your app.

To clear up the listener, here's the relevant code:

Inside your authListener function you need to save a reference to the listener inside your component (it is returned to you as a result of calling firebase.auth().onAuthStateChanged). It will be a hook that will un-reference the listener and remove it.

So instead of just calling it, save the returned value as such

this.fireBaseListener = firebase.auth().onAuthStateChanged ...

And when your component un-mounts, use this code:

componentWillUnmount() {
   this.fireBaseListener && this.fireBaseListener();
   this.authListener = undefined;
}