>>` data structure. If no subscribing effects Set was found for a property (tracked for the first time), it will be created. This is what the `getSubscribersForProperty()` function does, in short. For simplicity, we will skip its details.
Inside `trigger()`, we again lookup the subscriber effects for the property. But this time we invoke them instead:
```js
function trigger(target, key) {
const effects = getSubscribersForProperty(target, key)
effects.forEach((effect) => effect())
}
```
Now let's circle back to the `whenDepsChange()` function:
```js
function whenDepsChange(update) {
const effect = () => {
activeEffect = effect
update()
activeEffect = null
}
effect()
}
```
It wraps the raw `update` function into an effect that sets itself as the current active effect before running the actual update. This enables `track()` calls during the update to locate the current active effect.
At this point, we have created an effect that automatically tracks its dependencies, and re-runs whenever a dependency changes. We call this a **Reactive Effect**.
Vue provides an API that allows you to create reactive effects: [`watchEffect()`](/api/reactivity-core.html#watcheffect). In fact, you probably have noticed that it works pretty similar to the magical `whenDepsChange()` in the example. We can now rework the original example using actual Vue APIs:
```js
import { ref, watchEffect } from 'vue'
const A0 = ref(0)
const A1 = ref(1)
const A2 = ref()
watchEffect(() => {
// tracks A0 and A1
A2.value = A0.value + A1.value
})
// triggers the effect
A0.value = 2
```
Using a reactive effect to mutating a ref isn't the most interesting use case - in fact, using a computed property makes it more declarative:
```js
import { ref, computed } from 'vue'
const A0 = ref(0)
const A1 = ref(1)
const A2 = computed(() => A0.value + A1.value)
A0.value = 2
```
Internally, `computed` manages its invalidation and re-computation using a reactive effect.
So what's an example of a common and useful reactive effect? Well, updating the DOM! We can implement simple "reactive rendering" like this:
```js
import { ref, watchEffect } from 'vue'
const count = ref(0)
watchEffect(() => {
document.body.innerHTML = `count is: ${count.value}`
})
// updates the DOM
count.value++
```
In fact, this is pretty close to how a Vue component keeps the state and the DOM in sync - each component instance creates a reactive effect to render and update the DOM. Of course, Vue components use much more efficient ways to update the DOM than `innerHTML`. This is discussed in [Rendering Mechanism](./rendering-mechanism).
The `ref()`, `computed()` and `watchEffect()` APIs are all part of the Composition API. If you have only been using Options API with Vue so far, you'll notice that Composition API is closer to how Vue's reactivity system works under the hood. In fact, in Vue 3 the Options API is implemented on top of the Composition API. All property access on the component instance (`this`) trigger getter/setters for reactivity tracking, and options like `watch` and `computed` invoke their Composition API equivalents internally.
## Runtime vs. Compile-time Reactivity
Vue's reactivity system is primarily runtime-based: the tracking and triggering are all performed while the code is running directly in the browser. The pros of runtime reactivity is that it can work without a build step, and there are fewer edge cases. On the other hand, this makes it constrained by the syntax limitations of JavaScript.
We have already encountered a limitation in the previous example: JavaScript does not provide a way for us to intercept read and write of local variables, so we have to always access reactive state as object properties, using either reactive objects or refs.
We have been experimenting with the [Reactivity Transform](/guide/extras/reactivity-transform.html) feature to reduce the code verbosity:
```js
let A0 = $ref(0)
let A1 = $ref(1)
// track on variable read
const A2 = $computed(() => A0 + A1)
// trigger on variable write
A0 = 2
```
This snippet compiles into exactly what we'd have written without the transform, by automatically appending `.value` after references of the variables. With Reactivity Transform, Vue's reactivity system becomes a hybrid one.
## Reactivity Debugging
It's great that Vue's reactivity system automatically tracks dependencies, but in some cases we may want to figure out exactly what is being tracked, or what is causing a component to re-render.
### Component Debugging Hooks
We can debug what dependencies are used during a component's render and which dependency is triggering an update using the `renderTracked``onRenderTracked` and `renderTriggered``onRenderTriggered` lifecycle hooks. Both hooks will receive a debugger event which contains information on the dependency in question. It is recommended to place a `debugger` statement in the callbacks to interactively inspect the dependency:
```vue
```
```js
export default {
renderTracked(event) {
debugger
},
renderTriggered(event) {
debugger
}
}
```
:::tip
Component debug hooks only work in development mode.
:::
The debug event objects have the following type:
```ts
type DebuggerEvent = {
effect: ReactiveEffect
target: object
type:
| TrackOpTypes /* 'get' | 'has' | 'iterate' */
| TriggerOpTypes /* 'set' | 'add' | 'delete' | 'clear' */
key: any
newValue?: any
oldValue?: any
oldTarget?: Map | Set
}
```
### Computed Debugging
We can debug computed properties by passing `computed()` a second options object with `onTrack` and `onTrigger` callbacks:
- `onTrack` will be called when a reactive property or ref is tracked as a dependency.
- `onTrigger` will be called when the watcher callback is triggered by the mutation of a dependency.
Both callbacks will receive debugger events in the [same format](#debugger-event) as component debug hooks:
```js
const plusOne = computed(() => count.value + 1, {
onTrack(e) {
// triggered when count.value is tracked as a dependency
debugger
},
onTrigger(e) {
// triggered when count.value is mutated
debugger
}
})
// access plusOne, should trigger onTrack
console.log(plusOne.value)
// mutate count.value, should trigger onTrigger
count.value++
```
:::tip
`onTrack` and `onTrigger` computed options only work in development mode.
:::
### Watcher Debugging
Similar to `computed()`, watchers also support the `onTrack` and `onTrigger` options:
```js
watch(source, callback, {
onTrack(e) {
debugger
},
onTrigger(e) {
debugger
}
})
watchEffect(callback, {
onTrack(e) {
debugger
},
onTrigger(e) {
debugger
}
})
```
:::tip
`onTrack` and `onTrigger` watcher options only work in development mode.
:::
## Integration with External State Systems
Vue's reactivity system works by deeply converting plain JavaScript objects into reactive proxies. The deep conversion can be unnecessary or sometimes unwanted when integrating with external state management systems (e.g. if an external solution also uses Proxies).
The general idea of integrating Vue's reactivity system with an external state management solution is to hold the external state in a [`shallowRef`](/api/reactivity-advanced.html#shallowref). A shallow ref is only reactive when its `.value` property is accessed - the inner value is left intact. When the external state changes, replace the ref value to trigger updates.
### Immutable Data
If you are implementing a undo / redo feature, you likely want to take a snapshot of the application's state on every user edit. However, Vue's mutable reactivity system isn't best suited for this if the state tree is large, because serializing the entire state object on every update can be expensive in terms of both CPU and memory costs.
[Immutable data structures](https://en.wikipedia.org/wiki/Persistent_data_structure) solve this by never mutating the state objects - instead, it creates new objects that share the same, unchanged parts with old ones. There are different ways of using immutable data in JavaScript, but we recommend using [Immer](https://immerjs.github.io/immer/) with Vue because it allows you to use immutable data while keeping the more ergonomic, mutable syntax.
We can integrate Immer with Vue via a simple composable:
```js
import produce from "immer"
import { shallowRef } from 'vue'
export function useImmer(baseState) {
const state = shallowRef(baseState)
return {
state,
update(updater) {
state.value = produce(state.value, updater)
}
}
}
```
[Try it in the Playground](https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCB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y2UgZnJvbSBcImltbWVyXCJcbmltcG9ydCB7IHNoYWxsb3dSZWYgfSBmcm9tICd2dWUnXG5cbmV4cG9ydCBmdW5jdGlvbiB1c2VJbW1lcihiYXNlU3RhdGUpIHtcbiBcdCBjb25zdCBzdGF0ZSA9IHNoYWxsb3dSZWYoYmFzZVN0YXRlKVxuICAgXG4gICByZXR1cm4ge1xuICAgICBzdGF0ZSxcbiAgICAgdXBkYXRlKHVwZGF0ZXIpIHtcbiAgICAgICBzdGF0ZS52YWx1ZSA9IHByb2R1Y2Uoc3RhdGUudmFsdWUsIHVwZGF0ZXIpXG4gICAgIH1cbiAgIH1cbn1cbiJ9)
### State Machines
[State Machine](https://en.wikipedia.org/wiki/Finite-state_machine) is a model for describing all the possible states an application can be in, and all the possible ways it can transition from one state to another. While it may be an overkill for simple components, it can help make complex state flows more robust and manageable.
One of the most popular state machine implementations in JavaScript is [XState](https://xstate.js.org/). Here's a composable that integrates with it:
```js
import { createMachine, interpret } from 'xstate'
import { shallowRef } from 'vue'
export function useMachine(options) {
const machine = createMachine(options)
const state = shallowRef(machine.initialState)
const service = interpret(machine)
.onTransition(newState => state.value = newState)
.start()
return {
state,
send(event) {
service.send(event)
}
}
}
```
[Try it in the Playground](https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCB7IHVzZU1hY2hpbmUgfSBmcm9tICcuL21hY2hpbmUuanMnXG4gIFxuY29uc3QgeyBzdGF0ZSwgc2VuZCB9ID0gdXNlTWFjaGluZSh7XG4gIGlkOiAndG9nZ2xlJyxcbiAgaW5pdGlhbDogJ2luYWN0aXZlJyxcbiAgc3RhdGVzOiB7XG4gICAgaW5hY3RpdmU6IHsgb246IHsgVE9HR0xFOiAnYWN0aXZlJyB9IH0sXG4gICAgYWN0aXZlOiB7IG9uOiB7IFRPR0dMRTogJ2luYWN0aXZlJyB9IH1cbiAgfVxufSlcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxidXR0b24gQGNsaWNrPVwic2VuZCgnVE9HR0xFJylcIj5cbiAgICB7eyBzdGF0ZS5tYXRjaGVzKFwiaW5hY3RpdmVcIikgPyBcIk9mZlwiIDogXCJPblwiIH19XG4gIDwvYnV0dG9uPlxuPC90ZW1wbGF0ZT4iLCJpbXBvcnQtbWFwLmpzb24iOiJ7XG4gIFwiaW1wb3J0c1wiOiB7XG4gICAgXCJ2dWVcIjogXCJodHRwczovL3NmYy52dWVqcy5vcmcvdnVlLnJ1bnRpbWUuZXNtLWJyb3dzZXIuanNcIixcbiAgICBcInhzdGF0ZVwiOiBcImh0dHBzOi8vdW5wa2cuY29tL3hzdGF0ZUA0LjI3LjAvZXMvaW5kZXguanM/bW9kdWxlXCJcbiAgfVxufSIsIm1hY2hpbmUuanMiOiJpbXBvcnQgeyBjcmVhdGVNYWNoaW5lLCBpbnRlcnByZXQgfSBmcm9tICd4c3RhdGUnXG5pbXBvcnQgeyBzaGFsbG93UmVmIH0gZnJvbSAndnVlJ1xuXG5leHBvcnQgZnVuY3Rpb24gdXNlTWFjaGluZShvcHRpb25zKSB7XG4gIGNvbnN0IG1hY2hpbmUgPSBjcmVhdGVNYWNoaW5lKG9wdGlvbnMpXG4gIGNvbnN0IHN0YXRlID0gc2hhbGxvd1JlZihtYWNoaW5lLmluaXRpYWxTdGF0ZSlcbiAgY29uc3Qgc2VydmljZSA9IGludGVycHJldChtYWNoaW5lKVxuICBcdC5vblRyYW5zaXRpb24obmV3U3RhdGUgPT4gc3RhdGUudmFsdWUgPSBuZXdTdGF0ZSlcbiAgICAuc3RhcnQoKVxuICByZXR1cm4ge1xuICAgIHN0YXRlLFxuICAgIHNlbmQoZXZlbnQpIHtcbiAgICAgIHNlcnZpY2Uuc2VuZChldmVudClcbiAgICB9XG4gIH1cbn0ifQ==)
### RxJS
[RxJS](https://rxjs.dev/) is a library for working with asynchronous event streams. The [VueUse](https://vueuse.org/) library provides the [`@vueuse/rxjs`](https://vueuse.org/rxjs/readme.html) add-on for connecting RxJS streams with Vue's reactivity system.