클래스 컴포넌트의 this는 불변값이 아니다.

함수형 컴포넌트와 클래스, 어떤 차이가 존재할까?

0. 클래스 컴포넌트의 this는 불변값이 아니다.

class ProfilePage extends React.Component {
  showMessage = () => {
    alert('Followed ' + this.props.user);
  };

  handleClick = () => {
    setTimeout(this.showMessage, 3000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

function ProfilePage(props) {
  const showMessage = () => {
    alert('Followed ' + props.user);
  };

  const handleClick = () => {
    setTimeout(showMessage, 3000);
  };

  return (
    <button onClick={handleClick}>Follow</button>
  );
}
  1. 리액트에서 props는 불변값(immutable)이라 함수형 컴포넌트의 props는 고정된다.

  2. 요청이 진행되고 있는 상황에서 클래스 컴포넌트가 다시 렌더링 된다면, this.props는 바뀐다.

  3. 해결책

    1. this.props를 조금 더 일찍 부르고 timeout 함수에게 미리 저장해 놓은 값을 전달.
    class ProfilePage extends React.Component {
      showMessage = (user) => {
        alert('Followed ' + user);
      };
    
      handleClick = () => {
        const {user} = this.props;
        setTimeout(() => this.showMessage(user), 3000);
      };
    
      render() {
        return <button onClick={this.handleClick}>Follow</button>;
      }
    }
    

    → 하지만, 코드의 복잡성이 증가하며 버그가 생기기 쉬운 구조가 된다.

    1. 특정 render에서 props와 state를 클로저로 감싸준다
    class ProfilePage extends React.Component {
      render() {
        // props의 값을 고정!
        const props = this.props;
    
        // Note: 여긴 *render 안에* 존재하는 곳이다!
        // 클래스의 메서드가 아닌 render의 메서드
        const showMessage = () => {
          alert('Followed ' + props.user);
        };
    
        const handleClick = () => {
          setTimeout(showMessage, 3000);
        };
    
        return <button onClick={handleClick}>Follow</button>;
      }
    }
    
  4. 함수형 컴포넌트에서 특정 render에 종속되지 않은 가장 최근의 state나 props를 읽는 방법(나중에 render될 값을 미리 가져와서 쓰려면?)

    1. useRef
    2. useEffect
    unction MessageThread() {
      const [message, setMessage] = useState('');
    
      // 최신값을 쫓아간다
      const latestMessage = useRef('');
      useEffect(() => {
        latestMessage.current = message;
      });
    
      const showMessage = () => {
        alert('You said: ' + latestMessage.current);
      };
    

    [React] class 컴포넌트 vs 함수 컴포넌트 내부구조 들여다보기 + hook

1. 클래스 컴포넌트와 함수형 컴포넌트의 차이점

가. this


  1. 메서드를 사용 할 때, this가 어디에 바인딩 되어있는지 의식해야 한다.
  2. setTimeout으로 콜백함수가 호출될 때, this가 변경된 다면, 초기 렌더링 되었던 this가 아닌 변경된 this가 반영된다.
  3. this를 활용해 실시간으로 변경되는 내용을 반영한 렌더링이 가능 할 수도 있을 것 같다.

나. HOOK


  1. HOOK을 쓰는 방식이 아닌 React.Component로부터 메서드를 상속받아 사용한다.
  2. HOC를 통해 HOOK처럼 여러 기능들을 합성해서 사용 할 수 있으나, HOC의 깊이가 깊어 질 수록 wrapper지옥? 과 같이 복잡한 구조를 띄게 될 것 같다.
  3. 리덕스 또한 connect HOC를 통해 컴포넌트와 reducer를 결합하여 사용해야 한다.

다. extends를 통한 prototype 상속


  1. prototype을 상속함으로서, 코드의 재사용성을 높일 수 있다.
  2. 하지만 함수형 컴포넌트를 합성하는 방법으로 상속의 이점을 살릴 수 있지 않을까.

To-Do: 라이프 사이클 조사