0Pricing
React Academy · Lesson

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

  1. Render Props Pattern
  2. Higher-Order Components (HOCs) Explained
  3. HOC vs Render Props vs Custom Hooks
  4. Refactoring a HOC to a Custom Hook
← Back to React Academy