fix: Memory-Leak bei PWA-Update-Checks durch Cleanup beheben.

Entfernt Listener und Intervalle beim erneuten SW-Register und beim Unmount des Hooks.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-05-29 17:44:31 +02:00
co-authored by Cursor
parent f01c5dc86f
commit 593d1aea20
+24 -7
View File
@@ -1,34 +1,51 @@
import { useEffect, useRef } from 'react'
import { useRegisterSW } from 'virtual:pwa-register/react' import { useRegisterSW } from 'virtual:pwa-register/react'
const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000 const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000
function scheduleUpdateChecks(registration: ServiceWorkerRegistration) { function scheduleUpdateChecks(registration: ServiceWorkerRegistration): () => void {
const checkForUpdate = () => { const checkForUpdate = () => {
registration.update().catch(() => {}) registration.update().catch(() => {})
} }
document.addEventListener('visibilitychange', () => { const onVisibilityChange = () => {
if (document.visibilityState === 'visible') { if (document.visibilityState === 'visible') {
checkForUpdate() checkForUpdate()
} }
}) }
window.setInterval(checkForUpdate, UPDATE_CHECK_INTERVAL_MS) document.addEventListener('visibilitychange', onVisibilityChange)
const intervalId = window.setInterval(checkForUpdate, UPDATE_CHECK_INTERVAL_MS)
return () => {
document.removeEventListener('visibilitychange', onVisibilityChange)
window.clearInterval(intervalId)
}
} }
export function usePwaUpdate() { export function usePwaUpdate() {
const cleanupRef = useRef<(() => void) | null>(null)
const { const {
needRefresh: [needRefresh], needRefresh: [needRefresh],
updateServiceWorker updateServiceWorker
} = useRegisterSW({ } = useRegisterSW({
immediate: true, immediate: true,
onRegisteredSW(_swUrl: string, registration: ServiceWorkerRegistration | undefined) { onRegisteredSW(_swUrl: string, registration: ServiceWorkerRegistration | undefined) {
if (registration) { if (!registration) return
scheduleUpdateChecks(registration)
} cleanupRef.current?.()
cleanupRef.current = scheduleUpdateChecks(registration)
} }
}) })
useEffect(() => {
return () => {
cleanupRef.current?.()
cleanupRef.current = null
}
}, [])
const updateApp = async () => { const updateApp = async () => {
await updateServiceWorker(true) await updateServiceWorker(true)
} }