useRefの使い所

ReactのuseRefは、再レンダリングを伴わない値の保持や、DOM要素への参照に使用されます。
useStateのように値の変更で再描画が走らないため、パフォーマンス面でも重要な役割を果たします。


1. DOM要素への参照

ボタンやインプットなど、実際のHTML要素にアクセスしたい場合に使います。

import { useRef } from "react";

export const FocusInput = () => {
  const inputRef = useRef
<HTMLInputElement>(null);

  const handleClick = () => {
    inputRef.current?.focus(); // フォーカスを当てる
  };

  return (

<div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>フォーカスを当てる</button>
    </div>
  );
};
  • useRef(null) でDOM参照用のRefを作成
  • ref={inputRef} を対象のJSXタグに指定
  • inputRef.current からDOM API(focus, scrollIntoView, など)にアクセス可能

2. 値の永続保持(再描画なし)

再描画されても値を維持したいが、変更によって再レンダリングを引き起こしたくないケースで使います。

import { useRef, useState } from "react";

export const RenderCounter = () => {
  const [count, setCount] = useState(0);
  const renderCount = useRef(1);

  renderCount.current += 1;

  return (

<div>

<p>クリック回数: {count}</p>

<p>レンダリング回数: {renderCount.current}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>+1</button>
    </div>
  );
};
  • renderCountは変更しても再描画されない
  • 主にデバッグ、キャッシュ、非同期ハンドラ内での参照保持などに利用される

3. 前回の値を保持する

直前のpropsやstateの値を保存しておく用途にも便利です。

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

export const PreviousValueExample = () => {
  const [value, setValue] = useState("");
  const prevValue = useRef("");

  useEffect(() => {
    prevValue.current = value;
  }, [value]);

  return (

<div>
      <input value={value} onChange={(e) => setValue(e.target.value)} />

<p>現在の値: {value}</p>

<p>前回の値: {prevValue.current}</p>
    </div>
  );
};

まとめ

用途 特徴
DOM参照 .current で要素にアクセスできる
値の保持(再描画なし) useStateと違って更新しても再レンダリングしない
前回値の保持 useEffect内で.currentに記録
非同期内の参照保持 クロージャを避けて常に最新の値を参照できる
// 型ヒントはジェネリクスで明示するのが推奨
const ref = useRef<HTMLDivElement | null>(null);
const valueRef = useRef
<number>(0);

useRefはReactアプリ内で小さな工夫やパフォーマンスチューニングに役立つ便利なフックです。

コメントを残す 0

Your email address will not be published. Required fields are marked *