Vue · Senior · Question 8 of 75
How do you share one instance of a composable's state across all components that use it?
export const useOnlineStatus = createSharedComposable(() => {
const online = ref(navigator.onLine);
useEventListener(window, "online", () => (online.value = true));
return { online };
});- ✓Correct answer: Wrap it with a shared-composable helper that runs it once in an
effectScopeand disposes it when no subscribers remain - 2Call the composable in
main.tsand store it onwindow - 3Composables always share state automatically
Explanation
Each normal call creates new state and listeners. VueUse's createSharedComposable counts subscribers and stops the scope when the last component unmounts.