Intermediate React Interview QuestionsIntermediateConcept
React · Question 43
How should you think about the lifecycle and cleanup of a React Effect?
Direct answer
An Effect starts synchronizing with an external system after a commit, and its cleanup stops the previous synchronization before React starts it again or removes the component.
ChatRoom.jsx
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [roomId]);
return <h1>{roomId}</h1>;
}- The component commits with the current roomId.
- The Effect starts the connection for that room.
- If roomId changes, React runs the previous cleanup.
- React starts the Effect again using the new roomId.
- When the component is removed, cleanup runs for the active synchronization.