Search code examples
javascriptreactjsreact-bootstrap

How to disappear alert after 5 seconds in React JS?


import { useState } from 'react'
    
    const Message = ({ variant, children }) => {
      const [timeOut, setTimeOut] = useState(null)
    
      setTimeout(() => {
        setTimeOut(1)
      }, 3000)
    
      return (
        timeOut !== 1 && <div className={`alert alert-${variant}`}>{children}</div>
      )
    }
    
    Message.defaultPros = {
      variant: 'info',
    }
    
    export default Message

I want to disappear this alert after 2 or 3 seconds. I used this logic it's fine and working but In my console, I'm having this warning:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Is it affecting my app or is it oka? You can give me a better idea to implement this logic.


Solution

  • You can read through the comments

    import { useState, useEffect } from 'react'
        
    const Message = ({ variant, children }) => {
      const [show, setShow] = useState(true)
    
      // On componentDidMount set the timer
      useEffect(() => {
        const timeId = setTimeout(() => {
          // After 3 seconds set the show value to false
          setShow(false)
        }, 3000)
    
        return () => {
          clearTimeout(timeId)
        }
      }, []);
    
      // If show is false the component will return null and stop here
      if (!show) {
        return null;
      }
    
      // If show is true this will be returned
      return (
        <div className={`alert alert-${variant}`}>
          {children}
        </div>
      )
    }
    
    Message.defaultPros = {
      variant: 'info',
    }
    
    export default Message;