Created
March 24, 2021 16:32
-
-
Save greathmaster/d56d2eba297e040452cf9ab2721371b0 to your computer and use it in GitHub Desktop.
React: How to Correctly Build a Counter/Clock/Timer Component Using Hooks
This file contains hidden or 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
// React: How to Correctly Build a Counter/Clock/Timer Component Using Hooks | |
//Taken from: https://overreacted.io/making-setinterval-declarative-with-react-hooks/ | |
import React, { useState, useEffect, useRef } from "react"; | |
import ReactDOM from "react-dom"; | |
function Counter() { | |
const [count, setCount] = useState(0); | |
const savedCallback = useRef(); | |
function callback() { | |
setCount(count + 1); | |
} | |
useEffect(() => { | |
savedCallback.current = callback; | |
}); | |
useEffect(() => { | |
function tick() { | |
savedCallback.current(); | |
} | |
let id = setInterval(tick, 1000); | |
return () => { | |
console.log(id); | |
clearInterval(id); | |
} | |
}, []); | |
return <h1>{count}</h1>; | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<Counter />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment