React | Interval hook

by matox

HTML

<div id="root"></div>

CSS

/* Center tables for demo */

.tableSearch {
  display: flex;
  justify-content: center;
  margin: 1rem 0;
}

table {
  margin: 0 auto;
}

/* Default Table Style */
table {
  color: #333;
  background: white;
  border: 1px solid grey;
  font-size: 12pt;
  border-collapse: collapse;
}
table thead th,
table tfoot th {
  color: #777;
  background: rgba(0,0,0,.1);
}
table caption {
  padding:.5em;
}
table th,
table td {
  padding: .5em;
  border: 1px solid lightgrey;
}
/* Zebra Table Style */
[data-table-theme*=zebra] tbody tr:nth-of-type(odd) {
  background: rgba(0,0,0,.05);
}
[data-table-theme*=zebra][data-table-theme*=dark] tbody tr:nth-of-type(odd) {
  background: rgba(255,255,255,.05);
}
/* Dark Style */
[data-table-theme*=dark] {
  color: #ddd;
  background: #333;
  font-size: 12pt;
  border-collapse: collapse;
}
[data-table-theme*=dark] thead th,
[data-table-theme*=dark] tfoot th {
  color: #aaa;
  background: rgba(0255,255,255,.15);
}
[data-table-theme*=dark] caption {
  padding:.5em;
}
[data-table-theme*=dark] th,
[data-table-theme*=dark] td {
  padding: .5em;
  border: 1px solid grey;
}

React

function useInterval(fn, ms) {
  const callbackRef = React.useRef(fn);
  console.log(fn);
	
  React.useEffect(() => {
    callbackRef.current = fn;
  }, [fn]);
  
  React.useEffect(() => {
  	const intervalHandle = setInterval(() => {
    	console.log('tick', callbackRef.current);
	    callbackRef.current();
	  }, ms);
  
  	return () => clearInterval(intervalHandle);
  }, []);
}

function Example(props) {
	const [locale, setLocale] = React.useState();
  const [dateString, setDateString] = React.useState();
  const [functionString, setFunctionString] = React.useState('console.log("works")');
  const inputRef = React.useRef();
  
	useInterval(() => setDateString(new Date().toLocaleString(locale)), 5000);

  
  console.log(inputRef.current && inputRef.current.value, functionString);
  
	return (
  	<div>
      <span>Change format:</span>
      <button onClick={() => setLocale('sl')}>SL</button>
      <button onClick={() => setLocale('jp')}>JP</button><br/>
      <input type="text" ref={inputRef} />
      <button onClick={() => setFunctionString(inputRef.current.value)}>Apply</button>
      {dateString}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Example/>);