Advanced

Composables

Extract and reuse stateful logic across components with Vue composables.

What are Composables?

Composables are functions that encapsulate and reuse stateful logic. They're Vue's answer to React's custom hooks.

A composable:

  • Is a regular JavaScript function
  • Uses the Composition API internally
  • Conventionally starts with "use" (e.g., useFetch, useLocalStorage)
  • Returns reactive state and methods

Benefits

  • Extract complex logic from components
  • Reuse across multiple components
  • Easy to test in isolation
  • Better code organization

Example

javascript
// composables/useFetch.js
import { ref, watchEffect } from 'vue';

export function useFetch(url) {
  const data = ref(null);
  const error = ref(null);
  const loading = ref(true);

  watchEffect(async () => {
    loading.value = true;
    error.value = null;
    try {
      const res = await fetch(url.value ?? url);
      data.value = await res.json();
    } catch (e) {
      error.value = e;
    } finally {
      loading.value = false;
    }
  });

  return { data, error, loading };
}

// composables/useLocalStorage.js
import { ref, watch } from 'vue';

export function useLocalStorage(key, defaultValue) {
  const stored = localStorage.getItem(key);
  const value = ref(stored ? JSON.parse(stored) : defaultValue);

  watch(value, (newVal) => {
    localStorage.setItem(key, JSON.stringify(newVal));
  }, { deep: true });

  return value;
}

// Using composables in a component
<script setup>
import { useFetch } from '@/composables/useFetch';
import { useLocalStorage } from '@/composables/useLocalStorage';

const { data: users, loading, error } = useFetch('/api/users');
const theme = useLocalStorage('theme', 'light');
</script>
Try it yourself — JAVASCRIPT