보통 HOC는 with~라는 이름으로 시작한다.
이번 글에서는 HOC를 실제로 어떻게 만들 수 있는지 그 활용법을 이야기하고자한다.
리액트 컴포넌트를 작성할 때 반복될 수 있는 코드들은 HOC를 만들어 해결해 줄 수 있다.
예를 들면, 웹 요청을 하는 로직, Lifecycle method 이용하는 로직, Redux에서 특정 값을 받아와 주입시켜주는 등의 코드 작성에서 많이 사용될 수 있다.
import React, { Component } from 'react';
import axios from 'axios';
const withRequest = (url) => (WrappedComponen) => {
return class extends Component {
state = {
data: null
}
async initialize() {
try {
const response = await axios.get(url);
this.setState({
data: response.data
});
} catch (e) {
console.log(e);
}
}
componentDidMount() {
this.initialize();
}
render() {
const { data } = this.state;
return (
<WrappedComponent {...this.props} data={data}/>
)
}
}
}
export default withRequest;
만든 HOC 사용하기
import React, { Component } from 'react';
import withRequest from './withRequest';
class Post extends Component {
render() {
const { data } = this.props;
if (!data) return null;
return (
<div>
{ JSON.stringify(this.props.data) }
</div>
);
}
}
export default withRequest('https://jsonplaceholder.typicode.com/posts/1')(Post);
response.data를 props로 넘겨주고 WithRequest함수를 사용해 해당 props를 받을 컴포넌트를 감싸주는 형태로 이용한다.