Fix the effect run counter for a hooks migration
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: theuserIdat each render, in order. The first render is the mount.unstable_dep: a dependency changes on every render, like a function created during render withoutuseCallback.skip_mount: the effect does not run on mount, ascomponentDidUpdatenever did.- Return how many times the effect runs.
Rules the tests check:
- On the mount, the first render, the effect runs unless
skip_mountis true. - On every later render, the effect runs if
unstable_depis 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) -> intExample 1
Input
count_effect_runs(["u1", "u1", "u2"], False, False)Output
2Example 2
Input
count_effect_runs(["u1", "u1", "u2"], False, True)Output
1Example 3
Input
count_effect_runs(["u1", "u1", "u2"], True, False)Output
3