ReactuseRef
フック
フックを使用すると、useRef
レンダリング間で値を永続化できます。
更新時に再レンダリングを引き起こさない可変値を格納するために使用できます。
DOM要素に直接アクセスするために使用できます。
再レンダリングを引き起こしません
アプリケーションがフックを使用してレンダリングする回数を数えようとするとuseState
、このフック自体が再レンダリングを引き起こすため、無限ループに陥ります。
これを回避するために、useRef
フックを使用できます。
例:
useRef
アプリケーションのレンダリングを追跡するために使用します。
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
function App() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);
useEffect(() => {
count.current = count.current + 1;
});
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h1>Render Count: {count.current}</h1>
</>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
useRef()
1つのアイテムのみを返します。と呼ばれるオブジェクトを返しますcurrent
。
初期化するときuseRef
、初期値を設定します:useRef(0)
。
これを行うようなものです:const count = {current: 0}
。を使用してカウントにアクセスできますcount.current
。
これをコンピューターで実行し、入力を入力して、アプリケーションのレンダリング数が増加することを確認します。
DOM要素へのアクセス
一般的には、ReactにすべてのDOM操作を処理させたいと考えています。
ただしuseRef
、問題なく使用できる場合もあります。
Reactではref
、要素に属性を追加して、DOMで直接アクセスできます。
例:
useRef
入力をフォーカスするために使用します。
import { useRef } from "react";
import ReactDOM from "react-dom";
function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
状態変化の追跡
useRef
フックを使用して、以前の状態値を追跡することもできます。
これはuseRef
、レンダリング間で値を永続化できるためです。
例:
useRef
以前の状態値を追跡するために使用します。
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
function App() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
今回は、、、の組み合わせを使用してuseState
、useEffect
前useRef
の状態を追跡します。
では、入力フィールドにテキストを入力して、が更新されるたびuseEffect
に現在の値を更新しています。useRef
inputValue