Both HOCs and custom hooks are patterns for reusing logic in React, but they solve slightly different problems.
β Higher Order Components (HOCs)
πΉ What is an HOC?
An HOC is a function that:
- Takes a component
- Returns an enhanced component
const withAuth = (WrappedComponent) => {
return function Enhanced(props) {
if (!props.isAuth) return <Login />;
return <WrappedComponent {...props} />;
};
};
π§ When Should You Use HOCs?
β You need to wrap UI behavior
β You want to inject props into a component
β You want to control rendering (show/hide components)
β Working with class components
β Implementing cross-cutting concerns
Common HOC Use Cases:
- Authentication / authorization
- Logging
- Error boundaries
- Theming
β Downsides of HOCs
- Wrapper hell
- Harder debugging
- Props collision
- Less readable JSX
β Custom Hooks
πΉ What is a Custom Hook?
A custom hook is a function that:
- Uses React hooks
- Shares logic only, not UI
function useAuth() {
const [isAuth, setIsAuth] = useState(false);
return isAuth;
}
π§ When Should You Use Custom Hooks?
β You want to reuse stateful logic
β Logic does not affect UI structure
β Functional components only
β Cleaner and simpler abstraction
β Modern React applications
Common Hook Use Cases:
- Data fetching
- Form handling
- Debouncing / throttling
- Subscriptions
π₯ Side-by-Side Comparison
| Feature | HOC | Custom Hook |
|---|---|---|
| Reuses | UI + logic | Logic only |
| Affects JSX tree | β Yes | β No |
| Works with classes | β Yes | β No |
| Readability | β Lower | β Higher |
| Nesting | High | None |
| Modern React | β Legacy | β Preferred |
π§ Rule of Thumb
If you need to wrap or modify UI, use an HOC.
If you only need to reuse logic, use a custom hook.
π― Short Interview Answer
Higher Order Components are used when you need to wrap components to add UI behavior or inject props, especially in class components.
Custom hooks are preferred in modern React when you only need to reuse stateful logic in functional components without affecting the component tree.
β One-Line Summary
HOCs change what is rendered; custom hooks change how logic is reused.