1

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.

turisap
  • 231
  • 4
  • 13

1 Answers1

1

When you set the state, the component will be re-rendered. State changes are not synchronous in nature. Try adding a console.log below your useState line and you'll see that it gets called every time you set the focus because the entire component is re-rendered.

Zachrip
  • 3,242
  • 1
  • 17
  • 32