From 85a80b09fc8fab7a26f9e69e6d38a48fbf1dccf4 Mon Sep 17 00:00:00 2001 From: Alexander Petkov Date: Sat, 1 Jul 2023 12:29:20 +0300 Subject: [PATCH] notificationClient: Establish ws connection only on client render The current websocket configuration, creates a new websocket client, for every SSR generated page. Since those clients are technically active, they are never cleaned up, thus resulting in memory leak. This change makes it so, a new web socket connection is created only on first render of the component. Tests: 1. Start visiting different pages randomly 2. Observe the current websocket clients, in the Socket object. They can be found in Socket.adapters.sids 3. The size of sids should remain 1, per browser window --- src/common/util/notificationClient.ts | 1 + .../client/layout/NotificationSnackBar/NotificationSnackBar.tsx | 1 + 2 files changed, 2 insertions(+) diff --git a/src/common/util/notificationClient.ts b/src/common/util/notificationClient.ts index dcb4ed9b2..af66e2d73 100644 --- a/src/common/util/notificationClient.ts +++ b/src/common/util/notificationClient.ts @@ -4,6 +4,7 @@ import { io } from 'socket.io-client' const { publicRuntimeConfig } = getConfig() const notificationClient = io(publicRuntimeConfig.API_URL, { transports: ['websocket'], + autoConnect: false, }) export default notificationClient diff --git a/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx b/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx index fe670cd7b..e57af26a6 100644 --- a/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx +++ b/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx @@ -21,6 +21,7 @@ function NotificationSnackBar({ const [notifications, setNotifications] = useState([]) useEffect(() => { + if (!notificationClient.connected) notificationClient.connect() notificationClient.on('successfulDonation', (notificationData: NotificationLayoutData) => { setNotifications((prevState) => [...prevState, notificationData]) })