Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

Firebase auth onAuthChange proper way to use with useEffect hook

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.

Upvotes: 2

Views: 1942

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

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:


// The new way of doing this is:
import { getAuth } from "firebase/auth";
import { onAuthStateChanged } from "firebase/auth";


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

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

Upvotes: 1

Related Questions