React Hook - useEffect(Lifecycle)

choi seung-i·2022년 3월 22일
0

FE로그

목록 보기
6/19
post-thumbnail

Lifecycle = 생애주기

인간 : 일반적으로 시간에 흐름에 따라, 탄생부터 죽음에 이르는 순간에 따른 단계적인 과정
개발 : 프로그램의 실행과 종료

React의 Lifecycle

탄생 : 컴포넌트가 화면에 나타나는 것 (Mount) - ex) 초기화작업
변화 : 스테이트가 바뀌거나, 리렌더되는 과정 (update) - ex)예외 처리 작업
죽음 : 컴포넌트가 화면에서 사라짐 (UnMount) - ex) 메모리 정리 작업

Class형 컴포넌트를 만들 때에는 아래와같은 함수사용이 가능 (함수형 컴포넌트에서는 안됨)

Mount : ComponentDidMount
update : ComponentDidUpdate
Unmount : ComponentWillUnmount

  • state도 class형 컴포넌트에서 사용가능한 것이지만 React Hooks를 사용함으로,
    함수형 컴포넌트에서는 'use'를 앞에 붙이면서 사용 가능
    => useState, useEffect, useRef 등...

함수형 컴포넌트를 왜 쓰나 ?

class형 컴포넌트는 함수형 컴포넌트보다 복잡하고 중복코드를 많이 쓰게 됨



useEffect

  • Mount 일 때

    const [count, setCount] = useState(0)
    const [text, setText] = useState("")
    
    useEffect(() => {
        console.log("Mount!")
    },[])

    컴포넌트가 마운트 되는 시점에서만 콘솔이 찍힘
    => [ ] 뎁스를 빈배열로 놔두면 Mount단계에서만 작동됨
    => 버튼을 눌러서 count를 증가시키며 업데이트 될 때에는 Mount단계가 아니기때문에 안찍힘


  • Update 일 때

    const [count, setCount] = useState(0)
    const [text, setText] = useState("")
    
    useEffect(() => {
        console.log("Update!")
    })

    컴포넌트가 업데이트 될 때마다 콘솔이 찍힘
    => [ ] 뎁스 사용하지 않음
    => 처음 Mount될 때 같이 콘솔 찍히고, 이후 count, text가 업데이트 될 때마다 콘솔 찍힘

    const [count, setCount] = useState(0)
    const [text, setText] = useState("")
    
    useEffect(() => {
        console.log(`cont is update : ${count}`)
    },[count])

    count가 업데이트 될 때마다 콘솔이 찍힘
    => [ ] 뎁스 안에 count(업데이트되는 대상)을 넣어줌
    => 처음 Mount될 때, count가 업데이트 될 때마다 콘솔 찍힘


  • Unmount 일 때

    const UnmountTest = () => {
        useEffect(() => {
            console.log('Mount!')
            return () => {
                // Unmount 시점에 실행되게 됨
                console.log('Unmount!')
            }
        }, [])
    
        return <div>Unmount Testing Component</div>
    }
    
    const Lifecycle = () => {
        const [isVisible, setIsVisible] = useState(false)
        const toggle = () => setIsVisible(!isVisible);
    
        return <div style={{ padding: 20}}>
            <button onClick={toggle}>ON/OFF</button>
            {isVisible && <UnmountTest />}
        </div>
    }

    useEffect 안에서 return 콜백함수 를 사용하면 Unmount시점에 실행 됨

    • isVisible && <UnmountTest /> : 단락회로평가
      => isVisible이 true면 뒤에 UnmountTest까지 true인지 확인해야 하고, true라면 뒤에있는 UnmountTest가 실행됨
      => 만약 IsVisibledl false면 이미 단락회로평가가 false이기때문에 UnmountTest까지 가지도 않기에 실행되지 않음



공부하며 정리&기록하는 ._. 씅로그

profile
Front-end

0개의 댓글