KatInterview

From Class Lifecycles to Hooks: Effects, Stale Closures, Reuse

System DesignModel answer
MediumModel answerSystem DesignreacthooksuseEffect

Last 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 setCount stay 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.