슬기로운 개발자생활/Frontend

React HoC 고차 컴포넌트에 대한 이해 (예제 포함)

개발자 소신 2024. 1. 10. 07:50
반응형

React에서 고차 컴포넌트(Higher-Order Component, HoC)는 컴포넌트를 인자로 받아 새로운 컴포넌트를 반환하는 함수입니다. HoC는 컴포넌트의 재사용성, 로직 공유, 상태 추상화, prop 조작 등에 유용합니다.

HoC의 기본적인 구조는 다음과 같습니다:

 

function withHoC(WrappedComponent) {
  // 반환되는 새로운 컴포넌트
  return function(props) {
    // 추가 로직이나 상태를 이곳에 작성
    // ...

    // WrappedComponent에 props를 전달
    return <WrappedComponent {...props} />;
  };
}



HoC 예제: 로딩 상태 관리

예를 들어, 여러 컴포넌트에서 공통적으로 사용되는 로딩 상태 관리 로직을 HoC를 사용하여 구현할 수 있습니다.

아래는 로딩 상태를 관리하는 HoC(`withLoading`)의 예시입니다:

// withLoading.js
function withLoading(WrappedComponent) {
  return function(props) {
    const { isLoading, ...otherProps } = props;

    if (isLoading) {
      return <div>Loading...</div>;
    }

    return <WrappedComponent {...otherProps} />;
  };
}

// 사용 예시
import withLoading from './withLoading';

function MyComponent({ data }) {
  return <div>{data}</div>;
}

const MyComponentWithLoading = withLoading(MyComponent);

// 사용 시
<MyComponentWithLoading isLoading={loadingState} data={data} />



이 예제에서 `withLoading` HoC는 `isLoading` prop을 기반으로 로딩 상태를 관리합니다. `isLoading`이 `true`일 경우 로딩 인디케이터를 표시하고, `false`일 경우 실제 컴포넌트(`WrappedComponent`)를 렌더링합니다.

HoC를 사용하면 기존 컴포넌트의 로직을 변경하지 않고도 추가적인 기능을 주입할 수 있습니다. 이는 React의 컴포넌트 구조를 유지하면서도 코드의 재사용성과 관리 효율성을 높일 수 있는 강력한 방법입니다.

반응형