Jeff Huleatt

Avoid a flash of unauthenticated UI with Firebase Auth and React Router

If you're using Firebase Auth in a React app, you probably have a hook like this:

import { useState, useEffect } from "react";
import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();

export function useUser() {
  const [user, setUser] = useState(auth.currentUser);
  useEffect(() => onAuthStateChanged(auth, setUser), []);
  return user;
}

However, that hook has a big problem: it will nearly always return null immediately, resulting in a flash of unauthenticated UI before it fully initializes, even if the user is actually signed in.

Why does that happen? Firebase Auth stores login data in IndexedDB, which is asynchronous. Therefore, auth.currentUser will be set to null until the IndexedDB read completes.

You could go down the rabbit hole of managing loading states, or integrating with a query library that triggers Suspense until Auth is ready. However, if you're using React Router, there is already an easier way.

clientLoader is a special function that your page can export in React Router's Framework Mode (there's a similar loader API in Data Mode with createBrowserRouter). It gives you a spot to run setup code (even async code). On initial page load, React Router renders a HydrateFallback until clientLoader resolves, and on subsequent navigations it waits before switching pages:

"When the user navigates to a new url, the loaders for the next page are awaited before the next page renders" - React Router docs

This ends up looking something like:

import { redirect } from "react-router";
import { getAuth } from "firebase/auth";

export async function clientLoader() {
  const auth = getAuth();

  // Wait for Firebase Auth to finish initializing
  await auth.authStateReady();

  // auth.currentUser is now guaranteed to be accurate (User or null)
  if (!auth.currentUser) {
    throw redirect("/login");
  }

  return { user: auth.currentUser };
}

export function HydrateFallback() {
  return <p>Loading...</p>;
}

export default function Dashboard({ loaderData }) {
  const { user } = loaderData;

  return <h1>Welcome, {user?.displayName || user?.email || "friend"}!</h1>;
}

auth.authStateReady() returns a Promise that resolves once Firebase Auth finishes initializing on the page. After that, auth.currentUser can be read synchronously to get the current user.

If you still want to subscribe to auth state changes in the component with useUser, you can, but now you can be confident in the initial auth state, and avoid those flashes. TanStack Router has a similar API, so this pattern holds there, too.

#firebase #react