on
react HOC(고차 컴포넌트)
HOC : Higher Order Component
https://ko.reactjs.org/docs/higher-order-components.html
고차 컴포넌트
: 컴포넌트 로직을 재사용하기 위한 React의 고급 기술
React API의 일부가 아니며 react의 구성적 특성에서 나오는 패턴이다.
컴포넌트를 가져와 새 컴포넌트를 반환하는 사실상 함수이다.
인자로 컴포넌트를 받고 공통으로 사용하는 기능을 덧붙여 새 컴포넌트를 리턴해준다.
고차 컴포넌트명은 with로 시작하는 게 관행이다.
ex) functional component 사용
withLoading.jsx : HOC
2초동안 <p>Loading...</p>
을 보여주고 <Component />
를 리턴한다.
import React, { useState, useEffect } from "react";
//withLoading : HOC 함수
export default function withLoading(Component) {
// WithLoadingComponent : 함수형 컴포넌트
const WithLoadingComponent = (props) => {
const [loading, setLoading] = useState(true);
useEffect(() => {
const timer = setTimeout(() => setLoading(false), 2000);
return () => clearTimeout(timer);
}, []);
return loading ? <p>Loading...</p> : <Component />;
};
return WithLoadingComponent;
}
소문자로 시작하는 함수를 만들고(withLoading()
) 안에서 컴포넌트를 만들어(const WithLoadingComponent
) 컴포넌트로 리턴(return WithLoadingComponent
)한다.
HOC withLoading() 적용하기
Button.jsx : HOC로 뺀 공통 기능이 들어갈 컴포넌트
import React from "react";
import withLoading from "./withLoading";
function Button() {
return <button>Button</button>;
}
// HOC함수인 withLoading에 담아서 리턴
export default withLoading(Button);
Button 컴포넌트를 withLoading()
에 담아서 리턴한다.
Input.jsx : HOC로 뺀 공통 기능이 들어갈 컴포넌트
import React from "react";
import withLoading from "./withLoading";
function Input() {
return <input defaultValue="input" />;
}
// HOC함수인 withLoading에 담아서 리턴
export default withLoading(Input);
Input 컴포넌트를 withLoading()
에 담아서 리턴한다.
결과
<Button>
과 <Input>
이 렌더링이 되기전에 withLoading
로 인해서 2초동안 <p>Loading...</p>
을 보여주고 해당 컴포넌트를 리턴한다.
주의할 점
HOC 원본 컴포넌트를 수정하면 안된다.
render
메서드 안에서 사용하면 안된다.
고차 컴포넌트 안에서 ref
는 작동하지 않는다.
Discussion and feedback