Hooks Colocate Related Code
What you'll learn: How Hooks keep related setup and cleanup logic together, instead of scattering it across lifecycle methods.
The Class Component Problem
In class components, you often split related logic across multiple lifecycle methods. Imagine subscribing to a data source:
// Class component splits ONE concern across THREE methods
componentDidMount() {
DataSource.subscribe(this.handleChange);
}
componentDidUpdate(prevProps) {
if (prevProps.sourceId !== this.props.sourceId) {
DataSource.unsubscribe(this.handleChange);
DataSource.subscribe(this.handleChange);
}
}
componentWillUnmount() {
DataSource.unsubscribe(this.handleChange);
}
Your subscription setup is in componentDidMount, your cleanup is in componentWillUnmount, and if props change you need componentDidUpdate too. One feature, three places.
How useEffect Solves This
With Hooks, setup and cleanup live together in one useEffect:
// Hook keeps setup and cleanup colocated
useEffect(() => {
DataSource.subscribe(handleChange);
return () => {
DataSource.unsubscribe(handleChange);
};
}, [sourceId]);
Everything about this subscription—starting it, stopping it, restarting it when sourceId changes—lives in one place. You read setup and cleanup side-by-side.
The Mental Model
Think of it like a recipe card: classes make you look at three different pages for ingredients, cooking, and cleanup. Hooks put the entire recipe on one card.
Key Takeaway: Hooks colocate related code by grouping setup and cleanup for one concern inside a single useEffect, eliminating the fragmentation that lifecycle methods forced on you.