Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
Function firing twice on click in React component

TL/DR: My simple toggle function fires twice when button is clicked.

I'm using useEffect in a React (w/ Next.js) component so that I can target the :root <html> tag for which I need the class to be toggled. The code is the following:

useEffect(() => {
   const toggleMode = () => {
      const root = document.documentElement;
          
      root.classList.toggle("dark");
      console.log("click");
   };

const toggleBtn = document.querySelector("#toggle-btn");

toggleBtn.addEventListener("click", toggleMode);

I have the necessary imports, the code is placed inside the main component function before the return, and there's no errors in the console at all.

The only issue is that the function is fired twice every time the button is clicked and I cannot find any reason why or solutions online.

Would really appreciate your help and please let me know if I'm missing any information.

Cheers!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I resolved a similar problem in this post: Why does my NextJS Code run multiple times, and how can this be avoided?

Your code should only run once if you disable react strict mode.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your problem is coming from registering the event listener in a non-react way.

By registering the listener via

const toggleBtn = document.querySelector("#toggle-btn");

toggleBtn.addEventListener("click", toggleMode);

you are setting up a new listener each time the function is run, even if the DOM is not updated. This could result in multiple listeners being registered and firing simultaneously.

You need to add your listener the react way.

function Component ( props ){
  const [ isFirst, setIsFirst ] = useState( true );
  const [ toggle, setToggle ] = useState( false );
  useEffect(() => {
    if( isFirst ) {
      setIsFirst( false );
      return;
    }

    document.documentElement.classList.toggle("dark");
  }, [ toggle ] );

  return <div>
    <button id="toggle-btn" onClick = { e => setToggle( !toggle ) } />
  </div>
}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda