React 정리하기(3) - useEffect(Hook)

Rotti_Kim·2022년 12월 28일
0

React 공부

목록 보기
4/4
post-thumbnail

useEffect란?

컴포넌트가 렌더링 될 때 특정 작업을 실행할 수 있도록 하는 Hook이다.

  • 처음 컴포넌트가 마운트 되었을 때만, 특정 작업이 실행되도록 설정할 수 있다.
  • state 또는 props 변경시, 특정 작업이 실행되도록 설정할 수 있다.

mount란?

컴포넌트가 나타나는 것을 의미한다. 따라서 마운트, 언마운트라고 칭한다.

useEffect 사용법

첫번째 인자는 함수(effect), 두번째 인자는 배열(deps)이 들어간다.

  1. effect
  • 렌더링 이후 실행할 함수 (리액트는 해당 함수를 기억 후 , DOM 업데이트 후에 다시 불러낸다.)
  1. deps
  • [] : 처음 렌더링 시에만 실행한다. (Componentdidmount)

  • null : 렌더링 될 때마다 실행한다. (CompoenetUpdate)

  • [count] : 변수의 값이 변화할때에만 실행한다.

  • [keyword, count] : 두 변수 중 하나의 값만 병화해도 실행한다.

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  1. clean-up 함수 (ComponentWillUmount)
  • 사용목적

    component가 끝날 때, 파괴될 때(언마운트) 함수를 실행하고자 사용함

import "./App.css";
import React, { useEffect, useState } from "react";

function Hello() {
  useEffect(() => {
    console.log("created :)");
    return () => console.log("bye :("); // 해당부분
  }, []);
  return <h1>hello</h1>;
}

function App() {
  const [showing, setShowing] = useState(false);
  const onClick = () => setShowing((prev) => !prev);
  return (
    <div>
      {showing ? <Hello /> : null}
      <button onClick={onClick}>{showing ? "Hide" : "Show"}</button>
    </div>
  );
}

export default App;

추가적으로 알아야할 것들

  1. 상태주기 함수(마운트, 언마운트)
  2. clean up 하지 않을 시, 발생하는 메모리 누수
profile
세상의 문제를 기술적으로 해결하는 공학자

0개의 댓글