Handle Async User for Privates Routes (react-router-dom)

Hi !

In the intermediate lesson for routing (React 18), you introduce the concept of Privates Routing by introducing a PrivatesRoute component. You used a simple function to simulate a login. But in a real world application, the connection is not immediate and, even if the user is connected, on refresh user will be null.

const PrivatesRoutes = () => {
  const { user } = useContext(UserContext);
  // On refresh, user could be null the time we get the info from the backend
  if (!user) {
    // Redirection if user is null 
    return <Navigate to="/login" />;

  // Never go here
  return <Outlet />;

export default PrivatesRoutes;

But with this kind of implementation, the redirection will be done as soon as the user is “null” and we redirect to login page. The component doesn’t wait for user info to come.

As the “/login” doesn’t go through the PrivatesRoutes , we don’t check if the user is logged again.

The router is like this :

const router = createBrowserRouter([
    path: "/",
    layout: <App />,
    children: [{ path: "login", element: <LoginPage /> }],
  { path: "/", layout: <App />, element: <PrivatesRoutes />, children: [{ index: true, element: <HomePage /> }] },

What could be the best practice ?