✍ 기록
[React.js] life-cycle 고려해서 useEffect 사용하기
yeonDev
2022. 7. 4. 14:53
클래스형 컴포넌트에서 생명 주기(life-cycle) componentDidMount, componentDidUpdate, componentWillUnmount를 사용하듯이, 함수형 컴포넌트에서 useEffect를 사용해봅시다.
1️⃣ 컴포넌트가 생성/소멸하는 모든 상황에 함수 실행하기
// 클래스형 컴포넌트
componentDidMount() {
console.log("컴포넌트 생성 될 때 실행");
}
componentWillUnmount() {
console.log("컴포넌트 사라질 때 실행");
}
// 함수형 컴포넌트
useEffect(() => {
// componentDidMount
console.log("컴포넌트 생성 될 때 실행");
// componentWillUnmount (clean up)
return () => {
console.log("컴포넌트 사라질 때 실행");
};
});
2️⃣ 특정 state 관련 컴포넌트가 생성/소멸할 때 함수 실행하기
// 클래스형 컴포넌트
// value 값이 변할 때만 함수를 실행한다.
componentDidUpdate(prevProps, prevState) {
if (prevState.value !== this.state.value) {
console.log("value 관련 컴포넌트 랜더링 될 때 실행");
}
}
// 함수형 컴포넌트
const [value, setValue] = useState(true);
useEffect(() => {
// componentDidUpdate
console.log("value 관련 컴포넌트 랜더링 될 때 실행");
}, [value]);
3️⃣ 처음 컴포넌트 생성할 때만 함수 실행하기
처음 랜더링 될 때 한 번만 함수를 실행하고 싶다면, useEffect에 빈 배열 [ ]을 넘기면 됩니다. 그러면 React는 어떠한 state나 props에 의존하지 않고, 함수를 재실행하지 않습니다.
useEffect(() => {
// Mouting
console.log("처음에만 실행");
}, []);
참고자료
Using the Effect Hook – React
A JavaScript library for building user interfaces
reactjs.org