React usestate not updating on first Click Or on First time

Viewed 3651

Please, See this - https://codesandbox.io/s/morning-grass-z8qrq

https://codesandbox.io/s/blue-flower-wl92u

** the second click, third, fourth, fifth click - menuOpen is true, then again click false - behaves as expected**

let [menuOpen, setMenuOpen] = useState(false);

<div
    onClick={() => {
    // setMenuOpen(true);

    setMenuOpen(!menuOpen); // I's not updated in the First time.

    console.log(menuOpen); // First time: false // not updating
>
 .......// some code
</div>

Please give me, some answers. I have been trying to solve this problem for Two days. I just can't solve it.

5 Answers

Try this:

export default function App() {
  const [menuOpen, setMenuOpen] = useState(false);
  return (
    <>
      <button onClick={() => setMenuOpen(!menuOpen)}>Click</button>
      Is menu Open: { menuOpen ? "True": "False"}
    </>
  );
}

Example demo can be found here.

useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.

Give this a try

setMenuOpen(prevMenuOpenState => !prevMenuOpenState);

or

<div
    onClick={() => setMenuOpen(!menuOpen)}
>

I had even this problem in my code. My scenario is as follows: Its hotel detail page. There is horizontal tab menu of room types. If a hotel has more than 3 types of room, then there is show room button. I am using React Functional components in through the code. hotel detail basic page and room section page are different components created. values are passed to room section components through props.

My problem: When I click to room type further 3rd type, then show room value in function (setSelectedTab()) room component doesn't set at an instant. And hence as function moves further, it doesn't set document.getElementById(id) since show room had not been set. As function (setSelectedTab()) completes in first click it sets the show room to true, but selected tab doesn't set. I had to click 2nd time to set the tab.

solution: After a long try and error, I settle down to the following: I declare the function as async and made await the setshowRoom() value. This solved my complete problem.

async function setSelectedTab(e, data) {
firstScroll += 1;

data >= 2 && await setMenuOpen(true);
if (data >= 0) {
  .................
  const id = e.href;
  const anchor = document.getElementById(id);
  ..............
..............
}
}

and in room component: showRoom, setshowRoom in useState and calling the setSelectedTab() using props. This solves problem of single click

Drawback: I found delay of 1 second to set this tab.

If anyone have better solution than this without making async await, then please post here. Thanks.

The Answer is just refactoring the code into class Component without using hooks useState. Using state and setState to update. The Problem will solve.

But If I use useState hooks the problem remains the same Whatever I do with the code.

Related