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

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

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