Last active
April 4, 2021 17:25
-
-
Save myogeshchavan97/29b83d08c9f65352810ad1dae16c3a8e to your computer and use it in GitHub Desktop.
useRef Demo using Timer
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
import React, { useState, useEffect, useRef } from "react"; | |
import ReactDOM from "react-dom"; | |
const App = () => { | |
const [date, setDate] = useState(new Date()); | |
let interval = useRef(); | |
useEffect(() => { | |
setTimeout(() => { | |
clearInterval(interval.current); | |
}, 5000); | |
}, []); | |
useEffect(() => { | |
console.log("component mounted"); | |
interval.current = setInterval(() => { | |
console.log("displaying current time"); | |
setDate(new Date()); | |
}, 1000); | |
return () => { | |
clearInterval(interval.current); | |
console.log("component unmounted"); | |
}; | |
}, []); | |
const unmount = () => { | |
ReactDOM.render(<p>Hello</p>, document.getElementById("root")); | |
}; | |
return ( | |
<div> | |
<div>Date: {date.toLocaleTimeString()}</div> | |
<br /> | |
<button onClick={unmount}>Unmount Component</button> | |
</div> | |
); | |
}; | |
ReactDOM.render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment