4
3

はじめに

ReactでuseStateが更新されずに困ったのでこの機会に知ったことを残しておきます。
かなり初歩的な内容です。

useStateで監視している変数が更新されなかったコード

setRecordsで値を入れているが、その直後のrecordsは[]とログが出る

  const [records, setRecords] = useState([])
  const [totalValue, setTotalValue] = useState(0)
  
  const onClickRegister = () => {
    console.log(value) // valueは10
    setRecords([...records, { value }])

    console.log(records); // valueの10が入らず、[]とログが出る

    setTotalValue(records.reduce((total, value) => total + value, 0))

  }

原因

useStateの状態更新が次のレンダリングサイクルまで適用されないためrecordsが更新されない

値の状態を適切に監視するにはuseEffectを使う

  const [records, setRecords] = useState([])
  const [totalValue, setTotalValue] = useState(0)
  
  const onClickRegister = () => {
    setRecords([...records, { value }])
  }
  
  useEffect(() => {
    const newTotal = records.reduce((total, value) => total + value.time, 0)
    setTotal(newTotal)
  }, [records]) // recordsが更新されるたびにtotalValueを再計算する

おわりに

Reactの初歩の初歩な内容でしたが大事な基本なので残しておきます。
読んでいただきありがとうございました。

4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3