[{"data":1,"prerenderedAt":14},["ShallowReactive",2],{"post-vue-composition-api-patterns":3},{"_path":4,"title":5,"description":6,"date":7,"tags":8,"readingTime":12,"body":13},"\u002Fblog\u002Fvue-composition-api-patterns\u002F","Practical Vue Composition API Patterns","Reusable patterns for composables, shared state, and cleaner component logic in Vue 3.","2026-06-28",[9,10,11],"vue","javascript","frontend",2,"# Practical Vue Composition API Patterns\n\nThe Composition API shines when logic grows beyond a single component. Here are patterns I reach for often on Vue and Nuxt projects.\n\n## Extract early, keep it focused\n\nIf a piece of state and its handlers appear in more than one place—or the `\u003Cscript setup>` block gets hard to scan—move it into a composable:\n\n```javascript\n\u002F\u002F composables\u002FuseToggle.js\nexport function useToggle(initial = false) {\n  const on = ref(initial);\n  const toggle = () => { on.value = !on.value; };\n  const set = (value) => { on.value = Boolean(value); };\n  return { on, toggle, set };\n}\n```\n\nKeep composables small. One concern per file beats a mega-`useApp` that does everything.\n\n## Prefer explicit returns\n\nReturn only what the consumer needs. That keeps the API clear and makes refactors safer:\n\n```javascript\nexport function useFetchPosts() {\n  const posts = ref([]);\n  const pending = ref(false);\n  const error = ref(null);\n\n  async function load() {\n    pending.value = true;\n    error.value = null;\n    try {\n      posts.value = await $fetch('\u002Fblog-posts.json');\n    } catch (e) {\n      error.value = e;\n    } finally {\n      pending.value = false;\n    }\n  }\n\n  return { posts, pending, error, load };\n}\n```\n\n## Shared state without a global store\n\nFor light cross-component state, a module-level `ref` inside a composable is enough:\n\n```javascript\nconst theme = ref('system');\n\nexport function useTheme() {\n  function setTheme(next) {\n    theme.value = next;\n  }\n  return { theme, setTheme };\n}\n```\n\nReach for Pinia when you need persistence, DevTools, or many consumers with complex mutations.\n\n## Wrap-up\n\nComposition API patterns are less about cleverness and more about boundaries: extract early, return explicitly, and share state only when it earns its keep.",1784110285915]