I have been testing the change of states to be able to depend on them and calculate others but I have several results depending on the implementation, and there is one in particular that I do not know or have no idea of what is happening or why it gives that result, pay attention to the console.log()
case: 1
const [state, setState] = useState({count: 0});
const handleCount = () => {
console.log(state); // prints {count: 0}
setState(prevState => {
prevState.count = prevState.count + 1;
return prevState;
});
console.log(state); // prints {count: 1}
}
useEffect(() => {
console.log('has changed.. ' + state.count)
}, [state]); // in this case this doesn't show any changes, so isn't renders anything, I need to render this value
// in render
<Button onClick={() => handleCount()}>
Click {state.count}
</Button>
case: 2
const handleCount = () => {
console.log(state); // prints {count: 0}
setStateV(prevState => ({...prevState, count: prevState.count + 1}));
console.log(state); // prints {count: 0}
}
useEffect(() => {
console.log('has changed.. ' + state.count)
}, [state]); // it show that changed, but I cant depend on this because it haven't changed when I needed it
case: 3
const [state, setState] = useState(0);
const handleCount = () => {
console.log(state); // prints 0
setState(state => state + 1);
console.log(state); // prints 0 it supposed to be 1!
}
I have read this but not worked at all
So, I need help to understand what is going on please...