Vue composables¶
This guide describes when frontend code in app/frontend/src/ becomes a composable, how it receives reactive inputs, derives state, cleans up after itself, and handles asynchronous loading. The examples use a made-up bookmarks module: they show the pattern, not existing code.
Composable or util¶
- Write a composable (
use*in the module'scomposables/folder) when the code needs Vue reactivity or lifecycle:ref,computed, watchers, lifecycle hooks, or other composables. - Write a util when the code is a plain transformation of its arguments (see Utils). A composable can call it inside
computed, which keeps the logic testable without Vue. - Give each composable one responsibility and return only the state and functions its callers use.
Keep inputs reactive¶
A composable reads its inputs every time it derives a value, so pass something it can track:
- Accept a
Ref(or a getter) for an input that can change, and read.valueinsidecomputedor a watcher, not once at setup time. - Convert a prop with
toRef(props, "name"). Passingprops.namehands over the current value only, and later prop changes are lost. - Pass a plain value only when it is fixed for the owner's lifetime, such as an entity type that never changes while the component lives.
Derive with computed, react with watchers¶
Use computed for any value that can be calculated from other state. This composable keeps only the search query as its own state and derives the rest:
export const useBookmarkSearch = (bookmarks: Readonly<Ref<readonly Bookmark[]>>) => {
const query = ref("");
const visibleBookmarks = computed(() => filterBookmarks(bookmarks.value, query.value));
return { query, visibleBookmarks };
};
The filtering itself lives in the pure util filterBookmarks (Utils); the composable only connects it to reactive inputs.
Reach for a watcher last¶
A watcher is correct only when a state change must cause a side effect outside Vue's reactive graph. In other cases it usually hides a design problem: a derived value stored in a ref, state without a clear owner, or an action handled indirectly through the state it changed. Check the alternatives first:
| You want to | Use instead of a watcher |
|---|---|
| Calculate a value from other state, or transform a prop | computed |
| Edit a value the parent owns | defineModel, or a prop with an emit |
| Do something when the user clicks, types or selects | The event handler or the function that changes the state |
| Tell the parent that local state changed | emit from the function that changes it |
| Follow up on a store change | The store action that makes the change |
| Reset local state when the component shows another record | :key on the component in the parent, so it is created again |
| Fill an editable draft from a prop | Copy the value in the handler that starts editing |
| Run code once when the component is created | Call it in setup or onMounted |
| Track element size, a media query, storage or a DOM event | A @vueuse/core composable |
// Avoid: a second source of truth that is one tick behind and can drift.
const fullName = ref("");
watch([firstName, lastName], () => {
fullName.value = `${firstName.value} ${lastName.value}`;
});
// Prefer
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
A watcher remains the right tool for:
- loading data when a reactive input changes, such as an id from props or the route,
- synchronising with something outside Vue: the DOM, storage, a third-party widget.
When you do write one:
- Watch the narrowest source: a getter such as
() => props.issue.id, not the whole object. Avoiddeep: true, which walks every nested property on each change. - Prefer
watchwith an explicit source overwatchEffect, so the trigger is visible and nothing read after anawaitis silently left untracked. - Do not let a watcher write state that another watcher reads. A chain of watchers is a
computedor one function. - Cancel or ignore outdated asynchronous work with
onWatcherCleanupor the runner from Apply only the latest response. - Keep the default flush timing unless the effect needs the component's updated DOM, for example to measure a new layout or to focus an element that was just rendered; use
flush: "post"then. Avoidflush: "sync", which gives up batching and runs on every single mutation.
Clean up what you start¶
A composable that starts a listener, timer, observer, or subscription also stops it.
- Stop a previous instance before starting a new one, so repeated calls never leave two running.
- Register cleanup with
onUnmountedwhen the composable is tied to a component. UseonScopeDisposewhen it may run in a store or another effect scope, for example to invalidate pending requests (Apply only the latest response). - Prefer existing composables that already clean up after themselves, such as
useMediaQueryfrom@vueuse/core, over manualaddEventListenercalls.
A composable that owns an interval stops the previous one before starting and clears it on unmount:
export const useAutoRefresh = (refresh: () => void, intervalMs: number) => {
let timerId: number | undefined;
const stop = () => {
window.clearInterval(timerId);
timerId = undefined;
};
const start = () => {
stop();
timerId = window.setInterval(refresh, intervalMs);
};
onUnmounted(stop);
return { start, stop };
};
Own loading and errors¶
The code that starts a request owns its loading and error state and resets both on every outcome:
- Set
loadingbefore the request and clear it after both success and failure. - Decide what the caller sees after a failure (an empty list, an error flag, a message) instead of leaving the previous result in place.
- Log or report the error; do not swallow it silently.
Apply only the latest response¶
When a request can be triggered again before the previous one finishes, such as search-as-you-type, an older response must not overwrite a newer one. Use createLatestRequestRunner from shared/utils/createLatestRequestRunner.ts instead of writing a new sequence counter:
- Create one runner per independent request stream and call it with
task,onLatest, and an optionalonError. onLatestandonErrorrun only for the most recent call; superseded results and errors are ignored (errors are still logged).- The runner resolves to
truewhen that call was the latest. Clearloadingonly then, so a stale response does not end the loading state of a newer request. - Call
runLatest.invalidate()when the state is reset or its owner is disposed without a new request. Otherwise a request still in flight fills the cleared state again.
const runLatest = createLatestRequestRunner();
const searchBookmarks = async (query: string) => {
loading.value = true;
const isLatest = await runLatest({
task: () => bookmarkApi.search(query),
onLatest: result => {
bookmarks.value = result;
},
onError: () => {
bookmarks.value = [];
},
});
if (isLatest) {
loading.value = false;
}
};
const reset = () => {
runLatest.invalidate();
bookmarks.value = [];
loading.value = false;
};
The example also shows loading ownership, the empty-list fallback after an error, and the reset.