From 7d5d46e54968058770bfd720ce97a0f86b5ba4f1 Mon Sep 17 00:00:00 2001 From: Sam O'Shaughnessy Date: Fri, 27 Oct 2023 11:47:25 +0800 Subject: [PATCH] adding clock component refactoring logic --- src/App.jsx | 25 ++----------------------- src/Clock.jsx | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 23 deletions(-) create mode 100644 src/Clock.jsx diff --git a/src/App.jsx b/src/App.jsx index cc16d48..85f4b67 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,28 +1,8 @@ import logo from "/logo.png"; import "./App.css"; - -// import required React hooks for this component, useState will implement state, where as useEffect facilitates implementation of LifeCycle methods -import { useState, useEffect } from "react"; +import Clock from "./Clock"; function App() { - // Initialise Component state to contain a "date" attribute with current date using the useState method. - const [date, setDate] = useState(new Date()); - - useEffect(() => { - // useEffect implementation to execute code when the component loads - // Set date value in state every second to current date and time - // Save setInterval timerId in a variable for teardown later in the useEffect method - const timerId = setInterval(() => { - setDate(new Date()); - }, 1000); - - // useEffect implemenation to tear down the interval saved in timerId - return () => { - // Teardown setInterval timer saved within the timerId variable - clearInterval(timerId); - }; - }); - return ( <>
@@ -30,8 +10,7 @@ function App() {

World Clock

- {/* Render date value that is stored in state */} -

{date.toString()}

+
); diff --git a/src/Clock.jsx b/src/Clock.jsx new file mode 100644 index 0000000..96b50c7 --- /dev/null +++ b/src/Clock.jsx @@ -0,0 +1,27 @@ +// import required React hooks for this component, useState will implement state, where as useEffect facilitates implementation of LifeCycle methods +import { useState, useEffect } from "react"; + +export default function Clock(props) { + // Initialise Component state to contain a "date" attribute with current date using the useState method. + const [date, setDate] = useState(new Date()); + + useEffect(() => { + // useEffect implementation to execute code when the component loads + // Set date value in state every second to current date and time + // Save setInterval timerId in a variable for teardown later in the useEffect method + const timerId = setInterval(() => { + setDate(new Date()); + }, 1000); + + // useEffect implemenation to tear down the interval saved in timerId + return () => { + // Teardown setInterval timer saved within the timerId variable + clearInterval(timerId); + }; + }); + + return ( + // Render date value that is stored in state +

{date.toString()}

+ ); +}