Skip to content

Instantly share code, notes, and snippets.

@greathmaster
Created March 24, 2021 16:32
Show Gist options
  • Save greathmaster/d56d2eba297e040452cf9ab2721371b0 to your computer and use it in GitHub Desktop.
Save greathmaster/d56d2eba297e040452cf9ab2721371b0 to your computer and use it in GitHub Desktop.
React: How to Correctly Build a Counter/Clock/Timer Component Using Hooks
// 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