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

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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