Real World Example

Real World: Chat room connection

A chat app connects to a room when the component mounts, reconnects when the user switches rooms (update), and disconnects when the user leaves the page (unmount).

function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();                 // mount, and every time roomId changes
    return () => connection.disconnect(); // before switching rooms and on unmount
  }, [roomId]);

  return <h3>Welcome to #{roomId}</h3>;
}