[React] High-Order Components

mechaniccoder·2020년 10월 9일
0
post-thumbnail

HOC가 뭐죠?

HOC는 React API가 아닙니다. 리액트의 컴포넌트적인 특성에서부터 출현한 디자인 패턴입니다. 만약 presentational, container 디자인 패턴을 알고계시다면 HOC 패턴을 이해하는데 도움이 될겁니다.

제가 이해한 HOC패턴의 핵심은 subscription이나 로직에 해당되는 부분을 HOC로 분리시켜 많은 컴포넌트들에서 공통적으로 사용되는 로직을 하나로 모으는 것이라 생각합니다. 이를 통해 유지, 보수성이 더 향상될 것입니다.

HOC를 구현해보죠.

velopert님의 HOC에 관한 포스팅을 참고했습니다.

HOC의 네이밍은 보통 with~~~로 시작합니다. 이번 예제 코드에서는 API를 요청하는 Post Comment 컴포넌트에서 로직을 withRequest 라는 HOC로 분리시켜보죠.

Post.js

import React from "react";
import withRequest from "./HOCs/withRequest";

class Post extends React.Component {
  render() {
    const { data } = this.props;

    if (!data) return null;

    return <div>{JSON.stringify(data)}</div>;
  }
}

export default withRequest("https://jsonplaceholder.typicode.com/todos/2")(
  Post
);

Comment.js

import React from "react";
import withRequest from "./HOCs/withRequest";

class Comments extends React.Component {
  render() {
    const { data } = this.props;

    if (!data) return null;

    return <div>{JSON.stringify(data)}</div>;
  }
}

export default withRequest("https://jsonplaceholder.typicode.com/todos/1")(
  Comments
);

withRequest.js

import React from "react";
import axios from "axios";

const withRequest = (url) => (WrappedComponent) => {
  return class extends React.Component {
    state = {
      data: null
    };

    async initialize() {
      try {
        const response = await axios.get(url);

        this.setState({
          data: response.data
        });
      } catch (error) {
        console.log(error);
      }
    }

    componentDidMount() {
      this.initialize();
    }

    render() {
      const { data } = this.state;
      return <WrappedComponent {...this.props} data={data} />;
    }
  };
};

export default withRequest;

느낀점

리액트의 컴포넌트 패턴으로 커스텀 훅 그리고 presentational, container 이렇게 두 가지만 알고 있었습니다. 이번 기회를 통해 HOC에 대해서 확실하게 알 수 있는 계기가 되었고 추후 프로젝트를 통해 숙련도를 끌어올릴 생각입니다.

profile
세계 최고 수준을 향해 달려가는 개발자입니다.

0개의 댓글