I am learning about hooks, so I try to write code that display current time.
I had comment in each line of code the reason I write it. So:
- Am I understand right?
- Is there any bad practice?
- What need to be improved?
import * as React from 'react'
function App() {
// Define a state for keeping track of time
const [time, setTime] = React.useState("");
// Logic, computation to update time (which is side-effect) should put inside useEffect
React.useEffect(() => {
// Running side-effect when component mounted (componentDidMount)
const myInterval = setInterval(() => {
setTime(new Date().toLocaleTimeString());
}, 1000);
// Clear side-effect when component unmount (componentWillUnmount)
return () => {
clearInterval(myInterval);
}
})
return (
<div className="App">
<h1>{time}</h1>
</div>
);
}
export default App;