고차 컴포넌트(HOC)

Jung taeWoong·2021년 5월 23일
1

React.js

목록 보기
12/19
post-thumbnail

HOC(Higher-Ordered Component)

고차(高次)
고차(Highter-order)의 의미는 '상위 차원(수준)'이다.
사전적 의미는 '생각이나 행동 따위의 수준이나 정도가 높은 것'을 말하며
수학에서는 '높은 차수(3차 이상)'을 뜻한다. (고차 방정식, 고차 부등식)

고차 함수

함수형 프로그래밍에서는 함수는 값(value)으로 취급된다.
즉, 함수에 숫자, 문자 데이터를 전달하듯 함수 또한 다른 함수에 값으로 전달할 수 있다.
마찬가지로 함수를 값으로 반환하는 것도 가능

  • 하나 이상의 함수를 인자로 전달 받는다. ((fn) => {})
  • 함수를 결과로 반환 한다. (() => fn)
/*
  React 프로그래밍(리스트 렌더링)에서 자주 사용되는 Array의 map() 메서드는 '고차 함수'
  숫자 리스트를 전달 받아 숫자 리스트를 반환
*/


const numbers = [3, 6, 9];

const otherNumbers = numbers.map(number => (number * 2) / 3);

console.log(otherNumbers); // [2, 4, 6]

고차 컴포넌트

컴포넌트 로직을 재사용하기 위한 React 고급 프로그래밍 기술

  • React API는 아니지만, React 프로그래밍에서 자주 활용된다.
  • 컴포넌트를 전달 받아 새로운 컴포넌트를 반환하는 함수
const EnhancedComponent = withHOC(Component);

/*
  withHOC => 고차 컴포넌트
  Component => 일반 컴포넌트
  EnhancedComponent => 고차 컴포넌트가 반환한 향상된 컴포넌트
*/

일반 컴포넌트가 UI(React 요소)를 반환하지만, 고차 컴포넌트는 컴포넌트를 반환한다.
HOC는 Redux connect 함수, React Router withRouter 함수, Relay createFragmentContainer 함수 등 다양한 React 라이브러리에서 일반적으로 사용된다.

export default withRouter(connect(mapStateProps, mapDispatchProps)(Counter));

/*
  withRouter => 고차 컴포넌트
  connect => 고차 컴포넌트
  Counter => 일반 컴포넌트
*/

커스텀 고차 컴포넌트

필요한 경우, 고차 컴포넌트(HOC)를 직접 만들어 사용할 수 있다.

// hoc/withLectureContext.js

import LectureContext from '../경로';

export default (Comp) => {
  return class WithLectureContext extends Component {
    static contextType = LecutreContext
    render() {
      return <Comp {...this.props} context={this.context}/>
    }
  }
}
import withLectureContext from '../hoc/withLectureContext';

class Lecturer extends Component {
  render() {
    const { lecture, context } = this.props;
    const { removeLecture } = context;

    return (
      <li className="lecturer">
        {/*...*/}
      </li>
      )
   }
}
export default withLecturerContext(Lecturer)

React Hooks를 사용하면 HOC를 쉽게 처리 할 수 있다...?
너무 어렵다........😂

profile
Front-End 😲

0개의 댓글