Refactor NotificationContext to Optimize Notification Fetching

- Introduced useRef hooks to store references for fetchNotifications, authenticated, and connected states, improving performance and reducing unnecessary re-renders.
- Updated useEffect hooks to utilize the refs for fetching notifications, enhancing clarity and responsiveness to state changes while maintaining functionality.
This commit is contained in:
Tom Butcher 2026-08-21 11:37:57 +01:00
parent 2ed961b9ec
commit 9e88db5abe

View File

@ -3,7 +3,8 @@ import {
useState,
useContext,
useCallback,
useEffect
useEffect,
useRef
} from 'react'
import { useLocation } from 'react-router-dom'
import { notification, Drawer } from 'antd'
@ -59,6 +60,13 @@ const NotificationProvider = ({ children }) => {
}
}, [authenticated, fetchNotificationsApi, showError])
const fetchNotificationsRef = useRef(fetchNotifications)
const authenticatedRef = useRef(authenticated)
const connectedRef = useRef(connected)
fetchNotificationsRef.current = fetchNotifications
authenticatedRef.current = authenticated
connectedRef.current = connected
const markNotificationAsRead = useCallback(
async (notificationId) => {
try {
@ -116,14 +124,15 @@ const NotificationProvider = ({ children }) => {
// Initial load / when we become authenticated and connected
useEffect(() => {
if (!authenticated || !connected) return
fetchNotifications()
}, [authenticated, connected, fetchNotifications])
fetchNotificationsRef.current()
}, [authenticated, connected])
// Refresh when the notification center opens
useEffect(() => {
if (!notificationCenterVisible || !authenticated || !connected) return
fetchNotifications()
}, [notificationCenterVisible, authenticated, connected, fetchNotifications])
if (!notificationCenterVisible) return
if (!authenticatedRef.current || !connectedRef.current) return
fetchNotificationsRef.current()
}, [notificationCenterVisible])
useEffect(() => {
setNotificationCenterVisible(false)