Strange behavior: I expect that the first and the second console.log display a different result, but they display the same result and the value is changed only on the next c
The setState hook doesn't update the value in the component directly. It updates it's internal state, causes a rerender of the component, and then returns the new state value, which you assign to count.
When you console.log(count) inside test, you display the current value of count, which is the old value (before the update). If you'll move the console.log() to the render, you'll see the new value:
const { useState } = React;
const Component = () => {
const [count, setCount] = useState(false);
const test = () => {
console.log('before: ', count);
setCount(!count)
}
console.log('after: ', count);
return (
);
}
ReactDOM.render(
,
demo
);