React Hooks, setTimeOut to set State to false

I have this scenario

const [showAlertLink, setShowAlertLink] = useState(false);

 const handleClick = () => {

<Button disableRipple onClick={handleClick}>

{!!showAlertLink &&  <Alert icon={<CheckIcon fontSize="inherit" />} onClose={() => setShowAlertLink(false)}>{t(`alert_link_copied`)}</Alert>}

At the moment if i click on the Icon i can close the Alert. How can i make this alert closing automatically with a SetTimeout duration 2 seconds for example?


You can use useEffect:

  useEffect(() => {
    let timeout
    if (showAlertLink) {
      timeout = setTimeout(() => setShowAlertLink(false), 2000);
    return () => clearTimeout(timeout);
  }, [showAlertLink]);

It will trigger when showAlertLink value changes. If it is true it will set a timeout to set it to false in 2 seconds (2000).

Be careful that you always return the effect to clear the timeout (to ensure you don’t get tried to update state of an unmounted component) error.

If you are using typescript, you can type timeout like so:

let timeout: ReturnType<typeof setTimeout>;