Skip to main content

usePeriodicalSignal

Returns an int that increments every period, triggering a rebuild on each tick. Use it as a periodic trigger without hand-rolling a Timer.

void useHeartbeat(PresenceService service, String roomId) {
final signal = usePeriodicalSignal(period: const Duration(seconds: 30));

useEffect(() {
unawaited(service.sendHeartbeat(roomId)); // <- Re-runs every time the signal ticks
return null;
}, [signal, roomId]);
}

Signature

int usePeriodicalSignal({required Duration period, bool enabled = true});
  • period - the interval between ticks.
  • enabled (true by default) - when false, the timer is not running and the value stays put. Flip it to start and stop ticking.

The returned value carries no meaning beyond "the number of ticks so far" - it exists to be put in another hook's keys or to drive a rebuild.

Use cases

  • Periodic side effects: heartbeats, presence pings, polling. Put the signal in a useEffect key so the effect re-runs each tick.

  • Countdown and live-clock displays: derive the remaining time from a deadline and let the signal drive the rebuilds, so the value can never drift:

    Duration useRemaining(DateTime deadline) {
    final left = deadline.difference(DateTime.now());
    final remaining = left.isNegative ? Duration.zero : left;
    // Ticks once a second until the deadline passes, then the timer stops.
    usePeriodicalSignal(period: const Duration(seconds: 1), enabled: !left.isNegative);
    return remaining; // <- Derived from the deadline, so it can never drift
    }

Caveats

  • The value is a tick count, not a timestamp or a remaining duration. Do not display it - derive what you show from a real clock (DateTime.now()) or a deadline, and use the signal only to schedule the rebuild.

  • Disable the timer when it is not needed (enabled: false) - for example once a countdown reaches zero - so it does not keep firing in the background.

See also

  • useEffect - the usual consumer; key it on the signal to run work each tick
  • useDebounced - the other timer-based hook in this category
  • useMemoized - recompute a value each tick by keying on the signal