useEffect
useEffect?๐
let count = 0;
function greetWithSideEffect(name) {
// Input
count = count + 1; // Side Effect!
return `${name}๋ ์๋
ํ์ธ์!`; // Output
}
function greetWithSideEffect({ name }) {
// Input
// Bad!
document.title = `${name}๋ ์๋
ํ์ธ์!`; // Side Effect
return <div>{`${name}๋ ์๋
ํ์ธ์!`}</div>; // Output
}
import { useEffect } from "react"
// ์ฌ์ฉ๋ฒ
useEffect( ์คํ์ํฌ ๋์, [ ํ์ด๋ฐ ] )
document.addEventListener("ํ์ด๋ฐ", ์คํ์ํฌ ๋์) // ์ถ์ํ ํ ์์
// ๋งค ๋ ๋๋ง๋ง๋ค Side Effect๊ฐ ์คํ๋์ด์ผ ํ๋ ๊ฒฝ์ฐ
useEffect(() => {
// Side Effect
})
// Side Effect๊ฐ ์ฒซ ๋ฒ์งธ ๋ ๋๋ง ์ดํ ํ๋ฒ ์คํ ๋๊ณ ,
// ์ดํ ํน์ ๊ฐ์ ์
๋ฐ์ดํธ๋ฅผ ๊ฐ์งํ์ ๋๋ง๋ค ์คํ๋์ด์ผ ํ๋ ๊ฒฝ์ฐ
useEffect(() => {
// Side Effect
}, [value])
// Side Effect๊ฐ ์ฒซ ๋ฒ์งธ ๋ ๋๋ง ์ดํ ํ๋ฒ ์คํ ๋๊ณ ,
// ์ดํ ์ด๋ค ๊ฐ์ ์
๋ฐ์ดํธ๋ ๊ฐ์งํ์ง ์๋๋ก ํด์ผ ํ๋ ๊ฒฝ์ฐ
useEffect(() => {
// Side Effect
}, [])
useEffect(() => {
function handleScroll() {
console.log(window.scrollY);
}
document.addEventListener("scroll", handleScroll);
return () => {
document.removeEventLisnter("scroll", handleScroll);
};
}, []);
return๊ฐ์ ์ด๋ฒคํธ๋ฅผ ์ง์์ฃผ๋ ๋ก์ง์ ์์ฑํจ์ผ๋ก์จ ํ์ด์ง๋ฅผ ์ด๋ํ ๋(component๊ฐ unmount๋ ๋)
์ด๋ฒคํธ๊ฐ ์ ๋ฆฌ๋์ด ์ฑ๋ฅ์ ํ๋ฅผ ๋ง์ ์ ์์.
const App = () => {
const [count, setCount] = useState(0);
console.log("render", count);
useEffect(() => {
console.log("useEffect Callback", count);
return () => {
console.log("cleanUp", count);
});
}, [count]);
return <div onClick={() => setCount(count + 1)}>ํ์</div>;
};
export default Foo;
render, 0
useEffect Callback, 0
// ํด๋ฆญ
render, 1
cleanUp, 0
useEffect Callback, 1