[react] 생명주기 메서드를 사용하여 다양한 화면 크기에 대응하는 방법은 무엇인가요?

화면 크기에 따라 React 앱을 다르게 렌더링하기 위해서는 생명주기 메서드를 사용하여 화면 크기 변경 이벤트를 감지하여 동적으로 UI를 조정해야 합니다.

1. componentDidMount 메서드를 사용하여 초기 화면 크기 설정

처음에 컴포넌트가 렌더링될 때, componentDidMount 메서드 내에서 window 객체를 사용하여 현재 화면 크기를 감지하고 초기 레이아웃을 설정합니다.

class MyComponent extends React.Component {
  componentDidMount() {
    this.updateLayout();
    window.addEventListener('resize', this.updateLayout);
  }

  updateLayout() {
    // 화면 크기 변화에 따른 레이아웃 업데이트 로직
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateLayout);
  }

  render() {
    // 렌더링 로직
  }
}

2. componentDidUpdate 메서드를 사용하여 화면 크기 변화 감지

화면 크기가 변경될 때마다 UI를 업데이트하려면 componentDidUpdate 메서드 내에서 이전 화면 크기와 현재 화면 크기를 비교하여 변경을 감지하고 업데이트해야 합니다.

class MyComponent extends React.Component {
  state = {
    screenWidth: window.innerWidth,
  };

  componentDidMount() {
    window.addEventListener('resize', this.updateScreenWidth);
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.screenWidth !== prevState.screenWidth) {
      // 화면 크기가 변경될 때 수행할 로직
    }
  }

  updateScreenWidth() {
    this.setState({ screenWidth: window.innerWidth });
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateScreenWidth);
  }

  render() {
     // 렌더링 로직
  }
}

이렇게 하면 React 컴포넌트가 화면 크기 변경에 동적으로 대응할 수 있습니다.


참고 자료:

  1. React 공식 문서: 리액트 생명주기 메서드
  2. MDN 웹 문서: window 객체