Search code examples
htmlreactjsbuttonreact-hookssettimeout

React Hooks Change Text of Button on Click and then back again


Using React Hooks I would like to change the text of my button when a user clicks it to say "Added" and then I would like to set it back to the original text "Add to Cart" after 1 second. I assume I would use setTimeout for this but am having trouble figuring out how to use it in this case.

I have this

  const [buttonText, setButtonText] = useState("Add To Cart");

and this so far.

  <button
    type="submit"
    onClick={() => setButtonText("Added")}
  >
    {buttonText}
  </button>

Solution

  • Add the timeout inside useEffect, and pass buttonText as dependency, every time the buttonText is updated, the timeout will restore the default text value:

    const text = "Add To Cart" 
    const [buttonText, setButtonText] = useState(text);
    
     useEffect(()=> {
        const timer = setTimeout(()=> {
           setButtonText(text);
        }, 1000);
        return ()=> clearTimeout(timer);
     }, [buttonText])
     
     return (<button
        type="submit"
        onClick={() => setButtonText("Added")}
      >
        {buttonText}
      </button>)
    

    Working example