Higher-Order Components — React Technical Interview Questions & Answers
Higher-Order Components
Higher-Order Components
- An HOC is a function that takes a component and returns a new component, usually injecting props: withUser(Hello) → Hello receives user. withRouter was famous. Pattern: function withX(Wrapped) { return function Wrapper(props) { return <Wrapped {...props} extra={…} />; }; }
- Hooks replaced most HOCs. withUser becomes useUser(). HOCs still appear in old code and some libraries. Mention wrapper hell (many HOCs) as the reason teams switched.
- Higher-Order Components — on screen: Asha. withUser injected user. Today a custom hook useUser() is simpler.
Parent
│ props (read-only)
▼
Child → UITechnical Interview Tip: Define HOC + say hooks replaced most.
Code Examples for Higher-Order Components
Example
// HOC
function withUser(Wrapped) {
return function WithUser(props) {
const user = { name: "Asha" };
return <Wrapped {...props} user={user} />;
};
}
function Hello({ user }) { return <p>{user.name}</p>; }
export default withUser(Hello);
Higher-Order Components — on screen: Asha. withUser injected user. Today a custom hook useUser() is simpler.
How to Explain Higher-Order Components to an Interviewer
Explain Higher-Order Components as if you are teaching a junior — definition, then one tiny UI.
(Component) => Component. custom hooks.
What does the example show on screen (or print), and what does that prove?
Higher-Order Components — on screen: Asha
What mistake do freshers make with Higher-Order Components?
HOC soup.