React Router: “Invalid hook call” when using higher-order components for authentication

React Router: “Invalid hook call” when using higher-order components for authentication

Problem

I have two different implementations of authentication wrappers for my React components using React Router. The first implementation works correctly, while the second one causes an “Invalid hook call” error. I don’t understand why this is happening.

Working Implementation

import { PropsWithChildren } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from './auth-provider'

export function WithOptimisticAuth(props: PropsWithChildren) {
  const { isAuthenticated, isLoading, isError } = useAuth()
  if (isError || (!isLoading && isAuthenticated === false)) return <Navigate to="/login" replace />
  return <>{props.children}</>
}

export function WithConfirmedAuth(props: PropsWithChildren) {
  const { isAuthenticated, isLoading, isError } = useAuth()
  if (isLoading) return <></>
  if (isError || isAuthenticated === false) return <Navigate to="/login" replace />
  return <>{props.children}</>
}

Usage in router configuration:

// ... (router configuration)
.with(Routes.Installations, () => ({
  path: Routes.Installations,
  element: (
    <WithOptimisticAuth>
      <InstallationsPage />
    </WithOptimisticAuth>
  ),
}))
// ... (other routes)

Problematic Implementation

import { ComponentType, PropsWithChildren } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from './auth-provider'

export const withOptimisticAuth =
  <P extends object>(Component: ComponentType<P>) =>
  (props: PropsWithChildren<P>) => {
    const { isAuthenticated, isLoading, isError } = useAuth()
    if (isError || (!isLoading && isAuthenticated === false)) return <Navigate to="/login" replace />
    return <Component {...props} />
  }

export const withConfirmedAuth =
  <P extends object>(Component: ComponentType<P>) =>
  (props: PropsWithChildren<P>) => {
    const { isAuthenticated, isLoading, isError } = useAuth()
    if (isLoading) return <></>
    if (isError || isAuthenticated === false) return <Navigate to="/login" replace />
    return <Component {...props} />
  }

Usage in router configuration:

const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />,
    errorElement: <ErrorPage />,
    children: Object.keys(Routes).map(route =>
      match<Route>(Routes[route as keyof typeof Routes])
        .with(Routes.Installations, () => ({
          path: Routes.Installations,
          element: withOptimisticAuth(InstallationsPage)({}),
        }))
// ... (other routes)

Error Message

When using the second implementation, I get the following error:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Question

Why does the second implementation cause an “Invalid hook call” error, while the first one works correctly? How can I fix the second implementation to work properly?

withOptimisticAuth(InstallationsPage) returns a functional component, then I render that component by calling the function withOptimisticAuth(InstallationsPage)({}).

How is it different from inlining the HOC functionality in InstallationsPage:

export function InstallationsPage() {
  const { isAuthenticated, isLoading, isError } = useAuth()
  if (isError || (!isLoading && isAuthenticated === false)) return <Navigate to="/login" replace />

And rendering the component directly:

  element: <InstallationsPage />

Which works fine, but using the HOC doesn’t work.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật