Create clock component NextJS
- Published on
- 2 min read
- Authors

- Name
- Robin te Hofstee
- @Robin_teHofstee
How to Create a live clock component in Nextjs.
Here's a step-by-step breakdown:
- Importing Dependencies: The first line imports the
Reactlibrary, along with theuseStateanduseEffecthooks from 'react'.
import React, { useState, useEffect } from 'react';
- Type Definition: The
Propstype is defined to specify the shape of the props that theClockcomponent expects. It expects an object with atimeproperty of typenumber.
type Props = {
time:number
}
- Clock Component: The
Clockcomponent is defined as a functional component that takesPropsas its argument. Thetimeproperty from the props is destructured and renamed toinitial.
const Clock = ({time: initial}: Props) => {
- State Initialization: The
useStatehook is used to create a state variabletimeand a functionsetTimeto update it. The initial state is set to a newDateobject created with theinitialprop.
const [isClient, setIsClient] = useState(false);
const [time, setTime] = useState(new Date(initial))
- Effect Hook: The
useEffecthook is used to create a side effect that runs after render. In this case, it sets up a timer that updates thetimestate every second.
useEffect(() => {
setIsClient(true);
const timer = setInterval(() => {
setTime(new Date())
}, 1000)
return () => clearInterval(timer)
}, []);
- Rendering: The component returns a
divelement that displays the current time and date.
return (
<div className="relative w-full flex flex-col">
<div>{time.toLocaleTimeString()}</div>
<div>{time.toLocaleDateString()}</div>
</div>
);
- Exporting the Component: Finally, the
Clockcomponent is exported for use in other parts of the application.
export default Clock
This component will display the current time and date, and it will update every second. The time and date are displayed using the toLocaleTimeString and toLocaleDateString methods of the Date object, which format the time and date according to the user's locale. The useEffect hook ensures that the timer is cleared when the component is unmounted, preventing memory leaks. I hope this explanation helps! Let me know if you have any other questions. 😊