perf(Notice): replace useState by useSyncExternalStore (#3682)

* fix: the first function call creates multiple axios instances

* perf(Notice): replace useState by useSyncExternalStore

* chore: prettier --check .

* fix: prettier format
This commit is contained in:
TianHua Liu
2025-06-12 20:49:39 +08:00
committed by GitHub
parent 18850bb51a
commit b7cb511032
2 changed files with 10 additions and 15 deletions

View File

@@ -1,24 +1,17 @@
import React, { useState, useEffect } from "react";
import React, { useSyncExternalStore } from "react";
import { Snackbar, Alert, IconButton, Box } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import {
subscribeNotices,
hideNotice,
NoticeItem,
getSnapshotNotices,
} from "@/services/noticeService";
export const NoticeManager: React.FC = () => {
const [currentNotices, setCurrentNotices] = useState<NoticeItem[]>([]);
useEffect(() => {
const unsubscribe = subscribeNotices((notices) => {
setCurrentNotices(notices);
});
return () => {
unsubscribe();
};
}, []);
const currentNotices = useSyncExternalStore(
subscribeNotices,
getSnapshotNotices,
);
const handleClose = (id: number) => {
hideNotice(id);

View File

@@ -61,13 +61,15 @@ export function hideNotice(id: number) {
// Subscribes a listener function to notice state changes.
export function subscribeNotices(listener: Listener): () => void {
export function subscribeNotices(listener: () => void) {
listeners.add(listener);
listener([...notices]);
return () => {
listeners.delete(listener);
};
}
export function getSnapshotNotices() {
return notices;
}
// Function to clear all notices at once
export function clearAllNotices() {