Crea cuentas regresivas precisas. Calcula automáticamente días, horas, minutos y segundos hasta una fecha objetivo.
Crea cuentas regresivas sin gestionar intervalos o cálculos manuales. Define tu fecha objetivo y el hook calcula automáticamente el tiempo restante.
import { useCountdown } from "@blifedesarrollo/hooks";function EventCountdown() {
const targetDate = new Date("2024-12-31T23:59:59");
const { timeRemaining, isCompleted } = useCountdown(targetDate);
if (isCompleted) {
return <div>🎉 ¡El evento ha comenzado!</div>;
}
return (
<div>
<div>
<span>{timeRemaining.days}</span>
<span>Días</span>
</div>
<div>
<span>{timeRemaining.hours}</span>
<span>Horas</span>
</div>
<div>
<span>{timeRemaining.minutes}</span>
<span>Minutos</span>
</div>
<div>
<span>{timeRemaining.seconds}</span>
<span>Segundos</span>
</div>
</div>
);
}Cómo funciona:
"05", "23", "59")isCompleted cuando termina// Cuenta regresiva de 24 horas desde ahora
const targetDate = new Date(Date.now() + 24 * 60 * 60 * 1000);
const { timeRemaining } = useCountdown(targetDate);const targetDate = 1703462400000; // Timestamp en milisegundos
const { timeRemaining } = useCountdown(targetDate);function TimerApp() {
const targetDate = new Date(Date.now() + 5 * 60 * 1000); // 5 minutos
const { timeRemaining, isRunning, isCompleted, start, stop, restart } = useCountdown(targetDate, {
autoStart: false, // No iniciar automáticamente
});
return (
<div>
<div>
{timeRemaining.minutes}:{timeRemaining.seconds}
</div>
{!isRunning && !isCompleted && <button onClick={start}>Iniciar</button>}
{isRunning && <button onClick={stop}>Pausar</button>}
<button onClick={restart}>Reiniciar</button>
{isCompleted && <div>⏰ ¡Tiempo terminado!</div>}
</div>
);
}const { timeRemaining, isCompleted } = useCountdown(targetDate, {
onTick: (time) => {
// Se ejecuta cada segundo
document.title = `Faltan ${time.days}d ${time.hours}h`;
},
onComplete: () => {
// Se ejecuta cuando termina
document.title = "¡Evento disponible!";
alert("🎉 ¡El evento ha comenzado!");
},
});const { timeRemaining } = useCountdown(targetDate, {
padTime: false, // "2h 5m 30s" en lugar de "02:05:30"
});Por defecto, la cuenta regresiva calcula desde "ahora". Con startDate puedes definir un punto de inicio diferente:
// Calcular duración entre dos fechas específicas
const meetingStart = new Date("2024-05-15T14:00:00");
const meetingEnd = new Date("2024-05-15T15:30:00");
const { timeRemaining } = useCountdown(meetingEnd, {
startDate: meetingStart, // Calcula desde meetingStart hasta meetingEnd
autoStart: false,
});Cuándo usar startDate:
| Parámetro | Tipo | Requerido | Default | Descripción |
|---|---|---|---|---|
targetDate | Date | number | Sí | - | Fecha objetivo (Date o timestamp) |
options.onTick | (time) => void | No | - | Callback ejecutado cada segundo |
options.onComplete | () => void | No | - | Callback ejecutado cuando termina |
options.autoStart | boolean | No | true | Si debe iniciar automáticamente |
options.padTime | boolean | No | true | Si aplica padding a números ("05" vs "5") |
options.startDate | Date | number | No | - | Fecha de inicio personalizada |
Formas de definir targetDate:
// Date object
const targetDate = new Date("2024-12-25T00:00:00");
// Timestamp
const targetDate = 1703462400000;
// Relativa (en 24 horas)
const targetDate = new Date(Date.now() + 24 * 60 * 60 * 1000);Retorna un objeto con el siguiente formato:
const { timeRemaining, isRunning, isCompleted, start, stop, restart } = useCountdown(
targetDate,
options,
);| Propiedad | Tipo | Descripción |
|---|---|---|
timeRemaining | { days, hours, minutes, seconds } | Tiempo restante formateado (strings) |
isRunning | boolean | true si la cuenta regresiva está activa |
isCompleted | boolean | true si la cuenta regresiva ha terminado |
start | () => void | Inicia/reanuda la cuenta regresiva |
stop | () => void | Pausa la cuenta regresiva |
restart | () => void | Reinicia completamente la cuenta regresiva |
Formato de timeRemaining:
padTime: true (default): "05", "23", "59", "30"padTime: false: "5", "23", "59", "30"