useEffect Lifecycle
useEffect Lifecycle
The lifecycle of a useEffect hook is distinct from the lifecycle of the component itself. While a component goes through Mount, Update, and Unmount phases, an Effect goes through a cycle of Synchronize and Cleanup.
The Effect Lifecycle
Think of an Effect as an ongoing process that keeps your component synchronized with something outside of React.
- Setup (Start Synchronizing): The Effect runs after the component renders and the browser paints.
- Cleanup (Stop Synchronizing): The Effect’s cleanup function (if returned) runs right before the next setup runs, OR when the component unmounts.
useEffect(() => {
// 1. SETUP: Connect to the chat room
const connection = createConnection(roomId);
connection.connect();
return () => {
// 2. CLEANUP: Disconnect from the chat room
connection.disconnect();
};
}, [roomId]);
What happens when dependencies change?
If the roomId changes (e.g., the user clicks to switch from the “General” room to the “Help” room), the component updates. Here is the exact sequence of events:
- Render: React renders the component with the new
roomId(“Help”). - Paint: The browser updates the UI to show the new room.
- Cleanup (Previous Effect): React runs the cleanup function from the previous render. It disconnects from the “General” room.
- Setup (New Effect): React runs the setup function from the current render. It connects to the “Help” room.
This cycle of Cleanup ➔ Setup happens on every render where the dependencies have changed.
Visualizing the Cycle
Imagine the user navigates to a component, changes a dependency once, and then leaves the page. The lifecycle looks like this:
- Mount: Setup(A) runs.
- Update: Cleanup(A) runs ➔ Setup(B) runs.
- Unmount: Cleanup(B) runs.
Why does React clean up before the next setup?
This behavior guarantees that your component never has conflicting connections or overlapping event listeners. It ensures that the old synchronization process is completely torn down before the new one, based on the new props/state, is established.
Interview Questions
Q: How do you mimic componentDidMount using useEffect?
A: You provide an empty dependency array []. This explicitly tells React that the effect does not depend on any state or props, so it should only ever run once immediately after the initial render.