logo
logo

Countdown Timer with useEffect

Easy

Countdown Timer with useEffect

Easy
Create a
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.

Console
Submit
Solution
00:00

Solution Walkthrough for Countdown Timer with useEffect

Solution Explanation

Initialize state variable
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);
Set up the
useEffect
hook to update the timer every second: We use the
useEffect
hook to create an interval that updates the
timeRemaining
state every second.
Before setting the interval, we check if
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]);
Display the current
timeRemaining
:
We use the
timeRemaining
state variable to display the current countdown timer value in a paragraph element.
<p>Time Remaining: {timeRemaining}</p>
This solution demonstrates the key concepts of using the
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)