Devesh's Blog

Devesh's Blog

Let's build a real-time clock using React Hooks!

Let's build a real-time clock using React Hooks!

Building a real-time clock that doesn't re-render the page with React Hooks! P.S. with codepen link.

I looked through a lot of resources for building a clock using React Hooks but all I found was the one using React class components, so here's one using React Hooks!

P.S. you can go to the bottom of the blog for live codepen embed where you can play around with the code!


Step 1: Create a functional component 'Clock'.

const Clock = () => {
    //empty for now
}

Step 2: use "new Date()" to get the current time.

const Clock = () => {
    return (
        <div className="container">
            <h1>
                {new Date().toLocaleTimeString()} (IST)
            </h1>    
        </div>
    )
}

Here the "new Date().toLocaleTimeString()" returns the current time in format "hh-mm-ss" but notice that it doesn't re-render, and we'll do that using useState and useEffect methods!


Step 3: Store the current time in useState.

const Clock = () => {

    const [timer, setTimer] = useState(new Date())

    return (
        <div className="container">
            <h1>
                {new Date().toLocaleTimeString()} (IST)
            </h1>    
        </div>
    )
}

we will initialize the state with "new Date()" and update it in the next step.


Step 4: Create a function tick and call it every second using useEffect!

Create a tick function that set's the timer to new Date whenever it is called, so the useEffect makes use of setInterval to render it every 1000ms or 1s. Atlast make sure you change the "new Date()" to "timer" of the state.

const Clock = () => {

    const [timer, setTimer] = useState(new Date())

    function tick() {
        setTimer(new Date)
    }

    React.useEffect(() => {
        let timerID = setInterval(() => {
            tick()
        }, 1000)

        return () => {
            clearInterval(timerID)
        }
    })

    return (
        <div className="container">
            <h1>
                {timer.toLocaleTimeString()} (IST)
            </h1>    
        </div>
    )
}

Live playground for you to play with the code👇


Hope you liked the blog, and if you did make sure you hit those reactions, also follow here on Hashnode and also on Twitter @Deveshb15 where I post similar content every day!

Interested in reading more such articles from Devesh B?

Support the author by donating an amount of your choice.

Recent sponsors
 
Share this