This week I went back to basics to touch upon using hooks by building a stopwatch with react. I think this is a nice little project that can be tackled down in just a few hours and it is a good way to practice React hooks. With this stopwatch, you can start the time stop the time and reset. Let’s get started and look at the code.
We are going to remove all of the files in the src folder except for App.css, App.js and index.js and remove all the imports. We will be using the state and effect hooks. This is what our initial component will look like.
Great so now we have to display our time. We are going to start by displaying the milliseconds. Let’s start by building our useEffect. First our interval will be defined and if start is true the timer will start, otherwise we will clear interval. In useEffect’s second argument we are going to pass in an array with start. This means that our effect will run when start state changes. We will also add a return statement for cleanup. Finally we will have a button that will start the time once it is clicked. This is what that will look like.
Now our time will start counting up. As of now there is no way to stop or reset the stopwatch. We also need to format what is displayed so that the number’s look correctly. There is a nice trick to doing this. First we will divide the time by 10 because that is the value of a millisecond then modulo 1000. Now we will append this to a zero so that when the time starts there will be a zero already instead of just one digit. Finally we will slice and pass in a parameter of -2 so that when the number becomes two digits the zero will be removed. This is what that will look like.
Now the number displayed will make more sense. Finally what we need to do is show the seconds, minutes and create the stop and reset buttons. Creating the minutes and seconds is really similar to what we did with the milliseconds. We can copy and paste and make some changes. Instead of using module by 1000 we will do it by 60. Another thing we will have to do is round the numbers down since the decimal numbers will be displayed if we leave it as is. The buttons are also really similar to the one that we have already. For example we will set the start state to false in the stop button. For the reset button we will set the time to 0 and also set start to false. This is what our finished stopwatch will look like.
This is a nice way to practice some fundamentals like hooks. These same techniques can be used to create other similar projects like a timer or clock. It was super fun building this and it didn’t take that long to do. Hope you have as much fun as I did. Happy coding! 😎
Top comments (0)