I am using React with Firebase to develop a small web app. To take care of authentication, I am using context API and inside context I am adding loggedin user details.
When the page loads Firebase restores the user's credentials from local storage and checks with the server whether they are still valid. Since this is a call to the server, it may take some time and happens asynchronously. This is the reason it is normal that firebase.auth().currentUser is null until onAuthStateChanged fires.
The problem you have is that there are multiple reasons firebase.auth().currentUser can be null:
firebase.auth().currentUser is null because the client just loaded and it's still checking the credentials with the server.firebase.auth().currentUser is null because the client checked the credentials against the server and the client isn't logged in.firebase.auth().currentUser is null because the user never signed in, so there are no credentials to check.You want to navigate in case 2 and 3, but not case 1.
The typical solution is to not handle navigation until the first time onAuthStateChanged has fired. At that point you can be certain that the credentials were checked against the server, or that there were no credentials to check, in both of which cases you'll want to navigate to the sign-in page.
An additional option to speed this up is to store a small token in local storage yourself when the user signs in for the first time, and then read that when the app loads. If the token is present you can distinguish between case 1 and 3, and use that to navigate to the correct page a bit sooner.
For an example of this, see this I/O talk about Architecting Mobile Web Apps.