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

122
Vistas
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 Respuestas
Responde la pregunta

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