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を理解する

Last updated at Posted at 2024-11-30

useRefとは

useRefは、レンダー時には不要な値を参照するためのフックです。

注意点

  • ref.currentはstateと違って変更が可能で、レンダーを跨いだ情報の保存ができます
  • ref.currentを変更しても再レンダーされません
  • レンダー中にref.currentの値を読み取ったり書き込んだりするとコンポーネントの振る舞いが予測不能になります

使い方

const initialValue = 100;
const ref = useRef(initialValue);
console.log(ref.current); // 100

const countUp = () => {
  ref.current += 100;
  console.log(ref.current); // 200
};

return (
  <>
    <button onClick={countUp}>useRef</button>
      {/* 画面は再レンダリングされないため100のまま */}
      <div>{ref.current}</div> 
    </div>
  </>
);

image.png

refは、変更しても画面上の値が変わらないため、外見に影響しないデータを保持することに適しています。

DOMの操作

操作したいDOMノードのJSXのref属性にrefオブジェクトを渡すとcurrentプロパティにそのDOMノードが設定されます。
下記の例では、ボタンをクリックするとinputにフォーカスが当たります。

使い方

  const inputRef = useRef<HTMLInputElement>(null);

  const handleClick = () => {
    inputRef.current?.focus();
    console.log(inputRef.current);
  };

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={handleClick}>Click</button>
    </div>
  );

image.png

参考
useRef:https://ja.react.dev/reference/react/useRef
refでDOMを操作する:https://ja.react.dev/learn/manipulating-the-dom-with-refs

小コンポーネントを親コンポーネントに公開:
https://ja.react.dev/reference/react/forwardRef

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?