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:
parent
2ed961b9ec
commit
9e88db5abe
@ -3,7 +3,8 @@ import {
|
|||||||
useState,
|
useState,
|
||||||
useContext,
|
useContext,
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect
|
useEffect,
|
||||||
|
useRef
|
||||||
} from 'react'
|
} from 'react'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { useLocation } from 'react-router-dom'
|
||||||
import { notification, Drawer } from 'antd'
|
import { notification, Drawer } from 'antd'
|
||||||
@ -59,6 +60,13 @@ const NotificationProvider = ({ children }) => {
|
|||||||
}
|
}
|
||||||
}, [authenticated, fetchNotificationsApi, showError])
|
}, [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(
|
const markNotificationAsRead = useCallback(
|
||||||
async (notificationId) => {
|
async (notificationId) => {
|
||||||
try {
|
try {
|
||||||
@ -116,14 +124,15 @@ const NotificationProvider = ({ children }) => {
|
|||||||
// Initial load / when we become authenticated and connected
|
// Initial load / when we become authenticated and connected
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authenticated || !connected) return
|
if (!authenticated || !connected) return
|
||||||
fetchNotifications()
|
fetchNotificationsRef.current()
|
||||||
}, [authenticated, connected, fetchNotifications])
|
}, [authenticated, connected])
|
||||||
|
|
||||||
// Refresh when the notification center opens
|
// Refresh when the notification center opens
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!notificationCenterVisible || !authenticated || !connected) return
|
if (!notificationCenterVisible) return
|
||||||
fetchNotifications()
|
if (!authenticatedRef.current || !connectedRef.current) return
|
||||||
}, [notificationCenterVisible, authenticated, connected, fetchNotifications])
|
fetchNotificationsRef.current()
|
||||||
|
}, [notificationCenterVisible])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setNotificationCenterVisible(false)
|
setNotificationCenterVisible(false)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user