길용쓰 2024. 5. 13. 14:12

useEffect는 컴포넌트 렌더링 될때마다 특정 작업을 실행할 수 있게 하는 Hook이다

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

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

  useEffect(() => {
    console.log('렌더링이 완료되었습니다.');
  });
  
  useEffect(() => {
    console.log('마운트 완료되었습니다.');
  }, []);

  useEffect(() => {
    console.log(`count 상태가 ${count}로 변경되었습니다.`);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>증가</button>
    </div>
  );
}

useEffect는 실행할 함수와  함수를 실행할 조건 2가지 인자를 input으로 받는다.

 

2번째 인자가 빈배열[]이면 처음 마운트될때 한번만,

2번째 인자가 [a,b]와 같은 배열이면 a나 b의 값이 바뀔때마다 실행된다.

 

 

 

 

https://xiubindev.tistory.com/100

 

React Hooks : useEffect() 함수

useEffect 함수는 리액트 컴포넌트가 렌더링 될 때마다 특정 작업을 실행할 수 있도록 하는 Hook 이다. useEffect는 component가 mount 됐을 때, component가 unmount 됐을 때, component가 update 됐을 때, 특정 작업을

xiubindev.tistory.com

더 자세한 조건은 여기에