Vue's watchEffect Fires Twice: It's Not a Bug, It's How Dependency Tracking Works
Misreading the double run as a bug leads to pointless workarounds and wasted debugging sessions. Choosing `watch` over `watchEffect` for route-parameter logic keeps code predictable and avoids firing callbacks when the route object updates without real value changes.
A common Vue confusion: `watchEffect` inside a route component logs twice. The cause is built into the API. `watchEffect` evaluates its callback immediately at creation to collect reactive dependencies. That first run reads `route.query.type` and registers it as a dependency. Later, when the route updates and `route.query` changes, the effect runs a second time. Even if the `type` value is unchanged, a new reference to the query object can trigger it.
The article breaks down the mechanics. Reading `route.query.type` inside an `if` condition still counts as a dependency read, because the condition itself accesses the property. Debugging tools like `onTrack` and `onTrigger` can show when dependencies are collected and fired. A simple execution counter also confirms the sequence.
When the goal is to react only to changes in the `type` value itself, `watch` with a getter is the right tool. `watch` does not run immediately by default and compares the specific value, avoiding redundant triggers. The `stop` handle returned by `watchEffect` stops tracking manually, though component-scoped watchers stop automatically on unmount.
The first run of watchEffect is the dependency collection pass; without it, Vue would not know what to subscribe to, so the double execution is inherent to the design.
Because if conditions read properties, developers cannot avoid tracking by wrapping reads in conditionals; the dependency is recorded regardless of the branch taken.
watchEffect is a blunt instrument for route parameters: it reacts to any accessed reactive property, while watch offers value-level precision by comparing the old and new values.
The article's advice to prefer watch for value-specific reactions is a practical rule of thumb, but watchEffect still makes sense when the effect genuinely depends on the entire query state.
Calling stop() is often omitted in component code because Vue handles cleanup, but the article correctly flags that external watchers leak if not stopped manually.
The fact that the check inside an if is also tracked—I hadn't noticed that before.
This is actually a bug in Vue Router, but as long as it works, it's fine. Not going to dwell on it; this is duplicate dependency collection.