Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Simple example with Preact is firing twice on useState

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!