-
[React] 컴포넌트의 Lifecycle [useEffect에대한 고찰 2] 컴포넌트야 인생 원래 그런거야Java Script & Type Script 2023. 3. 18. 01:24728x90
컴포넌트가 페이지에 장착된다 (mount)
컴포넌트가 업데이트된다 (update)
컴포넌트가 삭제된다 (unmount)
class Detail2 extends React.Component { componentDidMount(){ //마운트될 때 실행할 코드 } componentDidUpdate(){ //업뎃될 때 실행할 코드 } componentWillunmount(){ //언마운트 될 때 실행할 코드 } }
옛날방식의 코드.
function Detail(props){ useEffect(()=> { //여기 적는 코드는 mount, update될 때 실행됨 }) }
그리고 useEffect를 이용한 mz방식 ㅋ.ㅋ
useEffect안에있는 코드는 html렌더링 후 동작한다. -> 효율적인 동작. html을 먼저 보여주고 어려운 작업 수행. 빠른 렌더링. 시간 오래걸리는 코드를 useEffect내부에 적으면 좋음. 어려운 연산, 서버에서 데이터 가져오는 작업, 타이머 장착, 등을 많이 이용.
의존성배열 dependency를 추가하면 마운트될 때 + 그 변수가 변할 때만 실행됨.
dependency를 비워둔다 -> 최초 마운트될 때만 한번 실행되고 업데이트될 떄는 실행되지 않음.useEffect 동작 전에 실행되는 clean up function
return ()-> {}function App() { const [a, setA] = useState(true); useEffect(() => { const timer = setTimeout(() => setA(false), 3000); return () => { clearTimeout(timer); //타이머 제거하는 함수 }; }, []); return <div>{a && <Popup>3초 내 구매하면 완쁠완 혜택!</Popup>}</div>;
서버로 데이터 요청할 때도 useEffect많이 쓰는데, 요청하기 전에 한번 싹 밀고 하기 위해선
return ()=> {
//기존데이터요청은 제거해주세요
}이런식으로 많이 한다고 함.
cleanup 함수는 useEffect 에 대한 뒷정리를 해준다고 이해하시면 되는데요, deps 가 비어있는 경우에는 컴포넌트가 사라질 때 cleanup 함수가 호출됩니다.728x90'Java Script & Type Script' 카테고리의 다른 글
[React] 리덕스 초기 세팅, 리듀서만들기 복습 (0) 2023.03.21 43. Ajax- Axios, Promise.all, fetch함수 복습하기 (0) 2023.03.18 [React] Styled component props 문법 (0) 2023.03.17 39. [after final project] Gnims 개선 - 리액트 framer-motion 라이브러리로 애니메이션효과 넣기 (0) 2023.03.16 36.깃헙액션 배포용 환경변수파일 생성하기 env 깃헙액션 시크릿활용하기 (0) 2023.03.14