์ปดํฌ๋ํธ์ ์์ ์ฃผ๊ธฐ ์ ์ฒด์ ๊ฑธ์ณ์ ์ ์ง๋๋ ๊ฐ์ฒด.
์ํ(state)๊ฐ ๋ณ๊ฒฝ๋๋ฉด ํด๋น ์ปดํฌ๋ํธ์ ํ์ ์ปดํฌ๋ํธ๋ฅผ ๋ค์ ๋ ๋๋งํ์ง๋ง,
๋ ํผ๋ฐ์ค ๊ฐ์ฒด์ ํ์ฌ ๊ฐ(current)์ด ๋ฐ๋๋๋ผ๋ ๋ ๋๋ง์ ์ํฅ์ ์ฃผ์ง ์๋๋ค.
Closure โ ๋ณ์๋ฅผ capture, bind๋ฅผ ๊น๋นกํ๋ ๋ฌธ์ ๊ฐ ์ข
์ข
์ผ์ด๋จ.
import { useEffect, useRef, useState } from "react";
function Timer() {
useEffect(()=>{
const savedTitle = document.title;
const id = setInterval(()=>{
document.title = `Now: ${new Date().getTime()}`;
},2000)
return () => {
clearInterval(id)
document.title = savedTitle // ์ ์ฅํด๋ title๋ก ์๋ณตํด์ค๋ค.
// ๊ฒฐ๋ก ์ ์ผ๋ก useEffect์ return์ ๋๋ ๋์ ๋ํ ์ฒ๋ฆฌ์ด๋ค.
}
})
return <p>Playing</p>
}
export default function TimerControl() {
// const ref = {
// value: 1,
// }
// ref.value = 2
// ์ด๋ฐ ref๋ฅผ ๋ง๋ค๊ณ
// const๋ก ๋ง๋ ref ์ง๋ง ref.value์ ๊ฐ์ ๋ณ๊ฒฝ ๊ฐ๋ฅํ๋ค. ์ด๋ฐ ๊ฐ๋
.
// ๊ฐ์ ๋ค๋ฅธ ์ปดํฌ๋ํธ๋ค์ด ์์ ๋ค๋ง์ ์ด๋ฐ ๊ฐ์ฒด๋ฅผ ๊ฐ๊ณ ์ถ์ด -> useRef
const ref = useRef(1)
// useState๋ ์ํ๊ฐ ๋ณ๊ฒฝ๋๋ฉด ํด๋น ์ปดํฌ๋ํธ์ ํ์ ์ปดํฌ๋ํธ๋ฅผ ๋ค์ ๋ ๋๋งํจ.
// useRef๋ ref.current ๊ฐ์ด ๋ณํด๋ ๋ฆฌ๋ ๋ ์ํจ.
// ๋ค๋ฅธ ์ด์ ๋ก ๋ ๋๋ ๋๋ง ๋ฐ์๋จ.
const [playing, setPlaying] = useState(false)
const handleClick = () => {
ref.current += 1
// setPlaying(!playing)
}
console.log(ref.current,'ss')
return (
<div>
{/* {playing ?(
<Timer />
): (
<p>Stop</p>
) } */}
<button type="button" onClick={handleClick}>
Toggle
</button>
<button type="button" onClick={()=>console.log(ref.current)}>see ref</button>
<p>{ref.current}</p>
</div>
)
}