Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
adding clock component refactoring logic
- Loading branch information
1 parent
7e701e2
commit 7d5d46e
Showing
2 changed files
with
29 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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> | ||
); | ||
} |