Dev HelpersOpen library
← Back

Cooldown button

Import and render <CooldownButton /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/CooldownButton.tsx

import { useState, useEffect } from "react";

export default function CooldownButton({ seconds = 10 }: { seconds?: number } = {}) {
  const [until, set] = useState(0);
  useEffect(() => {
    if (!until) return;
    const timer = setTimeout(() => set(0), Math.max(0, until - Date.now()));
    return () => clearTimeout(timer);
  }, [until]);
  return (
    <button disabled={!!until} onClick={() => set(Date.now() + seconds * 1000)}>
      {until ? "Cooling down" : "Start cooldown"}
    </button>
  );
}