From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Creating a timer using ref

Creating a timer using ref

In this session, I'll guide you through creating a timer in React using refs. We'll explore why regular variables and useState aren't suitable for this task, and discover how refs provide the perfect solution. You'll learn to build a timer with start, stop, and reset functionality, gaining a deeper understanding of refs in the process. Let's start with our basic React template. Now I am setting up the basic structure for the timer. You'll notice I've added a div with some styling to center the timer and an h1 tag to display the time. This provides a container for the timer elements. Here I am adding the initial time display within the H1 tag. It shows 00.00, which represents minutes, seconds and milliseconds, the format your timer will use. Ok, let's add the start button. We will connect the button to its corresponding function later. I am adding a handleStart function. This function will contain the logic to start your timer. For now, it's empty, but soon we'll populate it with the…

Contents