From Class Lifecycles to Hooks: Effects, Stale Closures, Reuse
System DesignModel answerLast updated
Port a class component's fetch-and-timer lifecycle to useEffect, diagnose a stale-closure bug in a counter, and compare HOCs and render props with custom hooks.
Moving a React Component from Classes to Hooks
Your team is migrating a codebase from class components to function components with hooks. Answer the four parts below the way you would explain them to a colleague in a code review.
Part 1: Lifecycle in a class component
A class component receives a userId prop. It must:
- load that user's data when it first appears,
- run a repeating timer while it is on screen,
- cancel the in-flight request and stop the timer when it disappears.
Which lifecycle methods do you use, and what goes in each? Think about what should happen if userId changes while the component stays mounted.
Part 2: The same behavior with useEffect
Rewrite Part 1 as a function component. Then explain:
- how the dependency array decides when an effect runs,
- when and why the cleanup function is called.
Part 3: A counter that will not count
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
console.log("Count is: " + count);
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}
- What is wrong with this component, and what is the name of the underlying problem?
- Why do the logged value and the value passed to
setCountstay the same on every tick? - Give a correct fix, and say which alternatives you would avoid and why.
Part 4: Sharing stateful logic
Compare how class-based code shares stateful logic (higher-order components, render props) with how custom hooks do it. Why have custom hooks become the default choice?
Hints
Hint 1
In a class, one concern (loading data) ends up split across three methods. Consider what must happen on first render, on a prop change, and on removal.
Hint 2
Each render of a function component has its own `count`. An effect with an empty dependency array only ever sees the variables from the render in which it was created.
Hint 3
State setters accept a function that receives the latest state. That removes the need to read `count` inside the interval. For comparing sharing patterns, look at wrapper depth, prop name collisions and how visible the data flow is.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
A strong answer shows that you understand the model, not just the syntax:
- Each render is a snapshot, and effects close over that snapshot.
- Setup and teardown are tied to dependencies, not to named lifecycle moments.
- Hooks let you organize code by concern and reuse it without wrapper components.
1. Class lifecycle
componentDidMount: start the first fetch and start the timer. It runs once, after the first commit to the DOM.componentDidUpdate(prevProps): ifprevProps.userId !== this.props.userId, refetch. Many people forget this. Without it, the component keeps showing the previous user.componentWillUnmount: clear the timer and abort the pending request.
class UserCard extends React.Component {
state = { user: null, error: null, ticks: 0 };
componentDidMount() {
this.load(this.props.userId);
this.timer = setInterval(
() => this.setState(s => ({ ticks: s.ticks + 1 })), 1000);
}
componentDidUpdate(prev) {
if (prev.userId !== this.props.userId) this.load(this.props.userId);
}
componentWillUnmount() {
clearInterval(this.timer);
this.controller?.abort();
}
load(id) {
this.controller?.abort(); // drop any older request
this.controller = new AbortController();
fetch(`/api/users/${id}`, { signal: this.controller.signal })
.then(r => r.json())
.then(user => this.setState({ user }))
.catch(e => { if (e.name !== "AbortError") this.setState({ error: e }); });
}
// render omitted
}
Weakness: the data-loading concern is spread over three methods, while the unrelated timer shares those same methods. Related code is separated and unrelated code is mixed together.
2. The useEffect version
function UserCard({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [ticks, setTicks] = useState(0);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(r => r.json())
.then(setUser)
.catch(e => { if (e.name !== "AbortError") setError(e); });
return () => controller.abort();
}, [userId]);
useEffect(() => {
const id = setInterval(() => setTicks(t => t + 1), 1000);
return () => clearInterval(id);
}, []);
// render omitted
}
Dependency array:
| Array | Effect runs |
|---|---|
| omitted | after every render |
[] | after the first render only |
[a, b] | after the first render, then after any render where a or b changed (compared with Object.is) |
Cleanup:
- React runs the previous effect's cleanup before running the effect again, and also when the component unmounts.
- So when
userIdchanges, the old request is aborted before the new one starts. This prevents a slow, outdated response from overwriting newer data (a race condition). - One mechanism replaces
componentDidMount,componentDidUpdateandcomponentWillUnmount, and each concern gets its own effect.
Details worth mentioning:
- Effects run after the browser paints. Use
useLayoutEffectonly for synchronous DOM measurement. - In development, React 18 StrictMode mounts, unmounts and remounts a component once. This deliberately exposes effects with missing or incorrect cleanup.
3. The stale closure
Cause: the dependency array is [], so the effect runs once, on the first render, where count is 0. The interval callback captures that render's count. Later renders create new count variables, but the callback never sees them.
Effect on each tick:
- The log always prints
Count is: 0. - The first tick calls
setCount(0 + 1), so the display goes to 1. - Every later tick calls
setCount(1)again with the same value. React sees no change and bails out, so the display stays at 1.
Preferred fix: a functional updater.
useEffect(() => {
const id = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(id);
}, []);
The updater receives the latest state, so the callback no longer reads count and [] is truthful. To log the current value, use a separate effect rather than logging inside the updater, since updaters must be pure and StrictMode may call them twice:
useEffect(() => { console.log("Count is: " + count); }, [count]);
Alternative: a ref, for cases where a long-lived callback needs the latest value but must not restart:
const countRef = useRef(count);
useEffect(() => { countRef.current = count; });
// the interval reads countRef.current
Fix to avoid: putting count in the dependency array. It is correct but tears down and recreates the interval every second, which can cause timing drift and wasted work. The react-hooks/exhaustive-deps lint rule flags the original bug, so enabling it is part of the prevention.
4. Sharing logic
Higher-order components (withUser(Comp)):
- Add a wrapper layer to the tree.
- Inject props invisibly, so it is unclear where a prop comes from.
- Two HOCs can inject the same prop name and overwrite each other.
- Need extra work for refs and static methods, and are awkward to type.
Render props (<User id={1}>{u => ...}</User>):
- Data flow is more explicit than with HOCs.
- Composing several produces nested callbacks.
- The shared values are only available inside the render callback, not in lifecycle methods.
Custom hooks (const user = useUser(id)):
function useUser(userId) {
const [user, setUser] = useState(null);
useEffect(() => { /* fetch with abort, keyed on userId */ }, [userId]);
return user;
}
Why they are preferred:
- No extra components, so the tree stays flat and devtools stay readable.
- The source of every value is visible at the call site.
- The caller names the returned values, so there are no collisions.
- Hooks compose naturally, since a hook can call other hooks.
- Logic is grouped by concern, and each hook can be tested on its own.
- Each call gets its own independent state, so sharing logic does not share state.
Trade-offs: hooks must follow the rules (call them at the top level, only from components or other hooks), and they require discipline about dependencies. Class components remain supported, and error boundaries still have to be classes.
Common mistakes
- Omitting
componentDidUpdate, or an equivalent dependency, so the data goes stale. - Forgetting cleanup, which leaks timers, subscriptions and state updates after unmount.
- Silencing the exhaustive-deps lint rule instead of restructuring the code.
- Believing that
[]means "always read current values". It means "always read the first render's values".