Skip to content

useNow and useTickingText ​

A clock for a view that shows how long something has been running.

tsx
import { useNow, useTickingText } from '@adecore/ui';
tsx
import { Button, useNow, useTickingText } from '@adecore/ui';
import { formatClockDuration, formatElapsedShort } from '@adecore/ui/format';
import { useState } from 'react';

export default function UseNowDemo() {
    const [startedAt, setStartedAt] = useState<number | null>(null);
    const now = useNow(1000, startedAt !== null);
    const [mountedAt] = useState(Date.now);
    const ticking = useTickingText(() => formatClockDuration(Date.now() - mountedAt));

    return (
        <div className="flex flex-col items-center gap-3 text-sm text-text">
            <p className="tabular-nums">{startedAt === null ? 'Not running' : `Running for ${formatElapsedShort(now - startedAt)}`}</p>
            <Button variant="secondary" onClick={() => setStartedAt(startedAt === null ? Date.now() : null)}>
                {startedAt === null ? 'Start' : 'Stop'}
            </Button>
            <p className="text-xs text-text-muted">
                On this page for <span ref={ticking} className="tabular-nums" />
            </p>
        </div>
    );
}

useNow ​

useNow(intervalMs, ticking = true) returns the time in epoch milliseconds and renders again every intervalMs while ticking is true. Each call starts its own timer, so call it once per view and hand the time to its rows.

useTickingText ​

useTickingText(render, intervalMs = 1000) writes the text straight into a <span> and returns the ref to put on it, without re-rendering. Use it for a timer on each row of a long list.

tsx
const ref = useTickingText(() => formatElapsedShort(Date.now() - startedAt));

return <span ref={ref} />;

It also writes after every render, so the first render shows the text.

Licenses and third-party notices are listed in each package.