Open History to see the last commit
1---
2id: reactivity
3title: Reactivity
4---
5β
6Vue uses [the signals paradigm](https://vuejs.org/guide/extras/reactivity-in-depth.html#connection-to-signals) to handle and track reactivity. A key feature of
7this system is the reactive system only triggers updates on specifically watched reactive properties. A consequence of this is you also need to ensure that the queries are updated when values they consume are updated.
8β
9## Keeping Queries Reactive
10β
11When creating a composable for a query your first choice may be to write it like so:
12β
13```ts
14export function useUserProjects(userId: string) {
15 return useQuery({
16 queryKey: ['userProjects', userId],
17 queryFn: () => api.fetchUserProjects(userId),
18 })
19}
20```
21β
22We might consume this composable like so:
23β
24```ts
25// Reactive user ID ref.
26const userId = ref('1')
27// Fetches the user 1's projects.
28const { data: projects } = useUserProjects(userId.value)
29β
30const onChangeUser = (newUserId: string) => {
31 // Edits the userId, but the query will not re-fetch.
32 userId.value = newUserId
33}
34```
35β
36This code will not work as intended. This is because we are extracting the value from the userId ref directly. Vue-query is not tracking the `userId` `ref` so it has no way of knowing when the value changes.
37β
38Luckily, the fix for this is trivial. The value must be made trackable in the query key. We can just accept the `ref` directly in the composable and place it in the query key:
39β
40```ts
41export function useUserProjects(userId: Ref<string>) {
42 return useQuery({
43 queryKey: ['userProjects', userId],
44 queryFn: () => api.fetchUserProjects(userId.value),
45 })
46}
47```
48β
49Now the query will re-fetch when the `userId` changes.
50β
51```ts
52const onChangeUser = (newUserId: string) => {
53 // Query refetches data with new user ID!
54 userId.value = newUserId
55}
56```
57β
58In vue query any reactive properties within a query key are tracked for changes automatically. This allows vue-query to refetch data whenever the
59parameters for a given request change.
60β
61### Accounting for Non-Reactive Queries
62β
63While far less likely, sometimes passing non-reactive variables is intentional. For example, some entities only need to be fetched once and don't need tracking, or we invalidate the query manually after a mutation instead.
64If we use our custom composable defined above the usage in this case feels a bit off:
65β
66```ts
67const { data: projects } = useUserProjects(ref('1'))
68```
69β
70We have to create an intermediate `ref` just to make the parameter type-compatible. We can do better here. Let's instead update our composable to accept both plain values and reactive values:
71β
72```ts
73export function useUserProjects(userId: MaybeRef<string>) {
74 return useQuery({
75 queryKey: ['userProjects', userId],
76 queryFn: () => api.fetchUserProjects(toValue(userId)),
77 })
78}
79```
80β
81Now we can use the composable with both plain values and refs:
82β
83```ts
84// Fetches the user 1's projects, userId is not expected to change.
85const { data: projects } = useUserProjects('1')
86β
87// Fetches the user 1's projects, queries will react to changes on userId.
88const userId = ref('1')
89β
90// Make some changes to userId...
91β
92// Query re-fetches based on any changes to userId.
93const { data: projects } = useUserProjects(userId)
94```
95β
96### Using Derived State inside Queries
97β
98It's quite common to derive some new reactive state from another source of reactive state. Commonly, this problem manifests in situations where you deal with component props. Let's assume our `userId` is a prop passed to a component:
99β
100```vue
101<script setup lang="ts">
102const props = defineProps<{
103 userId: string
104}>()
105</script>
106```
107β
108You may be tempted to use the prop directly in the query like so:
109β
110```ts
111// Won't react to changes in props.userId.
112const { data: projects } = useUserProjects(props.userId)
113```
114β
115However, similar to the first example, this is not reactive. Property access on `reactive` variables causes reactivity to be lost. We can fix this by making this derived state reactive via a `computed`:
116β
117```ts
118const userId = computed(() => props.userId)
119β
120// Reacts to changes in props.userId.
121const { data: projects } = useUserProjects(userId)
122```
123β
124This works as expected, however, this solution isn't always the most optimal. Aside from the introduction of an intermediate variable, we also create a memoized value that is somewhat unnecessary. For trivial cases of simple property access `computed` is an optimization with no real benefit. In these cases a more appropriate solution is to use [reactive getters](https://blog.vuejs.org/posts/vue-3-3#better-getter-support-with-toref-and-tovalue). Reactive getters are simply functions that return a value based on some reactive state, similar to how `computed` works. Unlike `computed`, reactive getters do not memoize their values so it makes it a good candidate for simple property access.
125β
126Let's once again refactor our composable, but this time we'll have it accept a `ref`, plain value, or a reactive getter:
127β
128```ts
129export function useUserProjects(userId: MaybeRefOrGetter<string>) {
130 ...
131}
132```
133β
134Let's adjust our usage and now use a reactive getter:
135β
136```ts
137// Reacts to changes in props.userId. No `computed` needed!
138const { data: projects } = useUserProjects(() => props.userId)
139```
140β
141This gives us a terse syntax and the reactivity we need without any unneeded memoization overhead.
142β
143### Other tracked Query Options
144β
145Above, we only touched one query option that tracks reactive dependencies. However, in addition to `queryKey`, `enabled` also allows
146the use of reactive values. This comes in handy in situations where you want to control the fetching of a query based on some derived state:
147β
148```ts
149export function useUserProjects(userId: MaybeRef<string>) {
150 return useQuery({
151 queryKey: ['userProjects', userId],
152 queryFn: () => api.fetchUserProjects(toValue(userId)),
153 enabled: () => toValue(userId) === activeUserId.value,
154 })
155}
156```
157β
158More details on this option can be found on the [useQuery reference](./reference/functions/useQuery.md) page.
159β
160The other query options accept refs as well, and pick up changes to them. Reactive getters, however, are only resolved in `queryKey` and `enabled`, since a function is already a valid value for options such as `select` or `staleTime`.
161β
162### Immutability
163β
164Results from `useQuery` are always immutable. This is necessary for performance and caching purposes. If you need to mutate a value returned from `useQuery`, you must create a copy of the data.
165β
166One implication of this design is that passing values from `useQuery` to a two-way binding such as `v-model` will not work. You must create a mutable copy of the data before attempting to update it in place.
167β
168## Key Takeaways
169β
170- Every query option accepts refs, but only `queryKey` and `enabled` also accept reactive getters.
171- Pass query option that accept all three types of values in Vue: refs, plain values, and reactive getters.
172- If you expect a query to react to changes based on the values it consumes, ensure that the values are reactive. (i.e. pass in refs directly to the query, or use reactive getters)
173- If you don't need a query to be reactive pass in a plain value.
174- For trivial derived state such as property access consider using a reactive getter in place of a `computed`.
175- Results from `useQuery` are always immutable.