<main></main>
const { useState, useEffect, useRef } = React;
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
function useTimer() {
const [ ticks, setTicks ] = useState(0);
useInterval(function() {
setTicks(ticks + 1);
}, 1000);
return ticks;
}
function App(props) {
const ticks = useTimer();
return (
<div>
<p>Hello World {ticks}</p>
</div>
);
}
ReactDOM.render(<App />, document.querySelector('main'));
View Compiled
This Pen doesn't use any external CSS resources.