AceDevHub
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>;
}
  1. The component commits with the current roomId.
  2. The Effect starts the connection for that room.
  3. If roomId changes, React runs the previous cleanup.
  4. React starts the Effect again using the new roomId.
  5. When the component is removed, cleanup runs for the active synchronization.