score:1

Issue

So I've gathered that a user is on the "/login" path and authenticate and you redirect them to the home path "/". If I'm reading the code correctly it's at this point the RequireAuth wrapper mounts and checks the current user. The initial currentUser state is undefined, or in other words is a falsey value, and <Navigate to="/login"/> is rendered and the user is redirected back to the login page. This unmounts the RequireAuth but there's possibly the lingering enqueued state update.

Solution

Move the RequireAuth outside App. I don't think this is the direct cause of your issue, but it's simply an anti-pattern to declare React components within other React components. Each time App rerenders you actually are declaring a new RequireAuth component and any component state will be lost.

To resolve the routing issue, add an indeterminant "pending" state that is either authenticated nor unauthenticated, and don't commit to rendering the outlet or redirect until the wrapper component confirms the currentUser auth status. Using undefined works for this as it is neither a user object nor null with there is no user.

function RequireAuth() {
  const currentUser = useAuth();

  if (currentUser === undefined) {
    return null; // or loading indicator, etc...
  }

  return currentUser ? <Outlet /> : <Navigate to="/login"/>;
}

Related Query

More Query from same tag