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

175
Vistas
State hook not changing boolean value

In the code below I am having an issue.

I was trying to implement doubleClick behaviors and the state hook for the boolean changes to trigger it. The problem is that even though handleDoubleClick function is triggered, setAllowSingleClick is not changing the value to false so anyway the handleClick function is getting triggered.

<div onClick={handleClick} onDoubleClick={handleDoubleClick}>
const CLICK_DELAY_TIME = 200;
const [allowSingleClick, setAllowSingleClick] = useState(true);
let timer = 0;

const handleClick = () => {
    timer = setTimeout(() => {
        if (allowSingleClick) {
            doSMTH1();
        }
    }, CLICK_DELAY_TIME);
};

const handleDoubleClick = () => {
    clearTimeout(timer);
    setAllowSingleClick(false);
    doSMTH();
};   
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

do not useState() on nested Callbacks. useRef() instead.

useState() itself is just a kind of hook that returns value and setter(asynchronously works).

when setTimeout() callback function is constructed, the value of allowSingleClick variable is fixed in callback function definition (this phenomenon is known as closure).

what useRef() returns itself is object: value evaluated when reference .current property.

example code

import React from "react";
import { useRef } from "react";

function App() {
  const CLICK_DELAY_TIME = 200;
  const allowSingleClickRef = useRef(true);
  const doSMTH1 = () => console.log("!!!");
  const doSMTH = () => console.log("???");
  let timer = null;

  const handleClick = () => {
    timer = setTimeout(() => {
      if (allowSingleClickRef.current) {
        doSMTH1();
      }
    }, CLICK_DELAY_TIME);
  };

  const handleDoubleClick = () => {
    clearTimeout(timer);
    allowSingleClickRef.current = false;
    doSMTH();
  };

  return (
    <div
      style={{ backgroundColor: "red", width: "100vw", height: "100vh" }}
      onClick={handleClick}
      onDoubleClick={handleDoubleClick}
    />
  );
}

export default App;

More reading: Making setInterval Declarative with React Hooks by Dan Abramov

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