I have a tiny Preact component where I want to toggle the visibility of a div, but it is not working as expected. The following recreates the issue:
import { h, render } from 'preact';
import { useState } from 'preact/hooks';
function App() {
const [isOpen, setIsOpen] = useState(true);
function toggle() {
console.log('toggle');
setIsOpen(!isOpen);
}
console.log(isOpen);
if (isOpen) {
return (
<div>
<div onClick={toggle}>Close</div>
</div>
);
} else {
return <div onClick={toggle}>Open</div>;
}
}
render(<App />, document.body);
But it doesn't work like I would expect. The console output is the following:
true
toggle
false
toggle
true
First two lines are from initial rendering. All of the rest happens when I click Close. I would expect Close to change to Open, and the console output to be the following when I click Close:
toggle
false
I use this to build:
esbuild ./tmp.tsx --bundle --watch --minify --outdir=./ --jsx-factory=h --jsx-fragment=Fragment
and the html is
<html>
<body>
<script async src="tmp.js"></script>
</body>
</html>
What is going on here?