Why Vue state and rendered text can disagree

ProjectsCommunity Digest0 replies

Community DigestMember#1

S M Tahosin traces a Vue update from a reactive property to the DOM in “You're Still Optimizing Re-Renders Wrong: The Vue 3 Architecture That Outsmarted the Virtual DOM” (https://dev.to/smtahosin/youre-still-optimizing-re-renders-wrong-the-vue-3-architecture-that-outsmarted-the-virtual-dom-3fd1). That sequence gives developers a way to diagnose two similar symptoms in a component: a value that has stopped tracking state and a DOM read that happened before Vue finished updating.

Check where the property is read

Vue uses proxies for reactive objects. Reading a property through the proxy during a tracked effect lets Vue register the dependency. A later write through the proxy can notify the subscribers to that property. If setup code copies a primitive property into a local binding, the binding holds the value it received at that moment. Reading the binding from an effect leaves Vue without a property access to track. Tahosin illustrates this with an age field. Keeping the access on the reactive object, or destructuring refs produced by toRefs(), preserves the link. Vue documents the tracking model and the limitation of destructuring in its reactivity guide (https://vuejs.org/guide/extras/reactivity-in-depth.html).

Check when the DOM is read

If the state is correct and rendered text looks stale in a synchronous callback, the read may be too early. Vue buffers DOM updates. Its nextTick() API lets code wait for the pending update flush before it measures or inspects the element. This matters when an interaction updates a counter and then immediately queries the counter's text. Any logic that reads the reactive value directly can use the new value, while logic that needs the newly rendered text can await the flush (https://vuejs.org/api/general.html#nexttick).

Tahosin also points out that tracking and patching serve separate purposes. When a component does update, Vue can use hints that the template compiler attached to dynamic nodes. A patch flag can indicate that text or a class binding needs attention. Blocks collect dynamic descendants so the renderer can skip stable parts of the template during updates. A profile card with a static header and a dynamic biography illustrates that distinction without requiring a benchmark (https://vuejs.org/guide/extras/rendering-mechanism.html).

No replies yet