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

180
Views
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 answers
Answer question

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 Report
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!