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?

Reactの `useRef` とは?わかりやすく解説

Posted at

Reactの useRef とは?わかりやすく解説

React の useRef は、コンポーネント内で 「再レンダリングなしで値を保持する」 ためのフックです。
useState と違い、値が変わってもコンポーネントが再レンダリングされません。

主な使い方は次の3つです。

  1. DOM(HTML要素)を直接操作する
  2. 再レンダリングなしで値を更新する
  3. 前回の値を記録する

1. DOM(HTML要素)を直接操作する

通常、React では DOMを直接操作しない のが基本ですが、
useRef を使うと inputbutton などの要素を 直接触ることができます。

📌 useRefinput に自動でフォーカスを当てる

import { useRef, useEffect } from "react";

const AutoFocusInput = () => {
  const inputRef = useRef<HTMLInputElement>(null); // input要素の参照を作成

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus(); // コンポーネントが表示されたら自動でフォーカス
    }
  }, []);

  return <input ref={inputRef} type="text" placeholder="ここに入力" />;
};

export default AutoFocusInput;

ref={inputRef}input に設定すると、 inputRef.current で要素にアクセス可能!
useEffect を使って、画面表示時に focus() を実行 → input に自動でフォーカス!


2. 再レンダリングなしで値を更新する

useState で値を管理すると、変更するたびに 再レンダリング されますが、
useRef なら 値を更新してもレンダリングは発生しません。

📌 useRef でカウントを増やす(でも画面は変わらない)

import { useRef, useState } from "react";

const Counter = () => {
  const countRef = useRef(0); // useRefでカウントを管理
  const [stateCount, setStateCount] = useState(0); // useStateでもカウントを管理

  const incrementRef = () => {
    countRef.current += 1; // useRefの値を更新(でも画面は更新されない)
    console.log("useRefのカウント:", countRef.current);
  };

  const incrementState = () => {
    setStateCount((prev) => prev + 1); // useStateで更新(画面も更新される)
  };

  return (
    <div>
      <p>useRefのカウント: {countRef.current}(画面には変化なし)</p>
      <button onClick={incrementRef}>useRefでカウント</button>

      <p>useStateのカウント: {stateCount}</p>
      <button onClick={incrementState}>useStateでカウント</button>
    </div>
  );
};

export default Counter;

useState変更すると画面が更新される
useRef変更しても画面に影響しない(再レンダリングなし)


3. 前回の値を記録する

前の値を覚えておきたい!」ときにも useRef は便利です。

📌 useRef で「前回のカウント」を記録する

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

const PreviousValue = () => {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef<number | null>(null); // useRefで前のカウントを記録

  useEffect(() => {
    prevCountRef.current = count; // useEffectのタイミングで前回の値を保存
  }, [count]);

  return (
    <div>
      <p>現在のカウント: {count}</p>
      <p>前回のカウント: {prevCountRef.current}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>カウントアップ</button>
    </div>
  );
};

export default PreviousValue;

prevCountRef.current前回のカウントを記録!
useEffect を使って、 count が変わるたびに prevCountRef に保存!


useRef を使うときの注意点

⚠️ useRefcurrent を変更しても、再レンダリングは発生しない
⚠️ 画面に表示したいデータの管理には useState を使うべき
⚠️ useRef の値はコンポーネントが 再描画されても保持される(リセットされない)


useRef はどんなときに使う?

フォームの input にフォーカスを当てる
カウントやタイマーの値を再レンダリングなしで管理
前回の値を記録する
アニメーションや setInterval のIDを管理


まとめ

🔹 useRefレンダリングに影響しない値 を保持するためのフック
🔹 DOM要素 へのアクセス、前回の値を記録再レンダリングなしの値管理 に使える
🔹 useState とは違い、 値を変更しても画面は更新されない!

useRef を適切に使えば、パフォーマンスを向上 させたり、無駄な再レンダリングを防ぐ ことができます!

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?