Skip to content

Colota - Android GPS Location tracker

refactor: move coord subscription into leaf components to reduce unnecessary re-renders

Max Dietrich85c59a70f53b
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 0c7e4700..7079d57d 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -6,7 +6,7 @@ import React, { useMemo, useState, useCallback } from "react"
import { NavigationContainer, NavigationContainerRef } from "@react-navigation/native"
import { createNativeStackNavigator } from "@react-navigation/native-stack"
import { SafeAreaProvider } from "react-native-safe-area-context"
-import { View, StatusBar, Platform } from "react-native"
+import { View, StatusBar, Platform, StyleSheet } from "react-native"
import MapLibreGL from "@maplibre/maplibre-react-native"
import { ThemeProvider, useTheme } from "./src/hooks/useTheme"
import { fonts } from "./src/styles/typography"
@@ -194,7 +194,7 @@ function AppNavigator() {
<SafeAreaProvider>
<StatusBar {...statusBarConfig} />
<NavigationContainer linking={linking} ref={navigationRef} onStateChange={handleStateChange}>
- <View style={{ flex: 1 }}>
+ <View style={styles.flex}>
<Stack.Navigator initialRouteName="Dashboard" screenOptions={screenOptions}>
{SCREEN_CONFIG.map((screen) => (
<Stack.Screen
@@ -223,3 +223,7 @@ export default function App() {
</ThemeProvider>
)
}
+
+const styles = StyleSheet.create({
+ flex: { flex: 1 }
+})
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index cfb71f28..6b6afa64 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -105,7 +105,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@Volatile
private var activeProfileName: String? = null
-
+
/** Skips when app is backgrounded to avoid unnecessary bridge overhead. */
@JvmStatic
fun sendLocationEvent(location: android.location.Location, battery: Int, batteryStatus: Int): Boolean {
diff --git a/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx b/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx
index e88210dd..d4101b8d 100644
--- a/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx
+++ b/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx
@@ -5,49 +5,21 @@
import React from "react"
import { View, Text, StyleSheet } from "react-native"
-import { LocationCoords } from "../../../types/global"
import { useTheme } from "../../../hooks/useTheme"
+import { useCoords } from "../../../contexts/TrackingProvider"
import { fonts } from "../../../styles/typography"
import { SectionTitle } from "../../ui/SectionTitle"
import { Card } from "../../ui/Card"
-/**
- * Props for the CoordinateDisplay component
- */
-type Props = {
- /** Location coordinates object containing latitude, longitude, altitude, accuracy, speed, and bearing */
- coords: LocationCoords
-}
-
-/**
- * Displays location data in a responsive grid layout with six metric cards.
- *
- * Shows:
- * - Latitude/Longitude (6 decimal places)
- * - Altitude (rounded meters)
- * - Accuracy (1 decimal place, with ± prefix)
- *
- * All values include fallbacks for missing data and adapt to the current theme.
- *
- * @example
- * ```tsx
- * <CoordinateDisplay
- * coords={{
- * latitude: 37.7749,
- * longitude: -122.4194,
- * altitude: 52,
- * accuracy: 10.5
- * }}
- * />
- * ```
- */
-export function CoordinateDisplay({ coords }: Props) {
+export function CoordinateDisplay() {
+ const coords = useCoords()
const { colors } = useTheme()
- // Format values with appropriate precision and fallbacks
+ if (!coords) return null
+
const latitude = coords.latitude?.toFixed(6) ?? "0.000000"
const longitude = coords.longitude?.toFixed(6) ?? "0.000000"
- const altitude = Math.round(coords.altitude ?? 0)
+ const altitude = Math.round(coords.altitude ?? 0).toLocaleString()
const accuracy = coords.accuracy?.toFixed(1) ?? "0.0"
/**
@@ -75,7 +47,7 @@ export function CoordinateDisplay({ coords }: Props) {
{/* Second Row: Altitude and Accuracy */}
<View style={styles.row}>
- {renderCard("Altitude", altitude.toLocaleString(), "m")}
+ {renderCard("Altitude", altitude, "m")}
{renderCard("Accuracy", `±${accuracy}`, "m")}
</View>
</View>
diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
index 51501af1..33990b86 100644
--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
@@ -7,6 +7,7 @@ import React, { useRef, useEffect, useMemo, useCallback, useState } from "react"
import { View, StyleSheet, Text, ActivityIndicator, DeviceEventEmitter, Image } from "react-native"
import { LocationCoords } from "../../../types/global"
import { useTheme } from "../../../hooks/useTheme"
+import { useCoords } from "../../../contexts/TrackingProvider"
import { fonts } from "../../../styles/typography"
import NativeLocationService from "../../../services/NativeLocationService"
import { MAP_ANIMATION_DURATION_MS, MAX_MAP_ZOOM } from "../../../constants"
@@ -19,7 +20,6 @@ import icon from "../../../assets/icons/icon.png"
import { logger } from "../../../utils/logger"
type Props = {
- coords: LocationCoords | null
tracking: boolean
activeZoneName: string | null
pauseReason: string | null
@@ -31,14 +31,8 @@ const isValidCoords = (c: LocationCoords | null): c is LocationCoords => {
return c !== null && c.latitude !== 0 && c.longitude !== 0
}
-export function DashboardMap({
- coords,
- tracking,
- activeZoneName,
- pauseReason,
- activeProfileName,
- isBatteryCritical
-}: Props) {
+export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProfileName, isBatteryCritical }: Props) {
+ const coords = useCoords()
const mapRef = useRef<ColotaMapRef>(null)
const { colors } = useTheme()
const [geofences, setGeofences] = useState<any[]>([])
@@ -75,9 +69,8 @@ export function DashboardMap({
// Uses ref to avoid re-triggering when isCentered flips (which would
// override the setCamera zoom from handleCenterMe with a pan-only moveTo).
useEffect(() => {
- if (coords && isCenteredRef.current && mapRef.current?.camera) {
- mapRef.current.camera.moveTo([coords.longitude, coords.latitude], MAP_ANIMATION_DURATION_MS)
- }
+ if (!coords || !isCenteredRef.current || !mapRef.current?.camera) return
+ mapRef.current.camera.moveTo([coords.longitude, coords.latitude], MAP_ANIMATION_DURATION_MS)
}, [coords])
const handleCenterMe = useCallback(() => {
diff --git a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
index 62b27449..7450b000 100644
--- a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
+++ b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
@@ -15,7 +15,7 @@ type DatabaseStatisticsProps = {
stats: DatabaseStats
}
-export function DatabaseStatistics({ stats }: DatabaseStatisticsProps) {
+export const DatabaseStatistics = React.memo(function DatabaseStatistics({ stats }: DatabaseStatisticsProps) {
const { settings } = useTracking()
const isOfflineMode = settings.isOfflineMode
const { colors } = useTheme()
@@ -63,7 +63,7 @@ export function DatabaseStatistics({ stats }: DatabaseStatisticsProps) {
</View>
</>
)
-}
+})
const styles = StyleSheet.create({
metricsSection: {
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
index ebae8bc5..ece6d587 100644
--- a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
@@ -53,6 +53,11 @@ jest.mock("../../../../services/NativeLocationService", () => ({
getSetting: jest.fn().mockResolvedValue(null)
}))
+const mockCoords = { latitude: 48.1, longitude: 11.5, accuracy: 10 }
+jest.mock("../../../../contexts/TrackingProvider", () => ({
+ useCoords: () => mockCoords
+}))
+
jest.mock("../../../../assets/icons/icon.png", () => "mock-icon")
jest.mock("../../map/MapCenterButton", () => {
@@ -64,10 +69,7 @@ jest.mock("../../map/MapCenterButton", () => {
import { DashboardMap } from "../DashboardMap"
describe("DashboardMap info cards", () => {
- const validCoords = { latitude: 48.1, longitude: 11.5, accuracy: 10 }
-
const baseProps = {
- coords: validCoords,
tracking: true,
activeZoneName: null as string | null,
pauseReason: null as string | null,
@@ -115,7 +117,7 @@ describe("DashboardMap info cards", () => {
})
it("shows Tracking Disabled when not tracking", () => {
- const { getByText } = render(<DashboardMap {...baseProps} tracking={false} coords={null} />)
+ const { getByText } = render(<DashboardMap {...baseProps} tracking={false} />)
expect(getByText("Tracking Disabled")).toBeTruthy()
})
diff --git a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
index 6b021d78..e4df406d 100644
--- a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
+++ b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
@@ -139,12 +139,16 @@ export function CalendarPicker({
return new Date(viewYear, viewMonth, 1).toLocaleDateString(undefined, { month: "long", year: "numeric" })
}, [viewYear, viewMonth])
- const formatted = date.toLocaleDateString(undefined, {
- weekday: "short",
- month: "short",
- day: "numeric",
- year: "numeric"
- })
+ const formatted = useMemo(
+ () =>
+ date.toLocaleDateString(undefined, {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ year: "numeric"
+ }),
+ [date]
+ )
const isFutureMonth =
viewYear > today.getFullYear() || (viewYear === today.getFullYear() && viewMonth >= today.getMonth())
diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsx
index 12b5a651..e5295d7e 100644
--- a/apps/mobile/src/screens/DashboardScreen.tsx
+++ b/apps/mobile/src/screens/DashboardScreen.tsx
@@ -8,7 +8,7 @@ import { StyleSheet, View, ScrollView, DeviceEventEmitter, Animated } from "reac
import { ScreenProps, DatabaseStats } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
-import { useTracking, useCoords } from "../contexts/TrackingProvider"
+import { useTracking } from "../contexts/TrackingProvider"
import { useFocusEffect } from "@react-navigation/native"
import {
Button,
@@ -25,7 +25,6 @@ import { logger } from "../utils/logger"
export function DashboardScreen({ navigation }: ScreenProps) {
const { settings, tracking, startTracking, stopTracking, setSettings, activeProfileName } = useTracking()
- const coords = useCoords()
const { colors } = useTheme()
const [stats, setStats] = useState<DatabaseStats>({
@@ -167,7 +166,6 @@ export function DashboardScreen({ navigation }: ScreenProps) {
onTouchEnd={() => setScrollEnabled(true)}
>
<DashboardMap
- coords={coords}
tracking={tracking}
activeZoneName={currentPauseZone}
pauseReason={pauseReason}
@@ -209,9 +207,9 @@ export function DashboardScreen({ navigation }: ScreenProps) {
)}
{/* Coordinates */}
- {tracking && coords && (
+ {tracking && (
<View style={styles.metricsSection}>
- <CoordinateDisplay coords={coords} />
+ <CoordinateDisplay />
</View>
)}
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 8dd38a07..bff79b85 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -108,11 +108,10 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
return () => listener.remove()
}, [loadGeofences])
- // Auto-center camera when position changes (ref avoids overriding setCamera zoom)
+ // Auto-center camera when position changes (ref avoids overriding setCamera zoom).
useEffect(() => {
- if (coords && isCenteredRef.current && tracking && mapRef.current?.camera) {
- mapRef.current.camera.moveTo([coords.longitude, coords.latitude], MAP_ANIMATION_DURATION_MS)
- }
+ if (!coords || !isCenteredRef.current || !tracking || !mapRef.current?.camera) return
+ mapRef.current.camera.moveTo([coords.longitude, coords.latitude], MAP_ANIMATION_DURATION_MS)
}, [coords, tracking])
const handleMapPress = useCallback(