Some questions about watchEffect()
#10563
-
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
When using watchEffect(), it is designed to deeply observe the entire object hierarchy for any changes in nested ref objects. This is different from the default behavior of watch(), which shallowly watches the object and triggers the callback only when the reference of the object changes. watchEffect() disregards the deep option used in watch() because its purpose is to capture any changes in reactive variables, allowing the callback to capture any changes that might affect the view. This depth-first observation behavior makes watchEffect() more suitable for handling side effects that need to be executed whenever any reactive variable changes. ref automatically unwraps the value, providing direct access to the underlying primitive or object. On the other hand, shallowRef maintains a shallow wrapping and does not automatically unwrap the value. When the deep option is set to true in watch, it triggers a deep traversal of the observed reactive variables to detect changes within nested objects. This deep traversal can result in performance overhead, especially when dealing with complex object structures or deeply nested levels. Therefore, when using watch, if there is no need to traverse deeply into the nested objects, setting deep to false can help avoid performance costs. This is particularly important for large objects or deeply nested structures. For simple value types like primitives or shallow objects, the performance impact of the deep option is relatively minimal. |
Beta Was this translation helpful? Give feedback.
a ref is deeply reactive, but it does not pre-emptively traverse the whole tree of properties recursively. properties are tracked when accessed, and those that are not accessed, are not tracked.
But when you set
deep: true
on awatch(someRef)
, then Vue will recursively walk the whole object on initialization of the watcher, and it's nested children objects / arrays etc, and track every single property. That can potentially created thousands upon thousands of dependencies that now need to be tracked, if you have a large enough complex object/array tree.That in turn will can add to the memory footprint - and it can make the watch callback run even though the callback might not even be inte…