useRef はミュータブルなコンテナ { current: ... } を返します。これはレンダリングをまたいで保持されますが、重要な点として、それを変更しても再レンダリングは発生しません。2 つの異なる用途があります。
1. DOM ノードへのアクセス
jsx
() {
inputRef = ();
( {
inputRef..();
}, []);
;
}
再レンダリングを引き起こさずに何かを覚えておくために使います。タイマー id、prop の前回値、ライブラリのインスタンスなどです:
function Timer() {
const intervalId = useRef(null);
const start = () => {
intervalId.current = setInterval(tick, 1000); // store across renders
};
const stop = () => clearInterval(intervalId.current);
}
const countRef = useRef(0);
countRef.current++; // changes the value, but the UI does NOT update
const [count, setCount] = useState(0);
setCount(count + 1); // changes value AND re-renders
したがってルールはこうです:UI が値を反映すべきなら state を使い、単なる「裏方の」データなら ref を使う。 レンダリング中に ref.current を読み書きすることは推奨されません(エフェクトやハンドラ内で行いましょう)。ref は React のレンダリングサイクルで追跡されないためです。