createRef と useRef の違い
たまに ref を扱うときがあるのですが、毎回『あれ、どっち使えば良いんだっけ…』となっているので、備忘録がてら。
結論
結論から書くと、
- class 内で使用する場合は createRef
- FC 内で使用する場合は useRef
となるようです。
根拠
同じ疑問を持っている人も多いみたいで、Stack Overflow に同様の質問が上がっています。
What's the difference between useRef
and createRef
?
で、答えとしては、
The difference is that createRef will always create a new ref. In a class-based component, you would typically put the ref in an instance property during construction (e.g. this.input = createRef()). You don't have this option in a function component. useRef takes care of returning the same ref each time as on the initial rendering.
↓ Google 翻訳
違いは、createRef は常に新しい ref を作成することです。 クラスベースのコンポーネントでは、通常、構築中にインスタンスプロパティに ref を配置します(例:this.input = createRef())。 関数コンポーネントにはこのオプションはありません。 useRef は、最初のレンダリング時と同じ ref を毎回返します。
とのことで、なるほどなぁ。
なので、Hooks を使う以上は、useRef のみを扱えば良さそうです。