JSFiddle - React, Tailwind, and code Playground

by henser

HTML

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

React

// Define the useInterval hook
function useInterval(callback, delay) {
  React.useEffect(() => {
    if (delay === null) return;

    const intervalId = setInterval(callback, delay);

    return () => {
      clearInterval(intervalId);
    };
  }, [callback, delay]);
}

// Main component
const CounterApp = () => {
  const [count, setCount] = React.useState(0);
  const [isRunning, setIsRunning] = React.useState(true);

  // Use the useInterval hook
  useInterval(() => {
    if (isRunning) {
      setCount(prevCount => prevCount + 1);
    }
  }, 1000); // Update count every second (1000 ms)

  return (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h1>Counter: {count}</h1>
      <button onClick={() => setIsRunning(!isRunning)}>
        {isRunning ? 'Pause' : 'Resume'}
      </button>
    </div>
  );
};

// Render the CounterApp component
ReactDOM.render(<CounterApp />, document.getElementById('root'));