79501127

Date: 2025-03-11 14:41:20
Score: 2
Natty:
Report link

Many React devs prefer Hooks over Higher-order Components (HoCs), and for good reasons. But sometimes, direct usage of hooks for certain logic—like authentication redirects—can clutter components and reduce readability.

Full context and examples here https://frontend-fundamentals.com/en/code/examples/login-start-page.html

Common Hook approach:

function LoginStartPage() {
  const { isLoggedIn } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (isLoggedIn) router.push('/main');
  }, [isLoggedIn, router]);

  return <Login />;
}

HoC as an alternative:

export default withLoggedOut(LoginStartPage, '/main');

Wrapper Component as another alternative:

function App() {
  return (
    <AuthGuard>
      <LoginStartPage />
    </AuthGuard>
  );
}

But here's the thing:

Many React developers strongly dislike HoCs, finding them overly abstract or cumbersome. Yet, could the issue be how we use HoCs, rather than HoCs themselves?

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Yurim Jalynne Jin