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

123
Visualizações
Set timeout for message with hooks

I have a component that after a user has clicked the button, a message appears and should disappear after 3 seconds. I'm trying to use useEffect to enable the timeout, but can't get it working:

const { useState, useEffect } = React

const SectionHeader = (props) => {
const {title, button, link, type} = props;
    const [copy, setCopy] = useState(false)
    const [showMessage, setShowMessage] = useState(true);
    
    useEffect(() => {
      setTimeout(() => {
        setShowMessage(false)
      }, 3000)
    }, [])
    const copyToClipboard = (title) => {
        navigator.clipboard.writeText(window.location.href + '#' + title.toLowerCase().replaceAll(" ", "-").replaceAll("'", ""))
        setCopy(true)
    }
    return (
        <div id={title.toLowerCase().replaceAll(" ", "-").replaceAll("'", "")}>
          <b>{title}</b>
          <div onClick={() => copyToClipboard(title)}>Copy to clipboard</div> {copy ? 'copied' : ''}
        </div>
    )
}

ReactDOM.render(<SectionHeader title="Test" />,
document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

useEffect execute the code written in its block only when the website is loaded for the first time or when the dependencies changes.

In your code you have not included any dependencies, so it'll only execute the code wrapped inside its block when the site will load for the first time.

 useEffect(() => {
      setTimeout(() => {
        setShowMessage(false)
      }, 3000)
    }, [here should be some state which changes when a button got clicked])
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