After doing that, we'll add a default constant targetDate for the edge case where the prop is not defined. We'll use as fallback a date that is defined as two days from the current date, this date is calculated on an util function that was previously imported from the /utils folder.
Creating the countdown block feature
Introduction
Now we covered the component's basics, it's time to implement the countdown effectively. For that, we need to use a React hook called
useState
.The
useState
hookIt is called within the functional component to update and consume the component state. The state represents the component's current state.
Seeing the example provided on the previous step we can understand these concepts:
In the above code piece, you might observe three things:
count
variables, it's possible to get the current state;setCount
is a function used for updating it;0
is its initial state;Activity
First, we need to import a few functions and types to continue. Inside the Countdown component, import the following:
Next step is to add the state update hook (
useState
):After doing that, we'll add a default constant
targetDate
for the edge case where the prop is not defined. We'll use as fallback a date that is defined as two days from the current date, this date is calculated on an util function that was previously imported from the/utils
folder.Now, we need to add the
tick
function and theDEFAULT_TARGET_DATE
constant to make the countdown work:At last but not least, change the
h1
so that it shows the countdown that we've created. For that, we need to use thetimeRemaining
current state:Therefore, with these changes, we'll see a real-time update of the countdown! The result on the homepage is this: