Firebase auth onAuthChange proper way to use

Viewed 861

I'm trying to use firebase auth module but when I try to make it work with it's method to unsubscribe it just won't call the method itself. My first aproach was without unsubscribe method, with worked but could make me have memory leaks:

useEffect(() => {
    firebase.auth().onAuthStateChanged((user) => {
      // My method
    });
  }, []);

Then I have been checking few websites and stackoverflow questions and they say it should be done like this:

useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      // My method
    });

    return unsubscribe();
  }, []);

This just does not call the firebase.auth().onAuthChanged method. Any suggestions?

Thanks very much.

1 Answers

Your second example is actually calling the returned unsubscribe function, then returning the result of that call (which returns nothing). That's not right. You just want to return the unsubscribe function itself so react can call it later when the observer is no longer needed:

useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      // My method
    });

    // Just return the unsubscribe function.  React will call it when it's
    // no longer needed.
    return unsubscribe;
  }, []);
Related