useEffect란?
컴포넌트가 렌더링 될 때 특정 작업을 실행할 수 있도록 하는 Hook이다.
- 처음 컴포넌트가 마운트 되었을 때만, 특정 작업이 실행되도록 설정할 수 있다.
- state 또는 props 변경시, 특정 작업이 실행되도록 설정할 수 있다.
mount란?
컴포넌트가 나타나는 것을 의미한다. 따라서 마운트, 언마운트라고 칭한다.
첫번째 인자는 함수(effect), 두번째 인자는 배열(deps)이 들어간다.
[] : 처음 렌더링 시에만 실행한다. (Componentdidmount)
null : 렌더링 될 때마다 실행한다. (CompoenetUpdate)
[count] : 변수의 값이 변화할때에만 실행한다.
[keyword, count] : 두 변수 중 하나의 값만 병화해도 실행한다.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
사용목적
component가 끝날 때, 파괴될 때(언마운트) 함수를 실행하고자 사용함
import "./App.css";
import React, { useEffect, useState } from "react";
function Hello() {
useEffect(() => {
console.log("created :)");
return () => console.log("bye :("); // 해당부분
}, []);
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>
);
}
export default App;