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

Viewed 4500

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>
5 Answers

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

Let's use useEffect:

useEffect(() => {
  const timeout = window.setTimeout(() => {
    setButtonText("Add To Cart")
  }, 1000)

  return () => window.clearTimeout(timeoutID )
}, [buttonText])

Just change the onClick handler to this

onClick={
setButtonText("Added");
setTimeout(() => setButtonText("Add to Cart"), 1000)
}
Related