Last active
August 2, 2025 13:44
-
-
Save kobitoDevelopment/18ba260acec78b8896c69d1b38474eb0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 問題のあるコード | |
| function Counter() { | |
| const [count, setCount] = useState(0); | |
| const handleClick = () => { | |
| // カウントを更新 | |
| setCount(count + 1); | |
| // すぐに新しい値を使おうとする - 期待通り動かない | |
| console.log('Current count:', count); // まだ古い値が表示される | |
| // 1回の関数実行内で複数回更新しても、最後の1回しか反映されない | |
| setCount(count + 1); | |
| setCount(count + 1); | |
| }; | |
| return ( | |
| <div> | |
| <p>Count: {count}</p> | |
| <button onClick={handleClick}>Increment</button> | |
| </div> | |
| ); | |
| } | |
| export default Counter; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect } from 'react'; | |
| // 修正されたコード | |
| function Counter() { | |
| const [count, setCount] = useState(0); | |
| const handleClick = () => { | |
| // 前の状態を基に更新する関数形式を使用 | |
| setCount(prevCount => prevCount + 1); | |
| // 複数回の更新も関数形式を使えば正しく反映される | |
| setCount(prevCount => prevCount + 1); | |
| setCount(prevCount => prevCount + 1); | |
| }; | |
| // 値の変更を確認するなら、useEffectを使う | |
| useEffect(() => { | |
| console.log('Count updated to:', count); | |
| }, [count]); | |
| return ( | |
| <div> | |
| <p>Count: {count}</p> | |
| <button onClick={handleClick}>Increment</button> | |
| </div> | |
| ); | |
| } | |
| export default Counter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment