概要
React について、わからないことがあるので質問します。
Function Component に、状態変数を持たせて、コンポーネントのマウント時に初期化を行いたいのですが、どのように書けばよいでしょうか。
他の言語でいう「クラスのメンバ変数をコンストラクタで初期化する」みたいなことをしたいです。
問題
以下の例では、レンダリングに影響しない変数のため、useRef で値を定義して、new Sample()
と初期化しました。
しかし、コンポーネントのレンダリングが必要となるタイミング (例えば、setSate()
で state
変数を更新した場合) で const ref = useRef(new Sample())
が実行され、Sample
オブジェクトのインスタンスがレンダリングのたびに作成されてしまいます。
変数 ref
の値自体はリファレンス記載の通り、一番最初に初期化されたときの値が保持されているのですが、レンダリングのたびに new Sample()
が実行され、Sample インスタンスが作成されてしまいます。
useRef のリファレンスの説明
initialValuecurrent: ref オブジェクトのプロパティに最初に設定する値。任意の型の値を指定できます。この引数は、最初のレンダリングの後は無視されます。
下記を実現するには、どうすればよいでしょうか
- オブジェクト型の状態変数を持たせたい
- 値の初期化はコンポーネントがマウントされた際の一度のみ (
new Sample()
で初期化されるのは一度のみ)
js
1import React, { useRef, useState } from "react"; 2 3class Sample { 4 constructor(date) { 5 console.log(`Sample constructor called. time: ${date.toLocaleString()}`); 6 this.date = date; 7 } 8} 9 10function App() { 11 const ref = useRef(new Sample(new Date())); 12 const [state, setState] = useState(0); 13 14 const updateState = () => { 15 setState(state + 1); 16 console.log(`ref.current.date: ${ref.current.date.toLocaleString()}`); 17 }; 18 19 return ( 20 <div> 21 <button onClick={updateState}>更新</button> 22 </div> 23 ); 24} 25 26export default App; 27
何回か更新ボタンをクリックした場合の出力
Sample constructor called. time: 2024/1/24 17:40:55 App.js:16 ref.current.date: 2024/1/24 17:40:55 App.js:5 Sample constructor called. time: 2024/1/24 17:40:56 App.js:16 ref.current.date: 2024/1/24 17:40:55 App.js:5 Sample constructor called. time: 2024/1/24 17:40:58 App.js:16 ref.current.date: 2024/1/24 17:40:55 App.js:5 Sample constructor called. time: 2024/1/24 17:40:59 App.js:16 ref.current.date: 2024/1/24 17:40:55 App.js:5 Sample constructor called. time: 2024/1/24 17:40:59 App.js:16 ref.current.date: 2024/1/24 17:40:55 App.js:5

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。