title: firebase onAuthStateChanged executes while sign-in state doesn't change, it also returns null before returning user
body: <p>I'm learning firebase authentication in react. I believed onAuthStateChanged only triggers when the user sign-in state changes. But even when I go to a different route or refresh the page, it would still execute.</p>
  <p>Here is my AuthContext.js</p>
  <pre><code>import React, {useContext,useEffect,useState} from 'react';
  import {auth} from './firebase';
  import { createUserWithEmailAndPassword, onAuthStateChanged, signInWithEmailAndPassword,
  signOut } from &quot;firebase/auth&quot;;
  
  const AuthContext = React.createContext();
  
  export function useAuth() {
      return useContext(AuthContext);
  }
  
  export function AuthProvider({children}) {
  
      const [currentUser,setCurrentUser] = useState();
      const [loading,setLoading] = useState(true);
  
      useEffect(()=&gt;{
          const unsub = onAuthStateChanged(auth,user=&gt;{
              setLoading(false);
              setCurrentUser(user);
              console.log(&quot;Auth state changed&quot;);
          })
          return unsub;
      },[])
  
      function signUp(email,password){
         return createUserWithEmailAndPassword(auth,email,password)
      }
  
      function login(email,password){
          return signInWithEmailAndPassword(auth,email,password);
      }
  
      function logout(){
          return signOut(auth);
      }
  
      const values = {
          currentUser,
          signUp,
          login,
          logout
      }
  
    return &lt;AuthContext.Provider value={values}&gt;
        {!loading &amp;&amp; children}
    &lt;/AuthContext.Provider&gt;;
  }
  </code></pre>
  <p>I put onAuthStateChanged in useEffect(), so every time the component renders the code inside will run. But why would onAuthStateChanged() still run when user sign-in state does not change? I'm asking this question because it created problems.
  onAuthStateChanged would first return a user of null. If user is already authenticated, it would return the user a second time. Because of the first &quot;null&quot; user, my other page would not work properly. For example, I have this private router that would always redirect to the login page even when the user is authenticated.</p>
  <p>My Private Route</p>
  <pre><code>import React from 'react';
  import {Route, Navigate} from &quot;react-router-dom&quot;;
  import { useAuth } from './AuthContext';
  
  export default function Private() {
      const {currentUser} = useAuth();
  
    return &lt;div&gt;
      {currentUser ? &lt;&gt;something&lt;/&gt;:&lt;Navigate to=&quot;/login&quot;/&gt;}
    &lt;/div&gt;;
  }
  
  </code></pre>
  <p>if onAuthStateChanged doesn't trigger when I don't sign in or log out, I wouldn't have the problems mentioned above</p>