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?