I am using useState
hook inside onClick
handler to change and track the focus
state. I set it to false
initially and then change it to true
and false
several times in the handler. After each change, I do console.log(focus)
and I expect it to be respective to the changes made.
function App() {
const [focus, setFocus] = useState(false);
return (
<div
className="App"
onClick={() => {
console.log(focus);
setFocus(true);
console.log(focus);
setFocus(false);
console.log(focus);
}}
>
<h1>App</h1>
</div>
);
}
In my case, in this code snippet, I expect to see in console false
, true
and then false
again, but I see all of them false
.
Why does it happen? I feel I am missing something quite fundamental here.