Performance & Patterns
React Higher Order Components
A higher-order component is a function that takes a component and returns a new one with extra behaviour. It was the main pattern for sharing logic before hooks, and it still appears in libraries such as React Redux and React Router v5.
What is Higher Order Components in React?
A higher-order component is a function that takes a component and returns a new one with extra behaviour. It was the main pattern for sharing logic before hooks, and it still appears in libraries such as React Redux and React Router v5.
Higher Order Components example
function withAuth(Component) {
return function Wrapped(props) {
const { user } = useAuth();
if (!user) return <Navigate to="/login" />;
return <Component {...props} user={user} />;
};
}
const Dashboard = withAuth(DashboardPage);
// Today you would simply write:
function DashboardPage() {
const { user } = useAuth();
if (!user) return <Navigate to="/login" />;
}Key points to remember
- Always spread the original props through, or the wrapped component loses them.
- Copy the display name so React DevTools stays readable.
- Custom hooks replace almost every HOC use case with less indirection.
Common mistakes with Higher Order Components
- Applying an HOC inside render, which creates a new component type each time and remounts everything.
- Stacking four HOCs and producing a wrapper tree nobody can debug.
React Higher Order Components— Interview Questions & FAQs
Are HOCs obsolete?+
For new code, mostly — custom hooks are simpler and avoid wrapper nesting. You still need to read HOCs when working with older libraries and legacy codebases.
