score:2

Accepted answer
const snapShotUnsubscribeRef = useRef();

useEffect(() => {
  const unsubscribe = firebase.auth.onAuthStateChanged(user => {
    if (user) {
      snapShotUnsubscribeRef.current = firebase.db
        .collection('users')
        .doc(user.uid)
        .onSnapshot(doc => {
          setUser({ user, ...doc.data() })
        })
    } else {
      setUser({ user })
    }
  });

  return () => {
    snapShotUnsubscribeRef.current?.();
    // Or if you can't use Optional Chaining:
    //   snapShotUnsubscribeRef.current && snapShotUnsubscribeRef.current()
    unsubscribe();
  };
}, [firebase]);

Related Query

More Query from same tag