본문 바로가기
Front end/React

[React] 컴포넌트 재사용성 극대화

by 더 이프 2024. 11. 23.
728x90

목차

    React 컴포넌트 재사용성 극대화하기: 효과적인 디자인 패턴 적용하기

    안녕하세요, 코드의 재사용성과 유지보수성을 중요시하는 개발자 여러분! React 애플리케이션 개발에서 컴포넌트의 재사용성을 극대화하는 것은 중요한 과제 중 하나입니다. 재사용 가능한 컴포넌트를 설계하면 코드의 중복을 줄이고, 프로젝트의 일관성을 유지하며, 개발 시간을 단축할 수 있습니다. 오늘은 React에서 컴포넌트 재사용성을 극대화하는 데 도움이 되는 몇 가지 디자인 패턴에 대해 소개하고자 합니다.


    Higher-Order Components (HOC)

    Higher-Order Components는 컴포넌트를 인수로 받아 새로운 컴포넌트를 반환하는 함수입니다. 이 패턴은 컴포넌트 간의 공통 기능을 추출하고 재사용하는 데 유용합니다.

    예제: 로그인 상태에 따라 컴포넌트를 보호하는 HOC

    function withAuthentication(WrappedComponent) {
      return class extends React.Component {
        componentDidMount() {
          if (!this.props.isLoggedIn) {
            // 로그인 페이지로 리다이렉트
          }
        }
    
        render() {
          return <WrappedComponent {...this.props} />;
        }
      };
    }
    
    // 사용 예
    const ProtectedComponent = withAuthentication(MyComponent);

     

    Render Props

    Render Props 패턴은 컴포넌트의 props를 통해 렌더링 로직을 공유하는 기술입니다. 이 패턴은 컴포넌트의 state나 로직을 여러 컴포넌트에서 활용할 수 있게 해줍니다.

    예제: 마우스 위치 추적 컴포넌트

    class MouseTracker extends React.Component {
      state = { x: 0, y: 0 };
    
      handleMouseMove = (event) => {
        this.setState({
          x: event.clientX,
          y: event.clientY
        });
      };
    
      render() {
        return (
          <div onMouseMove={this.handleMouseMove}>
            {this.props.render(this.state)}
          </div>
        );
      }
    }
    
    // 사용 예
    <MouseTracker render={({ x, y }) => (
      <h1>Mouse is at ({x}, {y})</h1>
    )} />

     

    Compound Components

    Compound Components 패턴은 관련된 컴포넌트들을 함께 그룹화하여 각 컴포넌트가 공유 상태를 사용할 수 있게 합니다. 이 패턴은 복잡한 컴포넌트 간의 명확한 커뮤니케이션을 제공합니다.

    예제: 탭 컴포넌트 구현

    class Tabs extends React.Component {
      state = { activeIndex: 0 };
    
      selectTabIndex = (index) => {
        this.setState({ activeIndex: index });
      };
    
      render() {
        const { children } = this.props;
        const { activeIndex } = this.state;
        return (
          <div>
            {React.Children.map(children, (child, index) =>
              React.cloneElement(child, {
                isActive: index === activeIndex,
                onActivate: () => this.selectTabIndex(index)
              })
            )}
          </div>
        );
      }
    }
    
    function Tab({ isActive, onActivate, children }) {
      return <div onClick={onActivate}>{isActive ? children : null}</div>;
    }
    
    // 사용 예
    <Tabs>
      <Tab>Tab 1 Content</Tab>
      <Tab>Tab 2 Content</Tab>
    </Tabs>

     

    마무리하며...

    React에서 컴포넌트의 재사용성을 극대화하는 것은 애플리케이션의 확장성과 유지보수성을 보장합니다. 위에서 소개한 디자인 패턴들은 컴포넌트를 더욱 유연하고 관리하기 쉽게 만들어 줄 것입니다. 이러한 패턴들을 적절히 활용하여, 보다 효율적이고 강력한 React 애플리케이션을 구축해 보세요!


    Reference:

     

    Higher-Order Components – React

    A JavaScript library for building user interfaces

    legacy.reactjs.org

     

     

    React Patterns

    Get the latest React patterns, tips, and tricks right to your inbox. Contents # Translations # These translations are not verified and links are not endorsements. Chinese Element # Elements are anything inside angle brackets. Components return Elements. Co

    reactpatterns.com