
📦 HOC는 컴포넌트를 감싸서 기능을 덧붙이는 패턴
➡️ 예를 들어, “로딩 처리” 기능을 추가하는 HOC를 만들자
// withLoading.js
import React from "react";
function withLoading(Component) {
return function WrappedComponent({ isLoading, ...props }) {
if (isLoading) {
return <div>Loading...</div>;
}
return <Component {...props} />;
};
}
export default withLoading;
➡️ 사용하는 쪽
// 원본 컴포넌트
function UserList({ users }) {
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
// HOC 적용
import withLoading from "./withLoading";
const UserListWithLoading = withLoading(UserList);
// 사용
<UserListWithLoading isLoading={true} users={[]} />
설명
원본 컴포넌트: UserList (props 받아서 리스트 그림)
HOC: withLoading(UserList)
└─ (isLoading 검사)
└─ 로딩 중이면 Loading 출력
└─ 아니면 UserList(props) 호출
WrappedComponent.displayName = `WithLoading(${Component.displayName || Component.name || "Component"})`;요즘은 복잡한 HOC 대신 Custom Hook 쓰는 겨우가 많지만,
권한 인증, 라우팅 제어 등은 여전히 HOC 패턴으로 구현하는 경우도 꽤 많다.