컴포넌트가 렌더링 될 때 특정 작업을 실행할 수 있도록 하는 Hook
import { useState, useEffect } from "react"
const App = () => {
const [count, setCount] = useState(0)
const plusOne = () => {
setCount(count + 1)
}
// 렌더링 될때마다 console.log가 실행됨
useEffect(() => {
console.log("실행", count)
})
return (
<>
<button onClick={plusOne}>
+
</button>
</>
)
}
export default App
import { useState, useEffect } from "react"
const App = () => {
const [count, setCount] = useState(0)
const plusOne = () => {
setCount(count + 1)
}
// 콘솔에 실행 0 이 찍히고 이후로 count가 변해도 찍히지 않음
useEffect(() => {
console.log("실행", count)
},[])
return (
<>
<button onClick={plusOne}>
+
</button>
</>
)
}
export default App
import { useState, useEffect } from "react"
const App = () => {
const [count, setCount] = useState(0)
const plusOne = () => {
setCount(count + 1)
}
// 최초 마운트 될 때 실행 되고, count가 바뀔때마다 실행됨
useEffect(() => {
console.log("실행", count)
},[count])
return (
<>
<button onClick={plusOne}>
+
</button>
</>
)
}
export default App
import { useState, useEffect } from "react"
const App = () => {
const [count, setCount] = useState(0)
const plusOne = () => {
setCount(count + 1)
}
// 페이지가 언마운트 되면 실행됨
useEffect(() => {
return () => {
console.log("언마운트")
}
},[])
return (
<>
<button onClick={plusOne}>
+
</button>
</>
)
}
export default App
import { useState, useEffect } from "react"
const App = () => {
const [count, setCount] = useState(0)
const plusOne = () => {
setCount(count + 1)
}
// count가 업데이트 되기 직전에 실행됨
// 버튼을 눌러서 count가 1이 되면 콘솔에 변화감지 0 실행 1 순서로 찍힘
useEffect(() => {
console.log("실행", count);
return () => {
console.log("변화감지", count)
}
},[count])
return (
<>
<button onClick={plusOne}>
+
</button>
</>
)
}
export default App
import { useEffect } from "react"
const App = () => {
let count = 0
const plusOne = () => {
count += 1
console.log("실행", count)
}
/*
가변변수일때는 변화를 감지하지 못함 count는 계속 늘어나지만
렌더링이 되지않아 useEffect는 실행되지않음
언마운트 될때는 count가 정상적으로 들어감 빈배열과 같은 효과
*/
useEffect(() => {
console.log("실행", count)
return () => {
console.log("변화감지", count)
}
},[count])
return (
<>
<button onClick={plusOne}>
+
</button>
</>
)
}
export default App