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

use-visible-second-clock.ts

27 lines1.2 KB

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