Higher-Order Components
Imagine you have a superpower and you want to share it with your friends. Higher-order components work the same way — they take a component and add extra abilities to it. HOCs are functions that wrap components and give them new powers.
Before hooks became popular, HOCs were the go-to way to share logic between components. They still work great and you will see them in many codebases.
Creating a HOC
A HOC is just a function that takes a component and returns a new component with added functionality. Think of it like a decorator that wraps a gift.
import { useState, useEffect } from 'react'
function withUserData(WrappedComponent) {
return function WithUserDataComponent(props) {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
fetch('/api/current-user')
.then(res => res.json())
.then(data => {
setUser(data)
setLoading(false)
})
}, [])
return (
)
}
}
function ProfilePage({ user, loading }) {
if (loading) return Loading profile...
return Welcome, {user.name}
}
const ProfileWithUser = withUserData(ProfilePage)
The HOC handles all the data fetching logic. Your wrapped component just receives user and loading as props. Clean separation of concerns.
Common Use Cases
HOCs shine when you need the same logic in multiple places. Authentication checks, data fetching, logging — any cross-cutting concern works well as a HOC.
function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
const [isAuthenticated, setIsAuthenticated] = useState(false)
useEffect(() => {
const token = localStorage.getItem('token')
setIsAuthenticated(!!token)
}, [])
if (!isAuthenticated) {
return Please log in to access this page
}
return
}
}
const ProtectedDashboard = withAuth(Dashboard)
const ProtectedSettings = withAuth(Settings)
Both Dashboard and Settings get authentication protection without repeating the check logic. Write once, use everywhere.
HOCs vs Hooks
Hooks like useState and useEffect largely replaced HOCs for new code. Hooks are simpler to compose and do not add extra component layers to your tree.
That said, HOCs still have their place. They work in class components, they keep concerns cleanly separated, and many popular libraries still use them. Understanding both approaches makes you a more versatile developer.
Try it Yourself →