Firebase stop listening onAuthStateChanged

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;
}, []);

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();