코드
import React, {useEffect, useState} from 'react';
export default function App() {
const [count, setCount] = useState(0);
const [name, setName] = useState('abc');
useEffect(() => {
console.log('componentDidMount');
return () => {
console.log('componentWillUnmount');
}
}, []);
useEffect(() => {
console.log(`componentDidUpdate [count]`);
return () => {
console.log('componentWillUpdate [count]');
}
}, [count]);
useEffect(() => {
console.log(`componentDidUpdate [name]`);
return () => {
console.log('componentWillUpdate [name]');
}
}, [name]);
return(
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count+1)}>-1</button>
<button onClick={() => setCount(count+1)}>+1</button>
<br />
<h1>{name}</h1>
<button onClick={() => setName(name+'a')}>change name</button>
</div>
)
}
배운점
- deps가 비어있을 때([]) 첫 mount와 화면이 전환되어 unmount되기 전에 cleanup이 작동한다.
- deps에 값이 있을 때([count], [name]) 첫 mount와 함께 변수가 생성되며 useEffect 함수가 작동한다.
- deps의 값들이 변화할 때 해당 deps의 cleanup이 실행되고, useEffect 함수가 작동한다.