반응형

주의: 이 글은 삽질기입니다...

HOC(Higher-Order Component)란?

컴포넌트를 구현하면서 공통된 로직을 재사용해야할 때가 있다. 

보통 공통 로직은 hook으로 처리하면 되지만, error boundary같은 wrapper component나 로깅을 구현해야할때가 있는데

 

js의 고차함수 개념을 활용한 HOC 개념을 사용하면 wrapper component를 쉽게 구현할 수 있다.

(보통 HOC는 class component에서 많이 사용하는데 함수 컴포넌트에서도 사용 가능하다.)

 

import { Component } from "react";

function withLogging(WrappedComponent) {
  return class extends Component {
    componentDidMount() {
      console.log(`Component ${WrappedComponent.name} is mounted.`);
    }

    componentDidUpdate() {
      console.log(`Component ${WrappedComponent.name} is updated.`);
    }

    componentWillUnmount() {
      console.log(`Component ${WrappedComponent.name} is unmounted.`);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}

const App = () => {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
};

export default withLogging(App);

(위 코드는 hoc component 예시)

 

고차함수는 React.memo나 mobx의 observer등 여러 라이브러리에서 유용하게 사용되고 있다.

HOC의 개념을 몰라도 리엑트를 사용하다보면 몇번은 사용해봤을 것이다.

 

decorator?

 

그런데 어디서 유사한걸 많이 봤지 않았나?

java의 spring이나 nest, typeORM 등에도 리엑트의 HOC와 비슷한 역할을 하는 함수가 있다. 

@Get('users')
@Auth('admin')
findAllUsers() {}

바로 decorator이다. 즉, HOC는 디자인패턴의 데코레이터 패턴과 유사한 기능을 한다고 생각하면 될듯하다.

 

나는 HOC를 js(혹은 ts)의 decorator로 대체할 수 있는 방법을 찾고 싶었고, 

@withLogging
const app = () => {
  ...
}

 

이 글의 주제를 HOC를 함수 컴포넌트의 decorator로 변환하는 법으로 쓰고 싶었는데

현재 2023년 05월 기준으론 js(ts)에서는 decorator는 클래스형 컴포넌트(object)에만 사용이 가능한것으로 판명났다.

 

즉, 내가 원했던것의 반대로 decorator가 HOC로 대체 된듯하다.. 원하는걸 하고 싶으면 고차함수를 쓰라는 것 같다.

 

ㅠㅜ

 

비록 함수 컴포넌트에는 쓰지 못하지만 만약 일급 컬렉션 객체나 repository pattern for api를 class형으로 사용할 경우 decorator는 사용해볼만 한것 같다..! 

 

ref 

 

https://ko.legacy.reactjs.org/docs/higher-order-components.html

 

고차 컴포넌트 – React

A JavaScript library for building user interfaces

ko.legacy.reactjs.org

https://www.typescriptlang.org/ko/docs/handbook/decorators.html

 

Documentation - Decorators

TypeScript Decorators overview

www.typescriptlang.org

 

반응형

+ Recent posts