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.
CodePudding user response:
Change:
function handleClick() {
setTheme(!theme);
}
to:
function handleClick() {
setTheme(currentTheme => !currentTheme);
}
The problem has to do with stale closures.
CodePudding user response:
Just try it:
return <button onClick={() => handleClick()}> Click me </button>;
CodePudding user response:
return <button onClick={() => handleClick()}> Click me ;