-5

I've made a button to change the value of a state when it is clicked. But the value of doesn't change when the button is clicked for the first time. After the first click the value does starts changing. I am learning React and I am a beginner so this might be a no brainer but can you please help me.

`

import React, { useState } from "react";

export default function Button() {
  const [theme, setTheme] = useState(false);

  function handleClick() {
    setTheme(!theme);
    console.log(theme);
  }

  return <button onClick={handleClick}> Click me </button>;
}

`

Link to sandbox where I was practicing this. https://codesandbox.io/s/button-sanbox-x4q2i2?file=/src/button.js:0-263

Thanks in Advance.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • 3
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Oct 01 '22 at 16:31
  • 1
    `useState` is asynchronous. The changes to your state will only be reflected on the next render of the component. Check the link above. – ivanatias Oct 01 '22 at 18:12

2 Answers2

-1

Change:

function handleClick() {
  setTheme(!theme);
}

to:

function handleClick() {
  setTheme(currentTheme => !currentTheme);
}

The problem has to do with stale closures.

rantao
  • 1,621
  • 4
  • 14
  • 34
  • there is nothing with stale closures. No async operations, no `useCallback` with wrong/incomplete/empty dep list. The issue is just because OP expects state variable to be updated immediately, not on the next re-render – skyboyer Oct 02 '22 at 07:08
  • I did what you asked for. Still isnt giving me the desired result – curse machina Oct 02 '22 at 08:34
-2

Just try it:

return <button onClick={() => handleClick()}> Click me </button>;
  • It doesn't works in my sandbox. Still gives the same result – curse machina Oct 01 '22 at 16:25
  • `onClick={() => handleClick()}` and `onClick={handleClick}` are equal so far `handleClick` does not expect any argument and does not return anything(although it's not like `onClick` handler would process return value, even if there was any) – skyboyer Oct 02 '22 at 07:06