Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda