Building a Simple Timer in React

Today we’ll be building a simple countdown timer in React with the following functionality:

  • Set start time
  • Alert when time runs out
  • Pause timer

Get started by using the create react app package through npm to set up your React application. Type the following into the terminal:

For more info on create-react-app go here

If you’re familiar with React you’ll know that by default the App.js component acts as the parent component for our application. It comes with a bunch of standard code when you use create-react-app, but for now let’s delete all of the unnecessary code. We also know we’ll need to use state at some point in our application to store and change the time remaining, so let’s also make App.js a class component. At this point it should look something like the following:

Now if you type ‘npm start’ into the terminal you’ll see something that looks like this pop up in your browser:

Plain and boring for now but our App is already working!

You don’t have to know every single component you’ll need before beginning to build your application, but it helps to have a general idea of the workflow. A common technique is to split your components into presentational and container components. I know for our Timer we will definitely need the following components:

  1. Timer (container )
  2. Start Button
  3. Stop Button
  4. Pause Button
  5. Number Button (0–9)

React is a process of constantly refactoring your code, and unfortunately I realized after already starting that our Timer should hold state as well. Thus I refactored Timer.js to a class component like so:

Now the app should look like this:

A GitHub repo containing the complete code can be found here

NYC based SWE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store