useRef๋ rendering์ ํ์ํ์ง ์์ ๊ฐ
์ ์ฐธ์กฐ
ํ ๋ ์ฌ์ฉ๋๋ React Hook์ด๋ค.
React ๊ณต์๋ฌธ์์ ๋ฐ๋ฅด๋ฉด, useRef Hook์ ํฌ๊ฒ ์ธ ๊ฐ์ง ์ํฉ์์ ์ฌ์ฉ๋๋ค.
๋ง์ ๋ด์ฉ์ด ์๊ฒ ์ง๋ง, ์ค๋์ ๊ณต์๋ฌธ์์ ์๋ Stopwatch ์์ ์ฝ๋๋ฅผ ํตํด useRef๋ฅผ ์ฌ์ฉํ๊ณ useState์ ๋น๊ตํด ๋ณด์๋ค.
import { useState, useRef } from "react";
export default function Stopwatch() {
const [startTime, setStartTime] = useState(null);
const [now, setNow] = useState(null);
const intervalRef = useRef(null);
console.log("๋ ์คํ๋์ด 1");
// 2. handleStart ํจ์๊ฐ ์คํ๋จ
function handleStart() {
// 3. startTime๋ผ๋ ์ํ๋ฅผ ํ์ฌ ์๊ฐ์ผ๋ก ์
๋ฐ์ดํธ
setStartTime(Date.now());
// 4. now๋ผ๋ ์ํ๋ฅผ ํ์ฌ ์๊ฐ์ผ๋ก ์
๋ฐ์ดํธ
setNow(Date.now());
// 5. cleaerInterval์ ์ฌ์ฉํ์ฌ ์คํ๋๋ ์ธํฐ๋ฒ์ ์ค์ง, ๋จ ์ด๊ธฐ๊ฐ์ด null์ด๊ธฐ์ ์ฒซ ํด๋ฆญ์์๋ ๋ฌด์๋จ
clearInterval(intervalRef.current);
// 6. 0.01์ด๋ง๋ค now๋ฅผ ํ์ฌ ์๊ฐ์ผ๋ก ์
๋ฐ์ดํธํ๋ ์๋ก์ด ์ธํฐ๋ฒ์ ์ค์ ํจ
intervalRef.current = setInterval(() => {
setNow(Date.now());
}, 10);
}
// 12. handleStop ํจ์๊ฐ ์คํ๋จ
function handleStop() {
// 13. ์คํ ์ค์ธ ์ธํฐ๋ฒ์ clearInterval์ ์ฌ์ฉํ์ฌ ์ค์งํจ
clearInterval(intervalRef.current);
}
// 7. secondsPassed ๋ณ์๋ ๊ฒฝ๊ณผํ ์๊ฐ์ ๋ํ๋ด๋ ๋ณ์
let secondsPassed = 0;
console.log(secondsPassed);
console.log("๋ ์คํ๋์ด 2");
// 8. startTime๊ณผ now๊ฐ ์กด์ฌํ ๊ฒฝ์ฐ์๋ง ๊ฐ์ ๊ณ์ฐํจ
if (startTime != null && now != null) {
// 9. ๊ณ์ฐ์ '(now-startTIme)/1000'๋ก ๊ตฌ์ฑ๋๋ฉฐ, ๋ฐ๋ฆฌ์ด ๋จ์์ธ ์๊ฐ์ ์ด ๋จ์๋ก ๋ณํํจ
secondsPassed = (now - startTime) / 1000;
}
console.log(secondsPassed);
console.log("๋ ์คํ๋์ด 3");
return (
<>
{/* 10. ๊ณ์ฐ ๊ฒฐ๊ณผ๋ฅผ ์์์ ์ธ ์๋ฆฌ๊น์ง ๋ณด์ฌ์ค */}
<h1>Time passed: {secondsPassed.toFixed(3)}</h1>
{/* 1.Start ๋ฒํผ์ ํด๋ฆญํจ */}
<button onClick={handleStart}>Start</button>
{/* 11. Stop ๋ฒํผ์ ํด๋ฆญํจ */}
<button onClick={handleStop}>Stop</button>
</>
);
}
์ฝ๋๋ง๋ค ์ฃผ์์ผ๋ก ์ค๋ช
์ ์ฒจ๋ถํ์ง๋ง, ํต์ฌ์ ์ธ ๋ด์ฉ์ useState๋ ์ํ๋ฅผ ์
๋ฐ์ดํธ
ํ๊ณ ํด๋น ์ํ์ ๋ํ ๋ ๋๋ง
์ ๊ด๋ฆฌํ๋ ๋ฐ๋ฉด, useRef๋ ๊ฐ์ ์ ์ง
ํ๊ณ ์ปดํฌ๋ํธ์ ๋ ๋๋ง๊ณผ ๊ด๋ จ์ด ์๋ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅ
ํ๊ธฐ ์ํด ์ฌ์ฉ๋๋ค๋ ์ ์ด๋ค.