code

useInterval

a react interval hook that keeps its callback current and cleans up the timer between runs.

html

<div id="app"></div>

css

body {
  background: #666;
  padding: 20px;
  font-family: sans-serrif;
  font-size: 2em;
  color: white;
}

button {
  margin-left: 1em;
  background-color: #000;
  border-color: #000;
  color: white;
  font-size: 1em;
}
button:hover {
  color: #eeddee;
  border: inset 1px #eeddee;
}

javascript

function useInterval(callback, delay) {
  const cbRef = React.useRef(callback);
  React.useEffect(() => {
    cbRef.current = callback;
  }, [callback]);
  React.useEffect(() => {
    function tick() {
      cbRef.current();
    }
    const id = window.setInterval(tick, delay);
    return () => window.clearInterval(id);
  }, [delay]);
}

function HelloWorld() {
  useInterval(() => console.log("yo"), 100);
  useInterval(() => console.log("yo dawg"), 100);

  return <div>see console.log</div>;
}

ReactDOM.render(<HelloWorld />, document.querySelector("#app"));

this demo preserves the compiled output and may depend on external libraries or services that are no longer available.

original jsfiddle post