ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Tuesday, December 13, 2022

[FIXED] How to reset setTimeout's timer at every state changes of a button?

 December 13, 2022     button, react-hooks, reactjs, settimeout   

Issue

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?


Solution

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])


Answered By - Mathew Berg
Answer Checked By - - Willingham (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix