[React] 컴포넌트의 생명주기(Lifecycle)와 useEffect()

vanLan·2022년 11월 16일
0

React

목록 보기
5/11
post-thumbnail

🔑 Lifecycle(생명주기)

  • React의 각 컴포넌트는 3가지 주요 단계를 통해 주기를 관리하고 관찰할 수 있다.
  • 컴포넌트가 Mount, Update, Unmount 될 때까지를 의미한다.

🗝 Mount

  • 컴포넌트가 처음으로 렌더링 될 때를 의미한다.

  • React는 컴포넌트를 마운트 할때 순서대로 4가지 내장 메소드를 호출하게 된다.

    1. constructor()
    2. getDerivedStateFromProps()
    3. render()
    4. componentDidMount()
  • render() 메소드는 항상 호출 되어야 하며, 다른 메소드들은 선택적으로 호출 될 수 있다.

    1. constructor

    • 컴포넌트가 초기화될때 가장먼저 호출되어, state와 다른 초기값을 생성한다.

    2. getDerivedStateFromProps

    • DOM에서 요소들이 렌더링 되기 직전에 호출된다.

    3. render

    • 필수값이며, 반환되는 html을 root DOM에 표현해 준다.

    4. componentDidMount

    • 컴포넌트가 렌더링된 직후 호출된다.
    • 이미 DOM에 위치한 컴포넌트에 필요로 하는 구문을 사용하는 곳이다.

🗝 Update

  • 컴포넌트가 업데이트 될 때를 의미한다.

  • 컴포넌트의 state나 props가 변경될 때 마다 업데이트 된다.

  • React는 컴포넌트가 업데이트 되면 순서대로 5가지 내장 메소드를 호출하게 된다.

    1. getDerivedStateFromProps()
    2. shouldComponentUpdate()
    3. render()
    4. getSnapshotBeforeUpdate()
    5. componentDidUpdate()

    1. getDerivedStateFromProps

    • 컴포넌트가 업데이트 될 때 가장먼저 호출된다.
    • 초기 props에 기반한 state가 저장되는 곳이다.

    2. shouldComponentUpdate

    • React가 렌더링을 진행해야 되는지에 대한 Boolean 값을 반환한다.
    • 기본값은 true이다.

    3. render

    • 컴포넌트가 업데이트가 되면 물론 render()도 호출 된다. 변경된 값들로 리렌더링 된다.

    4. getSnapshotBeforeUpdate

    • 업데이트가 되기 전에 props와 state에 접근할 수 있다. 즉, 업데이트 이후에도 업데이트 이전의 값들을 확인할 수 있다.
    • 컴포넌트에 getSnapshotBeforeUpdate 메소드가 존재하면, componentDidUpdate() 메소드 또한 포함해야 한다. 그렇지 않을시 에러가 발생한다.

    5. componentDidUpdate

    • 컴포넌트가 DOM에 update된 후에 호출된다.

🗝 Unmount

  • 컴포넌트가 DOM에서 제거하거나 unmount 될때를 의미한다.

  • React는 unmount 될 때엔, 하나의 내장 메소드가 호출된다.

    1. componentWillUnmount()

    1. componentWillUnmount

    • 컴포넌트가 DOM에서 제거될 때 호출되는 메소드이다.

🔑 함수형 컴포넌트와 클래스형 컴포넌트

  • 제어 방식 비교

    함수형 컴포넌트클래스형 컴포넌트
    비교적 최근에 나옴리액트 초기에 나옴
    Hook 함수로 컴포넌트의 mount, unmount 되는 시점을 제어할 수 있음생명 주기에 따른 메서드에 따라 제어할 수 있음

🗝 클래스형 컴포넌트

  • 생명주기에 따른 메소드로 제어.
    export default class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = { date: new Date() };
      }
      
      // Clock 출력값이 DOM에 삽입되면, React는 componentDidMount() 생명주기 메서드를 호출
      componentDidMount() {
        console.log('componentDidMount');
        this.timerID = setInterval(() => this.tick(), 1000);
      }
      
      // setState() 호출 덕분에 React는 state가 변경된 것을 인지하고 화면에 표시될 내용을 알아내기 위해 render() 메서드를 다시 호출
      tick() {
        this.setState({
          date: new Date();
        });
      }
      
      componentDidUpdate() {
        console.log('componentDidUpdate');
        console.log(this.state.date);
      }
      
      // Clock 컴포넌트가 DOM으로부터 한 번이라도 삭제된 적이 있다면 React는 타이머를 멈추기 위해 componentWillUnmount() 생명주기 메서드를 호출
      componentWillUnmount() {
        console.log('componentWillUnmount');
        clearInterval(this.timerID);
      }
      
      render() {
        return (
          <div>
            <h1>Timer</h1>
            // this.state.date가 변경되고 렌더링 출력값은 업데이트 된 시각을 포함
            <h2>It is {this.state.date.toLocaleTimeString()}</h2>
          </div>
        );
      }
    }

🗝 함수형 컴포넌트

  • useEffect() Hook으로 제어.

    1. useEffect(() => {}, []);
      componentDidMount 처럼 동작.
    2. useEffect(() => {});
      componentDidMount + componentDidUpdate 처럼 동작.
    3. useEffect(() => {}, [state, props.a]);
      componentDidMount + 특정값 [ ]이 변경 되었을 때에만 해당하는 componentDidUpdate 처럼 동작.
    4. useEffect(() => { return () => { cleanup }}, [state, props.a]);
      componentWillUnmount 처럼 동작.
    export default function Clock() {
      const [date, setDate] = useState(new Date());
      const tick = () => {
        setDate(new Date());
      };
      
      useEffect(() => {
        // componentDidMount()와 같음.
        console.log('componentDidMount');
        const timerId = setInterval(tick, 1000);
        
        // componentWillUnmount와 같음.
        return () => {
          clearInterval(timerId);
        };
      }, []);
      
      useEffect(() => {
        // componentDidUpdate()와 같음.
        console.log('componentDidUpdate');
        console.log(date);
      }, [date]);
      
      return (
        <div>
          <h1>Hello, wolrd!</h1>
          <h2>It is {date.toLocaleTimeString()}.</h2>
        </div>
      );
    }
  • Multiple Effect 사용.

    • 관련이 있는 로직들을 모아 구조에 맞게 Multiple Effect 사용.
    • state Hook을 여러번 사용할 수 있는것 처럼 effect 또한 여러번 사용할 수 있다.
    • useEffect를 이용하여 서로 관련이 없는 로직들을 갈라 놓을 수 있다.
    • Hook을 이용하면 생명주기 메소드에 따라서가 아니라 코드가 무엇을 하는지에 따라 나눌 수 있다.
    • React는 컴포넌트에 사용된 모든 useEffect를 지정된 순서에 맞춰 적용한다.

profile
프론트엔드 개발자를 꿈꾸는 이

0개의 댓글