React 16.2 Fragment 문법과 HOC 패턴 정리

Fragment 도입

React 16.2부터 <React.Fragment> 문법이 정식 지원된다. 기존에 불필요한 div 래퍼로 인해 발생하던 스타일 이슈를 해결할 수 있었다.

// Before
render() {
  return (
    <div>
      <ChildA />
      <ChildB />
    </div>
  );
}

// After
render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
    </React.Fragment>
  );
}

단축 문법 <></>도 지원하지만 Babel 설정에 따라 동작하지 않는 경우가 있어 명시적으로 React.Fragment를 사용했다.

HOC 패턴으로 인증 처리

여러 컴포넌트에서 반복되던 인증 체크 로직을 HOC로 분리했다.

function withAuth(WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      const { isAuthenticated } = this.props;
      if (!isAuthenticated) {
        this.props.history.push('/login');
      }
    }

    render() {
      const { isAuthenticated, ...rest } = this.props;
      return isAuthenticated ? <WrappedComponent {...rest} /> : null;
    }
  };
}

export default withAuth(MyPage);

문제는 여러 HOC를 중첩할 때 발생했다. withAuth, withRouter, connect를 함께 사용하니 prop drilling이 복잡해졌다. compose 유틸리티로 가독성을 개선했다.

import { compose } from 'redux';

export default compose(
  withRouter,
  connect(mapStateToProps),
  withAuth
)(MyPage);

남은 과제

HOC 패턴이 편하긴 하지만 디버깅 시 컴포넌트 트리가 복잡해지는 단점이 있다. displayName 설정으로 어느 정도 완화했지만, 더 나은 패턴이 있을지 고민 중이다.