0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

useRefの使い方

Posted at

useRef とは?

Reactのフックの一つで:

「**ある値を記憶するための箱(オブジェクト)**を作る」

ようなものです。


書き方(基本構文)

import { useRef } from "react";

const ref = useRef(initialValue);
  • initialValue は初期値(省略可)
  • ref.current に値が入る(変更しても再レンダリングされない)

✳️ 主な使い道 2パターン


① DOMを直接触る(主用途)

例:入力欄にボタンでフォーカスを当てたい

import { useRef } from "react";

const Example = () => {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus(); // DOMのfocus()を呼ぶ!
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="ここにフォーカス" />
      <button onClick={handleClick}>フォーカスする</button>
    </div>
  );
};

解説:

  • useRef() で作った inputRef<input ref={inputRef}> に渡すと、DOMが取得できる
  • inputRef.current にその DOM 要素(inputタグ)が入ってる
  • inputRef.current.focus() でフォーカスできる!

② 値を保持する(再レンダリングさせたくないとき)

例:前回のカウント値を保持する

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

const Example = () => {
  const [count, setCount] = useState(0);
  const prevCount = useRef(0);

  useEffect(() => {
    prevCount.current = count;
  }, [count]);

  return (
    <div>
      <p>今のカウント: {count}</p>
      <p>前のカウント: {prevCount.current}</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  );
};

解説:

  • prevCount.current に前回の count を記録
  • 値を更新しても 再レンダリングされない
  • useRef は「永続的なメモ帳」のような使い方もできる

useRef vs useState の違い

比較項目 useRef useState
値の更新で再レンダリング? ❌ されない ✅ 再レンダリングされる
DOM参照に使える? ✅ できる ❌ できない(HTMLには渡せない)
値の保持目的 ✅ 一時的・永続的どちらもOK ✅ UIに影響を与える状態を管理するため

よくある使い道まとめ

用途
DOM参照 inputRef.current.focus()
setTimeout の ID を保持 timeoutRef.current = setTimeout(...)
前回の値を覚えておく prevCount.current = count
スクロール位置・ビデオ制御など videoRef.current.play()

まとめ

  • useRef() は、DOM要素 or 値を保持するために使う
  • .current にアクセスする
  • 値が変わっても再レンダリングはされない
  • フォーカス、スクロール、前回の値保持などに便利
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?