I have a simple react component. It has a state, and if the state is true is logs something to the console. The component also renders a button with a handler to toggle the state.
However, some really unexpected behavior is happening. When I click the button, the state is true
logs twice. If I click the button again, it logs twice again. But on the third click onwards, it doesn't log anything anymore. The button was clicked
inside the click handler logs each time.
I am having a similar issue in my chrome environment as well. There, the state is true
only logs once per click, but again after two clicks it doesn't log anymore.
Does anyone know why the console.log
runs twice per click, as well as why it only works up to two times? I would expect the component to re-render each time and then run the console log each time as the state is always true.
https://codesandbox.io/s/blissful-jepsen-luo8ce?file=/src/App.js:0-360
export default function App() {
const [isShown, setShown] = React.useState(false);
if (isShown) {
console.log("the state is true");
}
return (
<button
onClick={() => {
console.log("button was clicked");
setShown(true);
}}
>
Click Me!
</button>
);
}
I tried search online but could not find any answers, help is appreciated!