DEV Community

geoffreyg81
geoffreyg81

Posted on

How I handled real-time notifications in a MERN stack using a Socket.io Singleton

Hi Dev Community! πŸ‘‹

I recently built Peekr, an anonymous social network, and I wanted to share a quick tip on handling WebSockets in React.

The Problem: My notification bell was re-rendering and creating multiple socket connections, leading to memory leaks and ghost notifications.

The Fix: I implemented a Singleton pattern for the socket instance. By centralizing the connection in one file, I ensure that the app uses only one socket across the entire lifecycle.

The Stack: MongoDB, Express, React, Node.js + Socket.io.

Feel free to check the live demo here (it's my first big MERN project!): https://peekr-seven.vercel.app


Top comments (0)