Reactjs state variable does not update

I am trying to make a simple game of chess in react and am trying to do so in a function component utilizing react hooks. In order to move a peice the player must click the peice they want to move and then click the desired square to move it to. Below is a snippet of my board component:

const Board = () => {
    const [clicked, setClicked] = useState(false);
    const [from, setFrom] = useState("");
    const [to, setTo] = useState("");
    ...

    const clickHandler = (i, j) => {
        if (!clicked) {
            setFrom('some_value');
            setClicked(true);
            ...
        } else {
            setTo('some_value');
            ...
            setClicked(false);
        }
        console.log(from + ', ' + to);
    }
    ...

the problem arrises from the to and from state variables not being updated when I want them to. The console output ends up looking like:

, 
some_value, 
some_value, some_value

where the to and from values are only updated on the next click event even when the console.log() is after the setFrom()/setTo() calls.

I am pretty sure that useState is not the hook I want to use here, but after trying useRef and useReducer a little and running into similar situations, I am in the dark as to what the best way would be to handle this situation.



Read more here: https://stackoverflow.com/questions/68462193/reactjs-state-variable-does-not-update

Content Attribution

This content was originally published by ketchua at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: