Lifecycle 제어하기
Lifecycle
탄생: 화면에 나타나는 것(Mount), ex) 초기화 작업
변화: 업데이트, 리렌더(Update), ex) 예외 처리 작업
죽음: 화면에서 사라짐(UnMount), ex) 메모리 정리 작업
리엑트는 각 주기마다 사용할 수 있는 메소드를 가지고있다.
Mount: ComponentDidMount, 컴포넌트가 생기는 순간에 사용
Update: ComponentDidUpdate, 컴포넌트가 변화하는 순간에 사용
Unmount: ComponentWillUnmount, 컴포넌트가 화면에서 사라지기 이전에 사용
-React Hooks
원래 State, Effect, Ref 등은 class형 컴포넌트에서만 사용가능 하고 함수형 컴포넌트에서 못 사용하는데 use를 붙여서 낚아채서 사용한다.
하지만 class형 컴포넌트에서는 중복 콛, 가독성 문제 등이 발생해서 함수형 컴포넌트에서 사용 가능하도록 했다.
-함수형 컴포넌트에서 리엑트 Hooks를 이용해서 Lifecycle 제어하기
함수형 컴포넌트에서 Life를 제어하기 위해서는 useEffect를 사용해야한다.
useEffect
useEffect(()=>{
//todo... 콜백 함수
}, [])//Dependency Array(의존성 배열)
//Dependency Array 배열 내에 들어있는 값이 변화하면 콜백 함수가 수행된다.
useEffect는 이런식으로 사용한다.
- Mount
import React, { useEffect, useState } from "react";
const Lifecycle = () => {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
useEffect(() => {
console.log("Mount!");
}, []);
return (
<div style={{ padding: 20 }}>
<div>
{count}
<button onClick={() => setCount(count + 1)}>+</button>
</div>
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
</div>
);
};
export default Lifecycle;
Lifectcke.js를 만들고 useEffect를 활용하여 Mount를 했다. 그렇기에 버튼을 눌러도 콘솔은 찍히지 않는다.
따라서 Mount를 하고 싶으면 useEffect에 두번째 인자에 빈 배열 []을 넣고 첫번째 인자에 우리가 하고 싶은 코드를 넣어주면 된다.
- Update
useEffect(() => {
console.log("Update!");
});
컴포넌트가 업데이트 되는 경우: state가 업데이트, 부모에게서 내려받는 Props가 바뀌거나, 부모 컴포넌트가 리렌더링되면 자기 자신도 리렌더링된다.
두번째 인자를 안써주면 업데이트를 할 때 마다 콘솔에 Update!가 출력된다.
import React, { useEffect, useState } from "react";
const Lifecycle = () => {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
useEffect(() => {
console.log("Mount!");
}, []);
useEffect(() => {
console.log("Update!");
});
useEffect(() => {
console.log(`count is update : ${count}`);
if (count > 5) {
alert("count가 5를 넘었습니다. 따라서 1로 초기화합니다.");
setCount(1);
}
}, [count]);
useEffect(() => {
console.log(`text is update : ${text}`);
}, [text]);
return (
<div style={{ padding: 20 }}>
<div>
{count}
<button onClick={() => setCount(count + 1)}>+</button>
</div>
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
</div>
);
};
export default Lifecycle;
useEffect는 두번째 인자가 바뀌게 되면 앞에 있는 콜백 함수가 수행된다.
이렇게 나온다.
-count 값 제한
useEffect(() => {
console.log(`count is update : ${count}`);
if (count > 5) {
alert("count가 5를 넘었습니다. 따라서 1로 초기화합니다.");
setCount(1);
}
}, [count]);
만약 count가 5를 넘기면 안된다면 이런식으로 활용할 수 있다.
- UnMount
import React, { useEffect, useState } from "react";
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이 true일때만 UnmountTest나오게 한다. */}
{/* 따라서 단락회로평가 사용 */}
{isVisible && <UnmountTest />}
</div>
);
};
export default Lifecycle;
우선 isVisible이 true일 때, UnmountTest가 나오도록 하기 위해서 단락회로 평가를 사용한다.
그리고 UnmountTest 안에는 Moust했던 useEffect를 만든다. 그리고 return으로 Unmount를 했다고 찍어주는 기능을 만들면 Unmount 시점을 알 수 있다.