Next

Fix the effect run counter for a hooks migration

Review the AI's codeEasy10 minMeta style

Your task

An agent migrating React class components to hooks turned a componentDidUpdate that refetched when userId changed into useEffect(() => { fetchUser(userId); }, [userId, fetchUser]). Two things changed. The effect now also runs on mount, and fetchUser is a new function on every render, so the dependency array changes every time. Your team counts how often the fetch runs for a sequence of renders.

An assistant wrote count_effect_runs(dep_values, unstable_dep, skip_mount). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • dep_values: the userId at each render, in order. The first render is the mount.
  • unstable_dep: a dependency changes on every render, like a function created during render without useCallback.
  • skip_mount: the effect does not run on mount, as componentDidUpdate never did.
  • Return how many times the effect runs.

Rules the tests check:

  • On the mount, the first render, the effect runs unless skip_mount is true.
  • On every later render, the effect runs if unstable_dep is true. Otherwise it runs only when the value differs from the previous render's value.
  • Values are compared exactly, as strings.

Examples

count_effect_runs(dep_values: list[str], unstable_dep: bool, skip_mount: bool) -> int
Example 1
Inputcount_effect_runs(["u1", "u1", "u2"], False, False)
Output2
Example 2
Inputcount_effect_runs(["u1", "u1", "u2"], False, True)
Output1
Example 3
Inputcount_effect_runs(["u1", "u1", "u2"], True, False)
Output3