🌟 https://ko.reactjs.org/docs/higher-order-components.html
HOC (High Order Component, 고차 컴포넌트)
- 비슷한 역할인 Hook 등장하며 사용빈도 하락
- component의 logic을 재사용할 수 있는 기술(리액트 외에서도 사용)
HOC = function(컴포넌트){ return 새로운컴포넌트; }
- 컴포넌트는 props 받아 UI 리턴, HOC는 컴포넌트 받아 새 컴포넌트 리턴
+) 이전에 props 전달 위해 사용한 withRouter 역시 HOC (with 붙은 함수가 HOC인 경우가 많음)
1. 사용법
- Cross-Cutting Concerns(횡단 관심사; 특정 시점에 비슷한 일을 하는 것드르이 모임) 위해 사용
- Original Component 변경하지 않고 Composition 사용할 것
- 전달받은 props(unrelated props) 오염하지 말 것
- 새로만드는 component에 쉬운 이름 지어줄 것
2. 주의점
- render 함수 안에서 사용하지 않기
- 인자로 받은 static methos는 따로 복사하기
-> hoistNonReactStatic 함수 사용 or static method를 따로 export해 사용
import hoistNonReactStatic from 'hoist-non-react-statics';
function enhance(WrappedComponent){
class Enhance extends React.Component { }
hoistNonReactStatic(Enhance, WrapperComponent);
return Enhance;
}
- Ref는 통과 불가능 ->
React.forwardRef()
사용