■P125

────────────────
const ref = useRef(initialValue);
────────────────

────────────────
const ref = useRef(0);
console.log(ref.current); // 0
────────────────

────────────────
ref.current = 1;
────────────────


■P126

────────────────
import { useRef, useState } from "react";
import sampleVideo from "./assets/sample.mp4";

const VideoPlayer = () => {
  // video要素を保存するrefを用意
  const videoRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);

  const handlePlayToggle = () => {
    if (videoRef.current) {
      // refの値に入っているvideo要素を操作
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying((prev) => !prev);
    }
  };

  return (
    <div>
      {/* ref属性に渡す */}
      <video ref={videoRef} width="320">
        <source src={sampleVideo} type="video/mp4" />
      </video>
      <button onClick={handlePlayToggle}>
        {isPlaying ? "一時停止" : "再生"}
      </button>
    </div>
  );
};

export default VideoPlayer;
────────────────


■P127

────────────────
<video ref={videoRef} />
────────────────

────────────────
if (isPlaying) {
  ref.current.pause();
} else {
  ref.current.play();
}
────────────────


■P128

────────────────
import { useRef, useState } from "react";

const Timer = () => {
  const timerRef = useRef(null);
  const [seconds, setSeconds] = useState(0);

  const handleStart = () => {
    if (timerRef.current === null) {
      // タイマーIDをrefに保存
      timerRef.current = setInterval(() => {
        setSeconds((prev) => prev + 1);
      }, 1000);
    }
  };
  const handleStop = () => {
    if (timerRef.current !== null) {
      // refに保存されたタイマーIDを使ってタイマーを停止
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  return (
    <div>
      <p>経過秒数: {seconds}</p>
      <button onClick={handleStart}>タイマー開始</button>
      <button onClick={handleStop}>タイマー停止</button>
    </div>
  );
};

export default Timer;
────────────────

