Home > Mobile >  How to reset setTimeout's timer at every state changes of a button?
How to reset setTimeout's timer at every state changes of a button?

Time:12-08

My first ever task last part in React :

  • Not clicking the button for three seconds changes the button text to Click me!.
import React, {useState, useEffect} from "react";

const TestButton = () => {
    const initialText = "Click me!"
    const changedText = "You clicked me!"
    const lastText = "Stop clicking me!"
    const [buttonText, setButtonText] = useState("Click me!")
    const onClick = () => {
        if (buttonText === initialText) {
            setButtonText(changedText)
        }
        if (buttonText === changedText) {
            setButtonText(lastText)
        }
    }
    useEffect(()=>{
        if(buttonText !== initialText){
            setTimeout(()=> setButtonText(initialText), [3000])
        }
    },[buttonText])
    
    return (
        <button
            type="button"
            className={"btn btn-primary"}
            onClick={onClick}
        >{buttonText}
        </button>);
};

export default TestButton;

I want to give 3 seconds to the user at each state-change. Is it possible to reset setTimeout or any other solution?

CodePudding user response:

You can return a function in useEffect so that when it's done (before it runs a second time) it can clear your timer:

   useEffect(()=>{
        let timer;
        if(buttonText !== initialText){
            timer = setTimeout(()=> setButtonText(initialText), [3000])
        }
        return () => {
            if(timer){ clearTimeout(timer); }
        }
    },[buttonText])
  • Related