Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-visible-second-clock.ts

30 lines1.2 KB

1import { useIsFocused } from "@react-navigation/native";
2import { useEffect, useLayoutEffect, useState } from "react";
3import { AppState } from "react-native";
4​
5/**
6 * Retained routes stay mounted when hidden, so an ungated interval would keep
7 * re-rendering them.
8 */
9export function useVisibleSecondClock(enabled: boolean): number {
10 const focused = useIsFocused();
11 const [appActive, setAppActive] = useState(() => AppState.currentState === "active");
12 const [nowMs, setNowMs] = useState(() => Date.now());
13 useEffect(() => {
14 const subscription = AppState.addEventListener("change", (state) =>
15 setAppActive(state === "active"),
16 );
17 // oxlint-disable-next-line react/set-state-in-effect -- Syncs state the listener missed.
18 setAppActive(AppState.currentState === "active");
19 return () => subscription.remove();
20 }, []);
21 const ticking = enabled && focused && appActive;
22 useLayoutEffect(() => {
23 if (!ticking) return;
24 // oxlint-disable-next-line react/set-state-in-effect -- Resuming reads the clock that stood still.
25 setNowMs(Date.now());
26 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
27 return () => clearInterval(intervalId);
28 }, [ticking]);
29 return nowMs;