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

110
Vistas
Extend the timeout after each click on react

Suppose there's the following simple component. When I click on the button, the message will change to Clicked for 1 second and then goes back to -. However, when I spam the button, I want the title to be Clicked but it should go back to - after the last click of the button. Basically, I want each click to expand the timeout.

If this was a simple JS function, I would just clear the interval after each click and set another timeout. However, I'm not sure how to achieve the same result using react hooks.

import ReactDOM from 'react-dom';
import {useEffect, useState} from 'react';
import './index.css';

const Test = () => {
    const [message, setMessage] = useState("-");

    const buttonClick = () => {
        setMessage("Clicked");
    }
    useEffect(() => {
        if(message !== "-") {
            const id = setTimeout(() => {
                console.log("Running Interval");
                setMessage("-");
            }, 1000);

            return () => {
                console.log("Clearing Interval");
                clearTimeout(id);
            }
        }
    }, [message]);

    return (
        <article>
            <header>
                {message}
            </header>
            <button onClick={buttonClick}>button</button>
        </article>
    );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Put the timeout ID into a ref, and then you can call clearTimeout on it at the very beginning of the click handler.

const Test = () => {
    const [message, setMessage] = React.useState("-");
    const timeoutIdRef = React.useRef();
    const handleClick = () => {
        setMessage("Clicked");
        clearTimeout(timeoutIdRef.current);
        timeoutIdRef.current = setTimeout(() => {
            setMessage("-");
        }, 1000);
    };
    // cleanup, if desired
    // React.useEffect(() => clearTimeout(timeoutIdRef.current), []);
    return (
        <article>
            <header>
                {message}
            </header>
            <button onClick={handleClick}>button</button>
        </article>
    );
}

ReactDOM.render(<Test />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></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