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

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

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