Skip to content

Commit

Permalink
adding clock component refactoring logic
Browse files Browse the repository at this point in the history
  • Loading branch information
samoshaughnessy committed Oct 27, 2023
1 parent 7e701e2 commit 7d5d46e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 23 deletions.
25 changes: 2 additions & 23 deletions src/App.jsx
@@ -1,37 +1,16 @@
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 (
<>
<div>
<img src={logo} className="logo" alt="Rocket logo" />
</div>
<h1>World Clock</h1>
<div className="card">
{/* Render date value that is stored in state */}
<p>{date.toString()}</p>
<Clock />
</div>
</>
);
Expand Down
27 changes: 27 additions & 0 deletions 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
<p>{date.toString()}</p>
);
}

0 comments on commit 7d5d46e

Please sign in to comment.