Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React setState not changing value

I am using react useState hook with a callback to update state.

However, the value stays at the initial value of 0.

const [currPos, setCurrPos] = useState(0);
console.log(`Current position is ${currPos}`);
// Update currPos so next keyPress is in the correct position
setCurrPos((prevState) => prevState + 1);

Logs always contain Current position is 0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code link: https://gitlab.com/mk851/wordle-clone/-/blob/main/src/App.tsx#L50

>Solution :

You will have to implement useEffect to view the changes.
You’re consoling the previous value, and useState is an asynchronous function it will go to the callback queue, meanwhile the value will be consoled, so you need to console the value whenever the currPos changes.

const [currPos, setCurrPos] = useState(0);

useEffect(() => console.log(currPos), [currPos]);

setCurrPos(prevCurrPos => prevCurrPos + 1);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading