본문 바로가기

Framework, Library/React

React_Life Cycle

React Life Cycle

: 리액트의 각 컴포넌트는 라이프사이클을 가진다.

과정을 단순히 보면, 컴포넌트를 작성해서 화면에 UI가 그려지는 과정

ReactDom.render()

 

const App = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

컴포넌트의 생명주기

  • Mount(생성)
  • Update(업데이트)
  • Unmount(제거)

- Mount

 

- constructor

: 컴포넌트 생성자 메서드, 컴포넌트가 생성되면 가장 먼저 실행되는 메서드(this.props, this.state)에 접근 가능하고 리액트 요소 반환

 

- getDerivedStateFromProps

: props로부터 파생된 state를 가져온다. props로 받아온 것은 state에 넣어주고 싶을때 사용

 

- render

: 컴포넌트를 렌더링하는 메서드

 

- componentDidMount

컴포넌트의 첫번째 렌더링이 마치면 호출되는 메서드

이 메서드가 호출되는 시점에는 화면에 컴포넌트가 나타난 상태

const App = () => {
  useEffect(() => {
    console.log("실행됩니다.");
  });
  return (
    <div>
      <h1>Hello World</h1>
      <button>안녕</button>
    </div>
  );
};

- Update

 

- getDerivedStateFromProps

: 컴포넌트의 props나 state가 바뀌었을때도 이 메서드가 호출된다.

 

- shouldComponentUpdate

: 컴포넌트가 리렌더링 할지 말지 결정하는 메서드

 

- componentDidUpdate

: 컴포넌트가 업데이트 되고 난 후 발생

const App = () => {
  const [hello, helloState] = useState("hello");
  useEffect(() => {
    console.log(hello);
  });
  return (
    <div>
      <h1>Hello World</h1>
      <button
        onClick={() => {
          helloState("hi");
        }}
      >
        안녕
      </button>
    </div>
  );
};

- UnMount

 

- ComponentWillUnMount

: DOM에서 컴포넌트가 지워질때 실행

컴포넌트와 관련된것들을 정리하는데 사용


- useEffect

: 화면에 렌더링이 완료된 후에 수행되며 componentDidMount와 componentDidUpdate, componentWillUnmount가 합쳐진 것

useEffect(() => {}}; // 렌더링 결과가 실제 돔에 반영된 후마다 호출
useEffect(() => {}, []); // 컴포넌트가 처음 나타날때 한 번 호출
useEffect(() => {},[의존성1, 의존성2, ...]); // 조건부 effect 발생, 의존성 중 하나가 변경된다면 effect 항상 재생성

- 내용 정리 및 후기

는 별로 없고.. useEffect를 어떻게 사용하는지 알아야 한다.

다른 Hook 들은 필요에 따라 공부하면서 쓰자.

 

지금 라최몇 물어본다면,

라최오 가능.

'Framework, Library > React' 카테고리의 다른 글

React_JSX  (0) 2023.01.22
React_Router 추가  (0) 2023.01.21
React_Router 기본  (0) 2023.01.18
React_DELETE  (0) 2023.01.15
React_UPDATE  (0) 2023.01.15