♻️
【React】Stateの値が最新になっていない問題を考える
発生事象
前提
- field内のvalueをstateとして管理している.
フォームへの入力を,テキストの変更が止まってからx秒後に保存する.といった自動保存のための出
バウンス処理を実装したところ,保存内容が最新のものの前のものになってしまうエラーが発生した.
デモ
コード
import React, { useRef, useState } from 'react'
import Confetti from 'js-confetti'
import './style.css'
const App = () => {
const [stateText,setText]=useState("")
const ref=useRef(0)
const handleChangeText=(argText)=>{
setText(argText)
console.log(`1: ${stateText}`)
if (ref.current) {clearTimeout(ref.current)}
ref.current=setTimeout(() => {
console.log(`2: ${stateText}`)
},1000)
}
return (
<div>
<input onChange={(e)=>handleChangeText(e.target.value)} value={stateText}></input>
</div>
)
}
export default App
原因
以下のドキュメントにある通りです.
Reactの中にはstateを跨いで残存するような変数,処理がある.具体的には以下のようなもの
- ReactのRef
- JS標準APIの色々
- ブラウザ,OSリソース
- setTimeout,setIntervalのタイマーID←今回のケース
- window.xxx
- addEventListenerしたものなど
(あくまでReactのstate,再レンダーはReact内部の仕組みなので,ブラウザ,JS標準APIなどの機能は異なるレンダーを跨いで残存することが多いと理解しています.)
今回のデバウンス処理の実装では,useRef,setTimeoutを使用した
最新から一つ前のstateを用いて宣言された関数は,stateの更新後も維持される場合がある.
実装方法は以下を参考にした.
解決方法
イベントハンドラの中の処理時点では,setStateを使用しても,stateの状態は即時更新されない.
具体的にstate更新に伴う再レンダリングは,stateを参照しているイベントハンドラ等の関数が終了し,JS内部の実行コンテキストがからになったタイミングである.
したがって,この問題を解決するためには,stateとは別の値(定数を宣言する)を使用することでこの問題を回避できる.

修正後コード
import React, { useRef, useState } from 'react'
import Confetti from 'js-confetti'
import './style.css'
const App = () => {
const [stateText,setText]=useState("")
const ref=useRef(0)
const handleChangeText=(argText)=>{
const updatedText=argText // 変数を宣言する
setText(updatedText)
if (ref.current) {clearTimeout(ref.current)}
ref.current=setTimeout(() => {
console.log(`state ${stateText}`) // hello worl
console.log(`const ${updatedText}`) // hello world
},1000)
}
return (
<div>
<input onChange={(e)=>handleChangeText(e.target.value)} value={stateText}></input>
</div>
)
}
export default App
参考
Discussion