Skip to content

Instantly share code, notes, and snippets.

@myogeshchavan97
Last active April 4, 2021 17:25
Show Gist options
  • Save myogeshchavan97/29b83d08c9f65352810ad1dae16c3a8e to your computer and use it in GitHub Desktop.
Save myogeshchavan97/29b83d08c9f65352810ad1dae16c3a8e to your computer and use it in GitHub Desktop.
useRef Demo using Timer
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