Mohamed Ajmal P
Posted on December 12, 2022
To create a timer in a React app using TypeScript and Moment.js, you can use the setInterval() method from the window object, along with Moment.js's duration and add methods to calculate the remaining time.
Here is an example of how you might implement a timer in a React component using TypeScript and Moment.js:
import React, { useState, useEffect } from 'react'
import moment from 'moment'
const MyComponent: React.FC = () => {
const [timeLeft, setTimeLeft] = useState(moment.duration(5, 'minutes'))
// Use the useEffect hook to set up the timer
useEffect(() => {
const interval = setInterval(() => {
setTimeLeft(timeLeft => timeLeft.subtract(1, 'seconds'))
}, 1000)
// Clean up the interval when the component unmounts
return () => clearInterval(interval)
}, [])
return (
<div>
<p>Time left: {timeLeft.minutes()}:{timeLeft.seconds()}</p>
</div>
)
}
In this example, the useEffect hook is used to set up the setInterval() method when the component is mounted. The setTimeLeft callback function is used to subtract one second from the timeLeft state variable every second, using Moment.js's duration and subtract methods. This causes the component to re-render with the updated time remaining.
Note that the useEffect hook takes an array of dependencies as its second argument. In this case, we've passed an empty array to indicate that the effect should only run once when the component is mounted. This is important, as it prevents the timer from being reset every time the component re-renders.
Posted on December 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.