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 };
});

Explanation

Each normal call creates new state and listeners. VueUse's createSharedComposable counts subscribers and stops the scope when the last component unmounts.

Further reading

Problem with a question

Vue · Senior · question 8

Test yourself

Take the Vue · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz