Understand once() and off()

Socket.IO supports additional listener-management methods.

socket.once() registers an event listener that executes only once.

socket.off() removes a previously registered listener.

These methods are particularly useful in frontend applications where components mount and unmount.

For example, repeatedly registering listeners without removing them can result in duplicate event handling.

Avoid Duplicate Listeners

In React applications, register listeners inside an appropriate effect and remove the same listener function during cleanup.

Manage Event Listeners
function handleNotification(notification) {
  console.log('Notification:', notification);
}

socket.once('notification:welcome', (message) => {
  console.log('Welcome:', message);
});

socket.on('notification:new', handleNotification);

// Remove the previously registered listener.
socket.off('notification:new', handleNotification);

The once method executes a listener only once, while off removes a specific previously registered listener.

Key Takeaways
  • once() executes a listener only once.

  • off() removes event listeners.

  • Clean up listeners to prevent duplicate processing.