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 click. How should I edit my code so that the value will be different?
function App() {
const [count, setCount] = React.useState(false);
const test = () => {
console.log(count); //false
setCount(!count);
console.log(count); //false
};
return (
<div className="App">
<h1 onClick={test}>Hello StackOverflow</h1>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
See Question&Answers more detail:os