masalibの日記

システム開発、運用と猫の写真ブログです

React hooksの入門(useRef)

React hooksのuseRefについて勉強した。

useRefとは

DOMノードへの参照を保持することができます 使う場合はcurrentを指定する事で値を引っ張る事ができます 一番簡単な例

const countRef = useRef(0)
console.log(countRef)
// { current: 0 }
console.log(countRef.current)
// 0

例1:レンダリングの回数をカウントして表示させる場合

useStateでやった場合

import React ,{useState,useEffect} from "react";
export default function App() {
  const [rerenderCount, setRerenderCount] = useState(0);
  useEffect(() => {
    setRerenderCount(prevCount => prevCount + 1);
  });
  return (
    <div>[rerenderCount]</div>
    );
}

f:id:masalib:20201112225847g:plain

永久に再描画(レンダリング)しています。

useRefでやった場合

import React, {  useEffect ,useRef} from "react";
export default function App() {
  const rerenderCount = useRef(1)
  useEffect(() => {
    rerenderCount.current = rerenderCount.current + 1;
  });
  return <div>rerenderCount:{rerenderCount.current}</div>;
}

f:id:masalib:20201112225745p:plain

refの値を設定すると再レンダリングが発生するため、refの例では1回しかレンダリングされません。

例2:フォーカス移動と前の値の参照

クリックすると展開されます(長文なので注意)

import React, { useState, useEffect, useRef } from "react";
export default function App() {
  //フォーカス
  const inputRef = useRef(null);
  const focusInput = () => {
    inputRef.current.focus();
  };
  const inputRef2 = useRef(null);
  const focusInput2 = () => {
    inputRef2.current.focus();
  };

  //カウント系
  const [count, setCount] = useState(0);
  const rerenderCount = useRef(1);
  const countup = () => {
    //setCount((prevCount) => prevCount + 1);
    setCount(prevCountRef.current + 1);
  };
  const prevCountRef = useRef(0);

  useEffect(() => {
    //レンダリングカウント
    rerenderCount.current = rerenderCount.current + 1;

    //1つ前の値
    prevCountRef.current = count;
  });
  return (
    <>
      <div>rerenderCount:{rerenderCount.current}</div>
      <div>Count:{count}</div>
      <div>before: {prevCountRef.current}</div>
      <button onClick={countup}>count up</button>
      <div>
        <input ref={inputRef} />
        <button onClick={focusInput}>Focus Input</button>
      </div>
      <div>
        <input ref={inputRef2} />
        <button onClick={focusInput2}>Focus Input2</button>
      </div>
    </>
  );
}

フォーカス1のボタンを押すとinputの1にフォーカスがいきます。
フォーカス2のボタンを押すとinputの2にフォーカスがいきます。
このようにフォーカスをしたい場合にも使えます
カウントを押した時に前の値の保持などでも使えます

感想

ReactのRefは、DOM要素に直接アクセスして操作するのに非常に便利です。 ページ制御の情報をもってレンダリングを制御できるかも・・・・

参考URL

https://yukinaka.me/react-useref
https://blog.webdevsimplified.com/2020-05/use-ref/