2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

間違ったsetStateの使い方

Last updated at Posted at 2023-02-23

setState対になるstateを使って計算する場合function記法setCount(prev => prev + 1)で書くべきです。

理由は、setCount(count + 1)のような書き方をするとstateが変更される前に、次のsetCountが動くと変更前の値で計算してしまうためです。

下記がその例です。
setCount(count + 1)は1づつしかcountが増えませんが、setCount(prev => prev + 1)では2づつcountが増えます。

import { useState } from "react";

import "./App.css";

function App() {
  const [count, setCount] = useState(0);
  const handleAdd = () => {
    // 1づつしか増えない(間違った使い方)
    // setCount(count + 1)
    // setCount(count + 1)
    
    // 2づつ増える
    setCount(prev => prev + 1)
    setCount(prev => prev + 1)
  }


  return (
    <div className="App">
      <button onClick={handleAdd} />
      {count}
    </div>
  );
}

export default App;


codesandbox
そのため、stateを使用してsetStateをする場合は必ずfunction記法で書くようにしましょう。

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?