Refactoring a HOC to a Custom Hook
Convert a withAuth HOC into a useAuth hook step-by-step.
Welcome
In this lesson you will refactor a withAuth HOC into a useAuth custom hook step-by-step, seeing exactly why the hook version is cleaner and easier to test.
The withAuth HOC (Starting Point)
The HOC takes a component, checks if the user is authenticated, and redirects to /login if not. It injects the user as a prop.
function withAuth(Component) {
return function AuthGuard(props) {
const { user, loading } = useAuthState();
if (loading) return <Spinner />;
if (!user) return <Navigate to="/login" />;
return <Component {...props} user={user} />;
};
}
const ProtectedPage = withAuth(MyPage);All lessons in this course
- Render Props Pattern
- Higher-Order Components (HOCs) Explained
- HOC vs Render Props vs Custom Hooks
- Refactoring a HOC to a Custom Hook