Countdown Timer with useEffect
CountdownTimer component that displays a countdown timer starting from a given initial value, and stops at 0. Use the useEffect hook to update the displayed time every second.Expectations
Display the countdown timer, starting from the given initial value.
Update the timer every second using
useEffect.Stop the timer when it reaches 0.
Display the following text as the timer counts down: "Time Remaining: X"
Start the timer when the component mounts.
Stop the timer when the component unmounts.
Solution Walkthrough for Countdown Timer with useEffect
Spoiler Alert!
Don't read this unless you've already solved the problem.
Solution Explanation
timeRemaining with the initialValue prop:
We create a state variable timeRemaining using the useState hook and set its initial value to the initialValue prop.const [timeRemaining, setTimeRemaining] = useState(initialValue);
useEffect hook to update the timer every second:
We use the useEffect hook to create an interval that updates the timeRemaining state every second. timeRemaining is less than or equal to 0. If it is, we don't set the interval, effectively stopping the timer. We also return a cleanup function to clear the interval when the component unmounts or when timeRemaining changes. This ensures that there are no memory leaks or unnecessary intervals running.useEffect(() => {
if (timeRemaining <= 0) {
return;
}
const timerId = setInterval(() => {
setTimeRemaining((prevTime) => prevTime - 1);
}, 1000);
return () => {
clearInterval(timerId);
};
}, [timeRemaining]);timeRemaining:timeRemaining state variable to display the current countdown timer value in a paragraph element.<p>Time Remaining: {timeRemaining}</p>useEffect hook for managing side effects like updating a timer every second, controlling when the effect runs using the dependency array, and cleaning up intervals to prevent memory leaks. Additionally, it showcases the ability to stop the timer when it reaches a specific value (0 in this case)