useEffect()의 return문
componentDidMount
직전 useEffect의 return문 출력하고, 이후 useEffect 내용이 실행된다.그 이후 리렌더 때 return문을 실행한다.
useEffect 함수의 return === 일반적인 class기반 컴포넌트의 Lifecycle에서
componentWillUnmount
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29const App = () => {
const [number, setNumber] = useState(0);
useEffect(() => {
console.log('component did mount with useEffect!');
return () => {
console.log("component will unmount");
};
}, [number]);
return (
<div>
<h2>number is {number}</h2>
<button
onClick={() => {
setNumber(number + 1);
}}
>
Increment
</button>
</div>
);
};
// 상태
var >>> number state가 1씩 증가
console >>>
component will unmount
component did mount with useEffect!
dependency array
- Giving it an empty array acts like
componentDidMount
as in, it only runs once. - Giving it no second argument acts as both
componentDidMount
andcomponentDidUpdate
, as in it runs first on mount and then on every re-render. - Giving it an array as second argument with any value inside (eg.
[variable1]
) will only execute the code inside youruseEffect
hook ONCE on mount, as well as whenever that particular variable (eg.variable1
) changes.