This project simulates a chat room application where users can switch between rooms and toggle end-to-end encryption. It demonstrates useEffect with cleanup: when the selected room or encryption setting changes, the previous connection is closed before a new one is established.
- Dropdown to select a chat room (general, travel, music)
- Checkbox to toggle encrypted or unencrypted connections
useEffectwith cleanup to manage connection lifecycle- Different connection factory functions passed as props
useEffectdependencies and cleanup functions- Passing functions as props
useStatefor room ID and encryption toggle- Effect re-runs triggered by dependency changes
- React
- JavaScript (ES6+)
- CSS
25-chat-room/
├── src/
│ ├── App.js
│ ├── ChatRoom.js
│ ├── chat.js
│ ├── index.js
│ └── styles.css
├── public/
└── package.json
export default function App() {
const [roomId, setRoomId] = useState('general');
const [isEncrypted, setIsEncrypted] = useState(false);
return (
<>
<select value={roomId} onChange={e => setRoomId(e.target.value)}>
<option value="general">general</option>
<option value="travel">travel</option>
</select>
<input
type="checkbox"
checked={isEncrypted}
onChange={e => setIsEncrypted(e.target.checked)}
/>
<ChatRoom
roomId={roomId}
createConnection={isEncrypted
? createEncryptedConnection
: createUnencryptedConnection}
/>
</>
);
}graph TD
A[User Changes Room or Encryption] --> B[State Updates in App]
B --> C[ChatRoom Re-renders with New Props]
C --> D[useEffect Cleanup Closes Old Connection]
D --> E[useEffect Runs createConnection with New Config]
E --> F[New Chat Connection Established]
cd 25-chat-room
npm install
npm start