React
[React] clean up function
Meaning_
2022. 5. 2. 08:00
728x90
반응형
component가 destroy 될때도 코드를 실행시킬 수 있는데, 이런걸 clean up function이라고 한다. component가 destroy할때 함수를 실행시키면서 뭔가 할 수 있도록 해준다. 이것을 통해 component가 언제 create 됐는지 언제 destroy 됐는지 알 수 있다.
show 버튼을 누르면
hide로 버튼이 바뀌면서 Hello가 뜨고 다시 이 hide버튼을 누르면 show버튼만 남게 코드를 구현해볼 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
function Hello(){
useEffect(()=>{
console.log("created ");
return ()=> console.log("destroyed");
},[]);
return <h1>Hello</h1>;
}
function App() {
const [showing,setShowing] =useState(false);
const onClick=()=>setShowing(prev=>!prev);
return(
<div>
{showing? <Hello/>:null}
<button onClick={onClick}>{showing ?"Hide" :"Show"}</button>
</div>
);
}
|
cs |
사용자가 button을 클릭하면 onClick 이벤트가 실행되면서 false였던 showing의 변수를 true로 바꿔주고 버튼안에 text도 hide로 바뀐다.
{showing ? <Hello/>:null} 을 보면 showing이 true일 때 <Hello>컴포넌트가 실행된다.
이 Hello 컴포넌트가 중요한데 useEffect함수를 사용해서 Hello가 호출되면 "created"가 콘솔 로그 되고
destroy, 즉 리턴할때는 "destroyed"가 호출된다 ( 왜냐면 이 useEffect는 dependency가 빈 [] 이기 때문에 그냥 한번만 호출되는 것이다!)
그래서 create되고 destroy되는걸 useEffect가 아닌 함수로 구현해보면
1
2
3
4
5
6
7
8
9
10
11
12
|
function Hello(){
function byeFn(){
console.log("destroyed");
}
function hiFn(){
console.log("created");
return byeFn;
}
return <h1>Hello</h1>;
}
|
cs |
728x90
반응형