Easy
React Memory Leak: How to Properly Clean Up EventSource Subscriptions in useEffect
You're maintaining a legacy React application and notice potential memory leaks. What's wrong with this event subscription pattern?
1function NotificationCenter({ userId }) {2 const [notifications, setNotifications] = useState([]);3 const eventSource = new EventSource(`/api/notifications/${userId}`);45 useEffect(() => {6 const handleNotification = (event) => {7 const notification = JSON.parse(event.data);8 setNotifications(prev => [...prev, notification]);9 };1011 eventSource.onmessage = handleNotification;1213 eventSource.onerror = (error) => {14 console.error('EventSource failed:', error);15 };16 }, []);1718 return (19 <div className="notification-center">20 {notifications.map(notification => (21 <NotificationItem22 key={notification.id}23 data={notification}24 />25 ))}26 </div>27 );28}