Edit 4

In Vue 3, composables are reusable functions that use the Composition API to encapsulate and share stateful logic across components.

They’re called “composables” because they let you compose functionality into your components without relying on mixins or large inheritance chains.



🧩 What a Composable Is

A composable is simply a function that:

  • Uses Composition API features like ref, reactive, computed, or watch.

  • Returns reactive data or methods that can be used in Vue components.

Example:


// useCounter.js import { ref } from 'vue' export function useCounter() { const count = ref(0) const increment = () => count.value++ const decrement = () => count.value-- return { count, increment, decrement } }

Then in a component:


<script setup> import { useCounter } from './useCounter' const { count, increment, decrement } = useCounter() </script> <template> <div> <p>{{ count }}</p> <button @click="increment">+</button> <button @click="decrement">-</button> </div> </template>


💡 Why Use Composables

They help you:

  • Reuse logic (e.g., fetching data, form handling, timers).

  • Organize code better than with mixins (no name conflicts, clear dependencies).

  • Test logic more easily (they’re plain JS functions).



🏗 Common Examples of Composables

  • useFetch – for data fetching with loading and error states.

  • useLocalStorage – sync reactive data with localStorage.

  • useDarkMode – toggle between light and dark themes.

  • useForm – manage reactive form data and validation.



🧠 Key Takeaways

  • Composables are not Vue-specific syntax—they’re just plain JavaScript functions that follow Vue’s Composition API pattern.

  • They’re usually stored in a /composables or /hooks directory.

  • Naming convention: prefix with use (e.g., useUser, useAuth, useMouse).