KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
🖖

Vue

Topic Hub & Articles

Vue Intro

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Get Started

10 min

Vue Directives

10 min

Vue Events

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Forms

10 min

Vue Components

10 min

Vue Props

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Methods

10 min

Vue Computed Properties

10 min

Vue Watchers

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Class and Style Bindings

10 min

Vue Conditional Rendering

10 min

Vue List Rendering

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Template Syntax

10 min

Vue Teleport

10 min

Vue Suspense

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Transitions

10 min

Vue Mixins

10 min

Vue Custom Directives

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Plugins

10 min

Vue Slots

10 min

Vue Provide / Inject

10 min

Recap Quiz

Gated

Milestone Assessment

Vue Dynamic Components

10 min

Vue Async Components

10 min

Composition API Intro

10 min

Recap Quiz

Gated

Milestone Assessment

ref vs reactive

10 min

Lifecycle Hooks

10 min

Dependency Injection

10 min

Recap Quiz

Gated

Milestone Assessment

Computed and Watch

10 min

Template Refs

10 min

Composable Functions

10 min

Script Setup

10 min

Progress
0%

0 / 32 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
VueVue Composition API
Lesson

Composable Functions

10 min reading
Free Course

Composable Functions: Sharing Stateful Logic in Vue 3

A Vue composable is a function that uses the Composition API to package and reuse stateful logic across multiple components. Unlike plain utility helpers such as formatDate(), composables manage reactive ref state, watchers, and lifecycle hooks.

By convention, every composable function name starts with use, such as useFetch, useMouse, or useDebounce. This makes it immediately obvious where reactive state comes from inside any <script setup> block.

flowchart TD
    Comp["useFetch(urlSource)"] --> State["data, error, isLoading refs"]
    State --> CardA["PostCard.vue (own state instance)"]
    State --> CardB["UserCard.vue (own state instance)"]

Core Rules for Writing Composables

  • Name with use Prefix: Follow useFeatureName so developers recognize Composition API hooks at a glance.
  • Accept Refs or Getters with toValue(): Using toValue(urlSource) (Vue 3.3+) lets callers pass a plain string, a ref, or a () => ... getter function.
  • Return Plain Objects of Refs: Returning { data, error, isLoading } lets callers destructure cleanly without losing reactivity.

Practical Composable Function Example

Here is a reusable src/composables/useFetch.js composable that re-fetches automatically whenever a reactive URL getter changes.

import { ref, watchEffect, toValue } from 'vue';

export function useFetch(urlSource) {
  const data = ref(null);
  const error = ref(null);
  const isLoading = ref(true);

  async function fetchData() {
    const url = toValue(urlSource);
    isLoading.value = true;
    error.value = null;

    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      data.value = await res.json();
    } catch (err) {
      error.value = err.message;
    } finally {
      isLoading.value = false;
    }
  }

  watchEffect(() => {
    fetchData();
  });

  return { data, error, isLoading, refetch: fetchData };
}

Consume useFetch inside any component's <script setup> block. Each component instance gets its own isolated reactive state.

<script setup>
import { ref } from 'vue';
import { useFetch } from './composables/useFetch';

const postId = ref(1);
const { data: post, error, isLoading } = useFetch(
  () => `https://jsonplaceholder.typicode.com/posts/${postId.value}`
);
</script>

<template>
  <div class="post-viewer">
    <button @click="postId++">Next Post (ID: {{ postId }})</button>

    <p v-if="isLoading">Loading post...</p>
    <p v-else-if="error" class="error">Error: {{ error }}</p>
    <article v-else-if="post">
      <h3>{{ post.title }}</h3>
      <p>{{ post.body }}</p>
    </article>
  </div>
</template>

Common Mistakes

  • Returning a reactive() Object from a Composable: If a caller destructures const { data } = useFetch(...) from a reactive object, reactivity breaks. Always return a plain object holding ref values.
  • Calling Composables Inside setTimeout or Event Clicks: Composables that register onMounted or watchEffect must be called synchronously at the top level of <script setup>.
  • Creating Accidental Global State: Putting const data = ref(null) outside export function useFetch() shares one ref across every component instance. Keep per-instance refs inside the composable function body.

Frequently Asked Questions

Do multiple components calling the same composable share state?

No. Each call to useFetch() creates fresh ref instances for that component. If you actually want shared global state, use Pinia or declare state outside the function intentionally.

Where should composable files live in a Vue 3 project?

Place shared composables in src/composables/ (for example src/composables/useFetch.js), and keep feature-specific composables near the components that use them.

Can I use VueUse instead of writing common composables myself?

Yes. VueUse is a well-tested collection of Vue 3 composables like useLocalStorage, useDebounceFn, and useMediaQuery.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Related Developer Tools & Topic Hub

Vue Topic Hub
JSON Formatter
Validate and format JSON payloads
HTML Formatter
Format HTML templates
CSS Formatter
Clean and format stylesheets
All Vue Articles
Deep-dive guides, tips & discussions
PreviousTemplate Refs
Continue JourneyNext: Script Setup

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum