Building a Beginner-Friendly React Countdown Timer App with Vite – Part 3

Posted by

React Countdown Timer App with Vite | Beginner Friendly part 3

React Countdown Timer App with Vite | Beginner Friendly part 3

In this tutorial, we will continue building our countdown timer app using React and Vite. If you haven’t already, make sure to check out part 1 and part 2 to get up to speed with the project.

Adding Functionality to the Timer

Now that we have our basic timer UI in place, it’s time to add the functionality to actually start and stop the countdown. We will be using React’s state and lifecycle methods to achieve this.

            
            import React, { useState, useEffect } from 'react';

            function CountdownTimer() {
                const [time, setTime] = useState(0);
                const [isRunning, setIsRunning] = useState(false);

                useEffect(() => {
                    let intervalId;

                    if (isRunning) {
                        intervalId = setInterval(() => {
                            setTime(prevTime => prevTime - 1);
                        }, 1000);
                    } else {
                        clearInterval(intervalId);
                    }

                    return () => clearInterval(intervalId);
                }, [isRunning]);

                const startTimer = () => {
                    setIsRunning(true);
                };

                const stopTimer = () => {
                    setIsRunning(false);
                };

                return (
                    

{time}

); } export default CountdownTimer;

Conclusion

With this functionality in place, our countdown timer app is starting to take shape. We now have a fully functioning timer that can be started and stopped by the user. In the next part of the tutorial, we will look at adding some additional features such as customization options and notifications. Stay tuned!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-gv1pe5re8w
11 months ago

nice explanation