How-To Write a Simple Countdown with React
CP
Posted on November 3, 2020
There are tutorials for writing countdown from scratch. With momentjs, it should be a pretty simple task.
But as the name suggests, easytimer makes it easy.
First, set up the countdown variable with React useState
:
const [countdown, setCountdown] = useState(null);
Then, start the timer, and use event listeners to listen to the timer changes, update the countdown
variable.
const target = {
minutes: 1
};
const timer = new Timer();
timer.start({ countdown: true, startValues: target });
timer.addEventListener("secondsUpdated", () =>
setCountdown(timer.getTimeValues().toString())
);
The target
object accepts these keys: secondTenths, seconds, minutes, hours, days, or you can pass in an array in the exact order of [secondTenths, seconds, minutes, hours, days]
Lastly, remember to remove the listeners when component unmount.
// Remove listeners on unmount
return () => {
timer.removeEventListener("secondsUpdated");
timer.removeEventListener("targetAchieved");
};
Here's the complete source code, or you can view it on codesandbox
import React, { useState, useEffect } from "react";
import Timer from "easytimer";
import "./styles.css";
const App = () => {
const EXPIRED = "Expired";
const [countdown, setCountdown] = useState(null);
const isActive = countdown !== EXPIRED && countdown !== null;
useEffect(
() => {
const target = {
minutes: 1
};
const timer = new Timer();
timer.start({ countdown: true, startValues: target });
timer.addEventListener("secondsUpdated", () =>
setCountdown(timer.getTimeValues().toString())
);
timer.addEventListener("targetAchieved", () => setCountdown(EXPIRED));
// Remove listners on unmount
return () => {
timer.removeEventListener("secondsUpdated");
timer.removeEventListener("targetAchieved");
};
},
// Known issue with eslint warning against the run-once useEffect
// eslint-disable-next-line
[]
);
return (
<div className="App">
<h1>Countdown Demo</h1>
<h2>{isActive ? countdown : EXPIRED}</h2>
<div>(refresh to reset a 1 min countdown)</div>
</div>
);
};
export default App;
I found it a little bit confusing that there are two npm packages named easytimer: easytimer (last updated 4 years ago) and easytimer.js (last updated 4 months ago), but they both point to the same GitHub user.
Posted on November 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.