Introduction
Now that we have covered the component's basics, it's time to implement the countdown effectively. For that, we need to use a React hook called useState.
It is called within the functional component to update and consume the component state. The state represents the component's current state. The
useStatereturns a pair: the current state value and a function to update it.
Making your countdown work!
-
First, we need to import a few functions and types to continue. Inside the Countdown component, import the following:
_10//react/Countdown.tsx_10import React, { useState } from 'react'_10import { TimeSplit } from './typings/global'_10import { tick, getTwoDaysFromNow } from './utils/time'The
getTwoDaysFromNowfunction will be used to handle edge cases. This step will explain it later. -
Next step is to add the state update hook (
useState):_14//react/Countdown.tsx_14const Countdown: StorefrontFunctionComponent<CountdownProps> = ({ targetDate }) => {_14+ const [timeRemaining, setTime] = useState<TimeSplit>({_14+ hours: '00',_14+ minutes: '00',_14+ seconds: '00'_14+ })_14_14return (_14<div>_14{ targetDate }_14</div>_14)_14} -
After doing that, we'll add a default constant
targetDatefor the edge case where the prop is not defined. We'll use as a fallback a date defined as two days from the current date. This date is calculated using a util function that was previously imported from the/utilsfolder._10//react/Countdown.tsx_10const DEFAULT_TARGET_DATE = getTwoDaysFromNow() -
Now, we need to add the
tickfunction and theDEFAULT_TARGET_DATEconstant to make the countdown work:_16//react/Countdown.tsx_16const Countdown: StorefrontFunctionComponent<CountdownProps> = ({ targetDate = DEFAULT_TARGET_DATE }) => {_16const [timeRemaining, setTime] = useState<TimeSplit>({_16hours: '00',_16minutes: '00',_16seconds: '00'_16})_16_16+ tick(targetDate, setTime)_16_16return (_16<div>_16{ targetDate }_16</div>_16)_16} -
Last but not least, change the
h1so that it shows the countdown that we've created. For that, we need to use thetimeRemainingcurrent state:_17//react/Countdown.tsx_17const Countdown: StorefrontFunctionComponent<CountdownProps> = ({ targetDate = DEFAULT_TARGET_DATE }) => {_17const [timeRemaining, setTime] = useState<TimeSplit>({_17hours: '00',_17minutes: '00',_17seconds: '00'_17})_17_17tick(targetDate, setTime)_17_17return (_17<div>_17- <h1>{ targetDate }</h1>_17+ <h1>{ `${timeRemaining.hours}:${timeRemaining.minutes}:${timeRemaining.seconds}` }</h1>_17</div>_17)_17}
The countdown string formatting is in a
HH:MM:SSformat, made through anhours,minutes, andsecondssplitting.
Therefore, with these changes, we'll see a real-time update of the countdown! The result on the homepage is this:

