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.
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);