본문 바로가기
IT/react

[React] Compound Pattern

by 내일은교양왕 2024. 2. 28.

개념

Context API 이용하여 여러 종류의 컴포넌트가 하나의 로직을 공유할 수 있게 하는 방법

렌더링 IoC를 실현 가능

HTML 태그인 <select/>, <option/> 도 compound pattern에 해당

 

사례

컴포넌트 내용은 같지만, 구성 순서를 다르게 하고 싶을 때

 - positionOrder같은 prop을 추가하고 렌더링 방식을 바꾸는 방식

 - Render Prop 패턴을 이용하는 방식

 

나중에 유사한 변경사항이 발생한다면, 위의 방식에서 로직이 추가되어 복잡도가 높아진다.

합성 컴포넌트로 구성한다면, 기존 로직을 그대로 사용할 수 있으면서 각각 구성요소별로 별개의 컴포넌트로 분리할 수 있다. 추후 UI 변경에 대해 유연하게 대응

 

export const Input: React.FC<InputHTMLAttributes<HTMLInputElement>> = function ({ value, ...others }) {
  // CounterContext를 사용하여 Counter 관련 로직을 공유
  const counterContext = useContext(CounterContext);
  const isCompounded = counterContext !== undefined;

  return <input value={isCompounded ? counterContext?.count : value} {...others} />;
};
Counter.Input = Input

function App1() {
  return (
    <div>
      <CompoundedCounter>
        <CompoundedCounter.CountButton countType="plus" />
        <CompoundedCounter.Input />
        <CompoundedCounter.CountButton countType="minus" />
      </CompoundedCounter>
    </div>
  );
}

function App2() {
  return (
    <div>
      <CompoundedCounter>
        <CompoundedCounter.CountButton countType="plus" />
        <CompoundedCounter.CountButton countType="minus" />
        <CompoundedCounter.Input />
      </CompoundedCounter>
    </div>
  );

 

장점

필요한 상태를 내부적으로 가지고 있는데 이것을 사용하는 쪽에서는 드러나지 않아 걱정 없이 사용 할 수 있다.

자식 컴포넌트들을 일일이 import할 필요 없음

 

단점

단순 prop 추가에 비해 추가적으로 context api를 사용하고 컴포넌트를 구성해야 하기에 복잡도 유발

 

 

 

 

 

See the Pen compound pattern by Daewoong Kim (@daewoong-kim) on CodePen.

 

 

 

https://patterns-dev-kr.github.io/design-patterns/compound-pattern/

 

Compound 패턴

하나의 작업을 위해 여러 컴포넌트를 만들어 역할을 분담하게 한다 - …

patterns-dev-kr.github.io

 

https://fe-developers.kakaoent.com/2022/221110-ioc-pattern/

 

이제부터 이 컴포넌트는 제 겁니다 | 카카오엔터테인먼트 FE 기술블로그

김규재(novell) 판타지 소설, 그 중에서도 사이버펑크나 아포칼립스 장르를 아주 좋아하는 개발자입니다. 언젠가는 나도 한번 글을 써보겠다는 꿈을 가지고 있으며, 현재는 카카오엔터테인먼트에

fe-developers.kakaoent.com

 

'IT > react' 카테고리의 다른 글

[React] 컴포넌트 추상화  (0) 2024.03.04
[React] Controlled Props Pattern  (0) 2024.03.01
[React] Render Prop Pattern  (0) 2024.02.26
[React] Suspense와 선언적으로 Data fetching처리  (1) 2024.02.11
[React] children 잘 활용하기  (0) 2024.02.06