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">
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])