Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

React lifeCycle

JAVASCRIPT, REACT, 20216 min read

배경

class형태로 react코드를 프로그래밍 했었다. lifeCycle을 통해서 원하는 시점에 특정 기능이 동작하도록 프로그래밍 할 수 있었다. react 코드에서 hooks를 사용하게 되면서 lifeCycle을 어떻게 쓸 수 있는지 궁금해 졌다. 지금부터는 lifeCycle에 관해서 알아보고 예제를 통해 hooks을 통해 구현해 보려고 한다.

Lifecycle methods ?

Lifecycle methods use a form of hooking that allows the execution of code at set points during a component's lifetime.

라이프사이클 메서드는 구성 요소의 수명 동안 설정된 지점에서 코드를 실행할 수 있는 후크 형식을 사용합니다.

왜 사용?

프로그래밍을 하면서 특정 시점에 코드를 수행해야 할 때 사용할 수 있습니다.

React 16.4 Life Cycle

  • life cycle은 업데이트 된다. Why need to update to new LifeCycle?

Mounting(생성)

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
  1. constructor

    생성자 메서드,컴포넌트가 만들어지면 가장 먼저 실행

    • If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.
    • You should not call setState() in the constructor().Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:
  2. render

    데이터가 변경되어 새 화면을 그려야 할 때 자동으로 호출

    • 함수형 컴포넌트는 render함수를 쓰지 않는다.
  3. componentDidMount

    • componentDidMount() is invoked immediately after a component is mounted render 함수가 JSX를 화면에 그린 후 호출
  4. getDerivedStateFromProps

    props 로 받아온 state 에 값을 넣어주고 싶을 때 사용

Updating :컴포넌트가 다시 렌더링 될 때 순차적으로 호출

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
  1. render

    render

    • render 함수는 오직 클레스 컴포넌트에서 요청된다
    • render 함수는 꺠끗하게 유지해야만 한다 그 의미는 그것은 수정하지 않는다 컴포넌트 상태를 ,그것은 반환한다 같은 결과를 그것이 호출되는 매시간 그리고 그것은 직접적으로 상호작용하지 않는다 브라우저에
    • 만약 브라우저와 상호작용이 필요하다면 수행해라 당신의 작업을 componentDidMount() 나 다른 lifecycle methods를 대신에.
    • shouldComponentUpdate()false를 반환한다면 render()는 호출되지 않을 거다
  2. componentDidUpdate

    • componentDidUpdate() is invoked immediately after updating occurs. 리렌더링을 완료한 후 실행
  3. getDerivedStateFromProps

  4. shouldComponentUpdate(nextProps,nextState)

    true나 false를 반환해 리렌더링을 결정

    1. (기존 props,state값과 달라짐) props,state가 변경 되었을때
    2. 부모 컴포넌트가 렌더링 되었을때
  5. getSnapshotBeforeUpdate

    render에서 만들어진 결과가 브라우저에 실제로 반영되기 직전에 호출

Unmounting

This method is called when a component is being removed from the DOM:
  1. componentWillUnmount

    컴포넌트가 DOM에서 제거될 때 호출


리액트 Hooks를 활용하여 라이프 사이클을 구현?

  • componentDidMount,
useEffect(() => {
console.log('componentDidMount ');
}, []);//empty array
  • componentDidUpdate
const [count, setCount] = useState(0);
useEffect(() => {
// 컴포넌트 업데이트 이후 실행
console.log('componentDidUpdate');
console.log(count);//업데이트 된 값
}, [count]);
  • componentWillUnmount

출처

출처2 출처3

lifecycle method 생명주기 함수

출생(마운트) 컴포넌트의 constructor 생성자 실행 => 생성자에서 state 를 정의하게 된다. 컴포넌트가 렌더링되며 이후에 componentDid Mount 함수 호출

다시 렌더링 = 업데이트 = props 가 변경되거나 setState 호출하여 state 변경,forceUpdate 강제 업데이트 렌더링 후에는 componentDidUpdate 호출

사망(언마운트) 상위 컴포넌트에서 현재 컴포넌트를 더 이상 화면에 표시하지 않게 될 때 언마운트된다 언마운트 직전에 componentWillUnmount 함수 호출 컴포넌트가 계속 존재하는 것이 아니라 시간의 흐름에 따라 생성되고 업데이트되다가 사라진다는 것

state

  • 직접 State를 수정하지 마세요
  • 부모 -> 자식 으로 데이터는 아래로 흐릅니다 (단방향식)
  • 컴포넌트는 자신의 state를 자식 컴포넌트에 props로 전달
© 2024 by GwiyeomGo Tech Blog. All rights reserved.