← Back to Tutorials

Vue Composables

Build custom hooks for reusable logic. Authentication, API calls, form handling.

What are Composables?

Composables are functions that use Composition API to encapsulate and reuse stateful logic. They're Vue's version of React hooks.

Creating a Composable

import { ref, onUnmounted } from 'vue'

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

  const fetchData = async () => {
    loading.value = true
    try {
      data.value = await fetch(url).then(r => r.json())
    } catch (err) {
      error.value = err
    } finally {
      loading.value = false
    }
  }

  return { data, error, loading, fetchData }
}

Using a Composable

const { data, loading, fetchData } = useFetch('/api/users')
fetchData()

Key takeaways

  • Composables encapsulate reusable logic
  • Use them for cross-cutting concerns
  • They're composable and testable
  • Cleaner than mixins or provide/inject