[TIL/React] 2023/06/24

์›๋ฏผ๊ด€ยท2023๋…„ 6์›” 24์ผ
0

[TIL]

๋ชฉ๋ก ๋ณด๊ธฐ
85/159

useRef ๐ŸŸข

useRef๋Š” rendering์— ํ•„์š”ํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ์ฐธ์กฐํ•  ๋•Œ ์‚ฌ์šฉ๋˜๋Š” React Hook์ด๋‹ค.

React ๊ณต์‹๋ฌธ์„œ์— ๋”ฐ๋ฅด๋ฉด, useRef Hook์€ ํฌ๊ฒŒ ์„ธ ๊ฐ€์ง€ ์ƒํ™ฉ์—์„œ ์‚ฌ์šฉ๋œ๋‹ค.

  1. Referencing a value with a ref
  2. Manipulating the DOM with a ref
  3. Avoiding recreating the ref contents

๋งŽ์€ ๋‚ด์šฉ์ด ์žˆ๊ฒ ์ง€๋งŒ, ์˜ค๋Š˜์€ ๊ณต์‹๋ฌธ์„œ์— ์žˆ๋Š” Stopwatch ์˜ˆ์ œ ์ฝ”๋“œ๋ฅผ ํ†ตํ•ด useRef๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  useState์™€ ๋น„๊ตํ•ด ๋ณด์•˜๋‹ค.

Stopwatch code ๐ŸŸก

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๋Š” ๊ฐ’์„ ์œ ์ง€ํ•˜๊ณ  ์ปดํฌ๋„ŒํŠธ์˜ ๋ Œ๋”๋ง๊ณผ ๊ด€๋ จ์ด ์—†๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋œ๋‹ค๋Š” ์ ์ด๋‹ค.

profile
Write a little every day, without hope, without despair โœ๏ธ

0๊ฐœ์˜ ๋Œ“๊ธ€